Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • 1000i100-test
  • 105_gitlab_container_registry
  • cgeek/issue-297-cpu
  • ci_cache
  • debug/podman
  • elois-compose-metrics
  • elois-duniter-storage
  • elois-smoldot
  • feature/dc-dump
  • feature/distance-rule
  • feature/show_milestone
  • fix-252
  • fix_picked_up_file_in_runtime_release
  • gdev-800-tests
  • hugo-release/runtime-701
  • hugo-tmp-dockerfile-cache
  • hugo/195-doc
  • hugo/195-graphql-schema
  • hugo/distance-precompute
  • hugo/endpoint-gossip
  • hugo/tmp-0.9.1
  • master
  • network/gdev-800
  • network/gdev-802
  • network/gdev-803
  • network/gdev-900
  • network/gtest-1000
  • pini-check-password
  • release/client-800.2
  • release/hugo-chainspec-gdev5
  • release/poka-chainspec-gdev5
  • release/poka-chainspec-gdev5-pini-docker
  • release/runtime-100
  • release/runtime-200
  • release/runtime-300
  • release/runtime-400
  • release/runtime-401
  • release/runtime-500
  • release/runtime-600
  • release/runtime-700
  • release/runtime-701
  • release/runtime-800
  • runtime/gtest-1000
  • tests/distance-with-oracle
  • tuxmain/anonymous-tx
  • tuxmain/benchmark-distance
  • tuxmain/fix-change-owner-key
  • update-docker-compose-rpc-squid-names
  • upgradable-multisig
  • gdev-800
  • gdev-800-0.8.0
  • gdev-802
  • gdev-803
  • gdev-900-0.10.0
  • gdev-900-0.10.1
  • gdev-900-0.9.0
  • gdev-900-0.9.1
  • gdev-900-0.9.2
  • gtest-1000
  • gtest-1000-0.11.0
  • gtest-1000-0.11.1
  • runtime-100
  • runtime-101
  • runtime-102
  • runtime-103
  • runtime-104
  • runtime-105
  • runtime-200
  • runtime-201
  • runtime-300
  • runtime-301
  • runtime-302
  • runtime-303
  • runtime-400
  • runtime-401
  • runtime-500
  • runtime-600
  • runtime-700
  • runtime-701
  • runtime-800
  • runtime-800-backup
  • runtime-800-bis
  • runtime-801
  • v0.1.0
  • v0.2.0
  • v0.3.0
  • v0.4.0
  • v0.4.1
88 results

Target

Select target project
  • nodes/rust/duniter-v2s
  • llaq/lc-core-substrate
  • pini-gh/duniter-v2s
  • vincentux/duniter-v2s
  • mildred/duniter-v2s
  • d0p1/duniter-v2s
  • bgallois/duniter-v2s
  • Nicolas80/duniter-v2s
8 results
Select Git revision
  • archive_upgrade_polkadot_v0.9.42
  • david-wot-scenarios-cucumber
  • distance
  • elois-ci-binary-release
  • elois-compose-metrics
  • elois-duniter-storage
  • elois-fix-85
  • elois-fix-idty-post-genesis
  • elois-fix-sufficients-change-owner-key
  • elois-opti-cert
  • elois-remove-renewable-period
  • elois-revoc-with-old-key
  • elois-rework-certs
  • elois-smish-members-cant-change-or-rem-idty
  • elois-smoldot
  • elois-substrate-v0.9.23
  • elois-technical-commitee
  • hugo-gtest
  • hugo-remove-duniter-account
  • hugo-rework-genesis
  • hugo-tmp
  • jrx/workspace_tomls
  • master
  • no-bootnodes
  • pallet-benchmark
  • release/poka-chainspec-gdev5
  • release/poka-chainspec-gdev5-pini-docker
  • release/runtime-100
  • release/runtime-200
  • release/runtime-300
  • release/runtime-400
  • test-gen-new-owner-key-msg
  • ts-types
  • ud-time-64
  • upgrade_polkadot_v0.9.42
  • runtime-100
  • runtime-101
  • runtime-102
  • runtime-103
  • runtime-104
  • runtime-105
  • runtime-200
  • runtime-201
  • runtime-300
  • runtime-301
  • runtime-302
  • runtime-303
  • runtime-400
  • v0.1.0
  • v0.2.0
  • v0.3.0
  • v0.4.0
52 results
Show changes
Showing
with 1580 additions and 1395 deletions
File added
No preview for this file type
[package]
name = "weight-analyzer"
authors.workspace = true
edition.workspace = true
homepage.workspace = true
license.workspace = true
repository.workspace = true
version.workspace = true
[lib]
name = "weightanalyzer"
path = "src/lib.rs"
[dependencies]
convert_case = { workspace = true }
glob = { workspace = true }
serde = { workspace = true, features = ["derive"] }
subweight-core = { workspace = true }
[features]
std = []
use convert_case::{Case, Casing};
use glob::glob;
use serde::Serialize;
use std::{collections::HashMap, ops::Div, path::Path};
use subweight_core::{
parse::{
overhead::Weight,
pallet::{ChromaticExtrinsic, ComponentRange},
storage::Weights,
},
scope::Scope,
term::Term,
};
// Substrate default maximum weight of a block in nanoseconds.
// Since the maximum block weight is one-third of the execution time,
// it corresponds to a block time of 6 seconds.
const MAX_BLOCK_WEIGHT_NS: f64 = 2_000_000_000_000.;
pub struct MaxBlockWeight(f64);
impl Default for MaxBlockWeight {
fn default() -> Self {
MaxBlockWeight(MAX_BLOCK_WEIGHT_NS)
}
}
impl Div<&MaxBlockWeight> for f64 {
type Output = Self;
fn div(self, max_block_weight: &MaxBlockWeight) -> Self::Output {
self / max_block_weight.0
}
}
impl MaxBlockWeight {
pub fn new<T: Into<f64>>(value: T) -> Self {
MaxBlockWeight(value.into())
}
}
#[derive(Clone, Debug, Serialize)]
pub struct WeightInfo {
pub weight: u128,
pub relative_weight: f64,
}
/// Returns a HashMap <pallet_name, <extrinsic_name, weigh_info>>
/// of the analyzed weights.
///
/// # Arguments
///
/// * `folder_path` - A Path to a folder where the weight files are stored.
/// `paritydb_weights.rs` is mandatory and pallet weights should start by
/// `pallet_`.
/// * `max_block_weight` - The maximal weight of a block.
///
/// # Examples
///
/// ```
/// use weightanalyzer::analyze_weight;
/// use std::path::Path;
/// use weightanalyzer::MaxBlockWeight;
/// let weight_by_pallet = analyze_weight(Path::new("../../runtime/gdev/src/weights/"), &MaxBlockWeight::default());
/// println!("{:?}", weight_by_pallet);
/// ```
pub fn analyze_weight(
folder_path: &Path,
max_block_weight: &MaxBlockWeight,
) -> Result<HashMap<String, HashMap<String, WeightInfo>>, String> {
let pallet_weights = read_pallet_weight(folder_path)?;
let db_weight = read_db_weight(folder_path)?;
let overhead_weights = read_overhead_weight(folder_path)?;
// Initialize scope with db weights
let mut scope = Scope::from_substrate();
scope = scope.with_storage_weights(db_weight.weights.read, db_weight.weights.write);
process(pallet_weights, scope, max_block_weight, &overhead_weights)
}
fn read_pallet_weight(folder_path: &Path) -> Result<Vec<Vec<ChromaticExtrinsic>>, String> {
let mut parsed_files = Vec::new();
for path in glob(folder_path.join("*").to_str().expect("Invalid pallet path"))
.expect("Invalid pallet pattern")
.filter_map(Result::ok)
{
let file = subweight_core::parse::pallet::parse_file(&path);
if let Ok(file) = file {
parsed_files.push(file);
}
}
if parsed_files.is_empty() {
return Err("No pallet found".into());
}
Ok(parsed_files)
}
fn read_db_weight(folder_path: &Path) -> Result<Weights, String> {
subweight_core::parse::storage::parse_file(folder_path.join("paritydb_weights.rs").as_path())
}
fn read_overhead_weight(folder_path: &Path) -> Result<Weight, String> {
subweight_core::parse::overhead::parse_file(folder_path.join("extrinsic_weights.rs").as_path())
}
fn evaluate_weight(
extrinsic: ChromaticExtrinsic,
scope: &mut Scope<Term<u128>>,
max_block_weight: &MaxBlockWeight,
overhead: &Weight,
) -> Result<(String, String, WeightInfo), String> {
// Extend the scope with the maximum value of the complexity parameter.
if let Some(params) = extrinsic.comp_ranges {
params
.iter()
.for_each(|(key, val): (&String, &ComponentRange)| {
scope.put_var(key.as_str(), Term::Scalar(val.max.into()));
});
}
// Evaluate the weight
let mut weight = extrinsic
.term
.simplify(subweight_core::Dimension::Time)
.expect("Can't evaluate")
.eval(scope)?;
// Add base extrinsic overhead
if let Weight::ExtrinsicBase(i) = overhead {
weight += i
.simplify(subweight_core::Dimension::Time)
.expect("Can't evaluate")
.eval(scope)?;
}
let relative_weight = (weight as f64) / max_block_weight * 100.;
Ok((
extrinsic
.pallet
.to_case(Case::Title)
.replace("Pallet", "")
.replace(".rs", "")
.chars()
.filter(|c| !c.is_whitespace())
.collect(),
extrinsic.name,
WeightInfo {
weight,
relative_weight,
},
))
}
fn process(
pallet_weights: Vec<Vec<ChromaticExtrinsic>>,
mut scope: Scope<Term<u128>>,
max_block_weight: &MaxBlockWeight,
overhead: &Weight,
) -> Result<HashMap<String, HashMap<String, WeightInfo>>, String> {
let mut weight_by_pallet: HashMap<String, HashMap<String, WeightInfo>> = HashMap::new();
for i in pallet_weights {
for j in i {
let (pallet, extrinsic, weight) =
evaluate_weight(j, &mut scope, max_block_weight, overhead)?;
if let Some(i) = weight_by_pallet.get_mut(&pallet) {
i.insert(extrinsic, weight);
} else {
weight_by_pallet.insert(pallet, HashMap::from([(extrinsic, weight)]));
}
}
}
Ok(weight_by_pallet)
}
#[cfg(test)]
mod tests {
use crate::{analyze_weight, MaxBlockWeight};
use std::path::Path;
#[test]
fn should_works() {
let weight_by_pallet = analyze_weight(
Path::new("../../runtime/gdev/src/weights/"),
&MaxBlockWeight::default(),
);
assert!(
weight_by_pallet
.clone()
.unwrap()
.get("Balances")
.unwrap()
.len()
== 10
); // 8 extrinsics in pallet
println!("{:?}", weight_by_pallet); // cargo test -- --nocapture
}
#[test]
#[should_panic]
fn should_not_works() {
let _ = analyze_weight(Path::new(""), &MaxBlockWeight::default()).unwrap();
}
}
......@@ -2,7 +2,7 @@
Duniter client can run several runtimes.
- ĞDev is for development purpose
- ĞTest is to prepare Ğ1 migration and test features before deploying on Ǧ1
- Ğ1 is the production currency
- [ĞDev](https://doc-duniter-org.ipns.pagu.re/gdev_runtime/index.html) is for development purpose
- [ĞTest](https://doc-duniter-org.ipns.pagu.re/gtest_runtime/index.html) is to prepare Ğ1 migration and test features before deploying on Ǧ1
- [Ğ1](https://doc-duniter-org.ipns.pagu.re/g1_runtime/index.html) is the production currency
[package]
name = 'common-runtime'
description = 'Common code shared between all runtimes'
license = 'GPL-3.0-only'
version = '0.8.0-dev'
authors = ['Axiom-Team Developers <https://axiom-team.fr>']
edition = "2021"
name = "common-runtime"
description = "Common code shared between all runtimes"
license.workspace = true
authors.workspace = true
edition.workspace = true
version.workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[features]
default = ["std"]
no_std = []
constant-fees = []
runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
'frame-support/runtime-benchmarks',
'frame-system-benchmarking/runtime-benchmarks',
'frame-system/runtime-benchmarks',
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"pallet-authority-members/runtime-benchmarks",
"pallet-babe/runtime-benchmarks",
'pallet-balances/runtime-benchmarks',
'pallet-certification/runtime-benchmarks',
'pallet-duniter-wot/runtime-benchmarks',
'pallet-identity/runtime-benchmarks',
'pallet-membership/runtime-benchmarks',
'pallet-multisig/runtime-benchmarks',
'pallet-proxy/runtime-benchmarks',
'pallet-treasury/runtime-benchmarks',
'pallet-upgrade-origin/runtime-benchmarks',
'sp-runtime/runtime-benchmarks',
"pallet-balances/runtime-benchmarks",
"pallet-certification/runtime-benchmarks",
"pallet-distance/runtime-benchmarks",
"pallet-duniter-account/runtime-benchmarks",
"pallet-duniter-wot/runtime-benchmarks",
"pallet-identity/runtime-benchmarks",
"pallet-membership/runtime-benchmarks",
"pallet-offences/runtime-benchmarks",
"pallet-provide-randomness/runtime-benchmarks",
"pallet-quota/runtime-benchmarks",
"pallet-smith-members/runtime-benchmarks",
"pallet-timestamp/runtime-benchmarks",
"pallet-transaction-payment/runtime-benchmarks",
"pallet-treasury/runtime-benchmarks",
"pallet-universal-dividend/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"sp-staking/runtime-benchmarks",
]
std = [
'codec/std',
'duniter-primitives/std',
'frame-support/std',
'frame-system/std',
'log/std',
'pallet-authority-members/std',
'pallet-babe/std',
'pallet-balances/std',
'pallet-certification/std',
'pallet-duniter-account/std',
'pallet-duniter-wot/std',
'pallet-grandpa/std',
'pallet-identity/std',
'pallet-membership/std',
'pallet-multisig/std',
'pallet-oneshot-account/std',
'pallet-provide-randomness/std',
'pallet-proxy/std',
'pallet-scheduler/std',
'pallet-timestamp/std',
'pallet-treasury/std',
'pallet-universal-dividend/std',
"codec/std",
"duniter-primitives/std",
"frame-benchmarking/std",
"frame-support/std",
"frame-system/std",
"pallet-authority-members/std",
"pallet-babe/std",
"pallet-balances/std",
"pallet-certification/std",
"pallet-distance/std",
"pallet-duniter-account/std",
"pallet-duniter-wot/std",
"pallet-identity/std",
"pallet-membership/std",
"pallet-offences/std",
"pallet-provide-randomness/std",
"pallet-quota/std",
"pallet-session/std",
"pallet-smith-members/std",
"pallet-timestamp/std",
"pallet-treasury/std",
"pallet-universal-dividend/std",
"scale-info/std",
"serde/std",
"serde_derive",
'sp-arithmetic/std',
'sp-core/std',
'sp-membership/std',
'sp-runtime/std',
'sp-std/std',
"sp-arithmetic/std",
"sp-consensus-babe/std",
"sp-core/std",
"sp-membership/std",
"sp-runtime/std",
"sp-staking/std",
"sp-weights/std",
]
try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
"pallet-authority-members/try-runtime",
"pallet-babe/try-runtime",
"pallet-grandpa/try-runtime",
"pallet-balances/try-runtime",
"pallet-certification/try-runtime",
"pallet-distance/try-runtime",
"pallet-duniter-account/try-runtime",
"pallet-duniter-wot/try-runtime",
"pallet-identity/try-runtime",
"pallet-membership/try-runtime",
"pallet-offences/try-runtime",
"pallet-provide-randomness/try-runtime",
"pallet-quota/try-runtime",
"pallet-session/try-runtime",
"pallet-smith-members/try-runtime",
"pallet-timestamp/try-runtime",
"pallet-transaction-payment/try-runtime",
"pallet-treasury/try-runtime",
"pallet-universal-dividend/try-runtime",
"sp-membership/try-runtime",
"sp-runtime/try-runtime",
]
[dependencies]
duniter-primitives = { path = '../../primitives/duniter', default-features = false }
pallet-authority-members = { path = '../../pallets/authority-members', default-features = false }
pallet-certification = { path = '../../pallets/certification', default-features = false }
pallet-duniter-account = { path = '../../pallets/duniter-account', default-features = false }
pallet-duniter-wot = { path = '../../pallets/duniter-wot', default-features = false }
pallet-identity = { path = '../../pallets/identity', default-features = false }
pallet-membership = { path = '../../pallets/membership', default-features = false }
pallet-oneshot-account = { path = '../../pallets/oneshot-account', default-features = false }
pallet-provide-randomness = { path = '../../pallets/provide-randomness', default-features = false }
pallet-upgrade-origin = { path = '../../pallets/upgrade-origin', default-features = false }
pallet-universal-dividend = { path = '../../pallets/universal-dividend', default-features = false }
sp-membership = { path = '../../primitives/membership', default-features = false }
# Crates.io
codec = { package = "parity-scale-codec", version = "3.1.5", features = ["derive"], default-features = false }
log = { version = "0.4.14", default-features = false }
scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
serde = { version = "1.0.101", default-features = false }
serde_derive = { version = "1.0.101", optional = true }
smallvec = "1.6.1"
# Substrate
frame-support = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
frame-system = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
pallet-babe = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
pallet-balances = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
pallet-grandpa = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
pallet-multisig = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
pallet-proxy = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
pallet-scheduler = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
pallet-session = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
pallet-timestamp = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
pallet-treasury = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
sp-arithmetic = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
sp-consensus-babe = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
sp-core = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
sp-runtime = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
sp-std = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
# substrate benchmarks
frame-benchmarking = { git = "https://github.com/duniter/substrate", branch = 'duniter-substrate-v0.9.32', default-features = false, optional = true }
frame-system-benchmarking = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false, optional = true }
# TODO: there is a bad coupling in substrate that force to add this dependency
sp-staking = { git = 'https://github.com/duniter/substrate', branch = 'duniter-substrate-v0.9.32', default-features = false }
codec = { workspace = true, features = ["derive"] }
duniter-primitives = { workspace = true }
frame-benchmarking = { workspace = true }
frame-support = { workspace = true }
frame-system = { workspace = true }
pallet-authority-members = { workspace = true }
pallet-babe = { workspace = true }
pallet-balances = { workspace = true }
pallet-certification = { workspace = true }
pallet-distance = { workspace = true }
pallet-duniter-account = { workspace = true }
pallet-duniter-wot = { workspace = true }
pallet-identity = { workspace = true }
pallet-membership = { workspace = true }
pallet-offences = { workspace = true }
pallet-provide-randomness = { workspace = true }
pallet-quota = { workspace = true }
pallet-session = { workspace = true }
pallet-smith-members = { workspace = true }
pallet-timestamp = { workspace = true }
pallet-transaction-payment = { workspace = true }
pallet-treasury = { workspace = true }
pallet-universal-dividend = { workspace = true }
scale-info = { workspace = true, features = ["derive"] }
serde = { workspace = true }
smallvec = { workspace = true }
sp-arithmetic = { workspace = true }
sp-consensus-babe = { workspace = true }
sp-core = { workspace = true }
sp-membership = { workspace = true }
sp-runtime = { workspace = true }
sp-staking = { workspace = true }
sp-weights = { workspace = true }
......@@ -14,9 +14,12 @@
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
// This file is not formatted automatically due to the nested macro definition.
// It can be formatted by commenting out the last line, the first five lines,
// and then running `rustfmt` on `runtime/common/src/apis.rs`.
#[macro_export]
macro_rules! runtime_apis {
{$($custom:tt)*} => {
($($custom:tt)*) => {
impl_runtime_apis! {
$($custom)*
......@@ -73,10 +76,7 @@ macro_rules! runtime_apis {
) -> Option<()> {
let key_owner_proof = key_owner_proof.decode()?;
Babe::submit_unsigned_equivocation_report(
equivocation_proof,
key_owner_proof,
)
Babe::submit_unsigned_equivocation_report(equivocation_proof, key_owner_proof)
}
}
......@@ -89,7 +89,7 @@ macro_rules! runtime_apis {
Executive::execute_block(block)
}
fn initialize_block(header: &<Block as BlockT>::Header) {
fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
Executive::initialize_block(header)
}
}
......@@ -98,6 +98,14 @@ macro_rules! runtime_apis {
fn metadata() -> OpaqueMetadata {
OpaqueMetadata::new(Runtime::metadata().into())
}
fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
Runtime::metadata_at_version(version)
}
fn metadata_versions() -> Vec<u32> {
Runtime::metadata_versions()
}
}
impl sp_block_builder::BlockBuilder<Block> for Runtime {
......@@ -109,9 +117,7 @@ macro_rules! runtime_apis {
Executive::finalize_block()
}
fn inherent_extrinsics(
data: sp_inherents::InherentData,
) -> Vec<<Block as BlockT>::Extrinsic> {
fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
data.create_extrinsics()
}
......@@ -130,8 +136,7 @@ macro_rules! runtime_apis {
block_hash: <Block as BlockT>::Hash,
) -> TransactionValidity {
// Filtered calls should not enter the tx pool.
if !<Runtime as frame_system::Config>::BaseCallFilter::contains(&tx.function)
{
if !<Runtime as frame_system::Config>::BaseCallFilter::contains(&tx.function) {
return sp_runtime::transaction_validity::InvalidTransaction::Call.into();
}
Executive::validate_transaction(source, tx, block_hash)
......@@ -145,9 +150,7 @@ macro_rules! runtime_apis {
}
impl sp_session::SessionKeys<Block> for Runtime {
fn decode_session_keys(
encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
fn decode_session_keys(encoded: Vec<u8>) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
opaque::SessionKeys::decode_into_raw_public_keys(&encoded)
}
......@@ -192,8 +195,7 @@ macro_rules! runtime_apis {
}
}
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
for Runtime {
impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
fn query_info(
uxt: <Block as BlockT>::Extrinsic,
len: u32,
......@@ -207,64 +209,101 @@ macro_rules! runtime_apis {
) -> pallet_transaction_payment::FeeDetails<Balance> {
TransactionPayment::query_fee_details(uxt, len)
}
fn query_weight_to_fee(weight: Weight) -> Balance {
TransactionPayment::weight_to_fee(weight)
}
fn query_length_to_fee(length: u32) -> Balance {
TransactionPayment::length_to_fee(length)
}
}
impl pallet_duniter_account::DuniterAccountApi<Block, Balance> for Runtime {
fn estimate_cost(
uxt: <Block as BlockT>::Extrinsic,
) -> pallet_duniter_account::EstimatedCost<Balance> {
pallet_duniter_account::Pallet::<Runtime>::estimate_cost(uxt)
}
}
impl pallet_universal_dividend::UniversalDividendApi<Block, AccountId, Balance> for Runtime {
fn account_balances(account: AccountId) -> pallet_universal_dividend::AccountBalances<Balance> {
UniversalDividend::account_balances(&account)
}
}
impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
frame_support::genesis_builder_helper::build_state::<RuntimeGenesisConfig>(config)
}
fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
frame_support::genesis_builder_helper::get_preset::<RuntimeGenesisConfig>(id, |_| None)
}
fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
vec![]
}
}
#[cfg(feature = "try-runtime")]
impl frame_try_runtime::TryRuntime<Block> for Runtime where <Runtime as frame_system::Config>::BlockNumber: Clone + sp_std::fmt::Debug + sp_runtime::traits::AtLeast32BitUnsigned {
fn on_runtime_upgrade() -> (Weight, Weight) {
log::info!("try-runtime::on_runtime_upgrade.");
todo!()
// TODO solve the problem to uncomment this:
//let weight = Executive::try_runtime_upgrade().unwrap();
//(weight, BlockWeights::get().max_block)
impl frame_try_runtime::TryRuntime<Block> for Runtime {
fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
let weight = Executive::try_runtime_upgrade(checks).unwrap();
(weight, BlockWeights::get().max_block)
}
fn execute_block(
block: Block,
state_root_check: bool,
signature_check: bool,
select: frame_try_runtime::TryStateSelect,
) -> Weight {
todo!()
// TODO solve the problem to uncomment this:
//Executive::try_execute_block(block, state_root_check, select).expect("try_execute_block failed")
Executive::try_execute_block(block, state_root_check, signature_check, select)
.expect("execute-block failed")
}
}
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(extra: bool) -> (
fn benchmark_metadata(
extra: bool,
) -> (
Vec<frame_benchmarking::BenchmarkList>,
Vec<frame_support::traits::StorageInfo>,
) {
use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};
use frame_benchmarking::{list_benchmark, BenchmarkList, Benchmarking};
use frame_support::traits::StorageInfoTrait;
use frame_system_benchmarking::Pallet as SystemBench;
use frame_benchmarking::baseline::Pallet as Baseline;
use frame_system_benchmarking::{
extensions::Pallet as SystemExtensionsBench, Pallet as SystemBench,
};
use pallet_session_benchmarking::Pallet as SessionBench;
let mut list = Vec::<BenchmarkList>::new();
list_benchmarks!(list, extra);
let storage_info = AllPalletsWithSystem::storage_info();
return (list, storage_info)
return (list, storage_info);
}
fn dispatch_benchmark(
config: frame_benchmarking::BenchmarkConfig
) -> Result<
Vec<frame_benchmarking::BenchmarkBatch>,
sp_runtime::RuntimeString,
> {
use frame_benchmarking::{Benchmarking, BenchmarkBatch, TrackedStorageKey};
// Trying to add benchmarks directly to some pallets caused cyclic dependency issues.
// To get around that, we separated the benchmarks into its own crate.
use frame_system_benchmarking::Pallet as SystemBench;
use frame_benchmarking::baseline::Pallet as Baseline;
config: frame_benchmarking::BenchmarkConfig,
) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, scale_info::prelude::string::String> {
use frame_benchmarking::{baseline::Pallet as Baseline, BenchmarkBatch, Benchmarking};
use frame_support::traits::{TrackedStorageKey, WhitelistedStorageKeys};
use frame_system_benchmarking::{
extensions::Pallet as SystemExtensionsBench, Pallet as SystemBench,
};
use pallet_session_benchmarking::Pallet as SessionBench;
impl pallet_session_benchmarking::Config for Runtime {}
impl frame_system_benchmarking::Config for Runtime {}
impl frame_benchmarking::baseline::Config for Runtime {}
let whitelist: Vec<TrackedStorageKey> = vec![
/*let whitelist: Vec<TrackedStorageKey> = vec![
// Block Number
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),
// Total Issuance
......@@ -277,16 +316,17 @@ macro_rules! runtime_apis {
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),
// Treasury Account
hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95ecffd7b6c0f78751baa9d281e0bfa3a6d6f646c70792f74727372790000000000000000000000000000000000000000").to_vec().into(),
];
];*/
let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
let mut batches = Vec::<BenchmarkBatch>::new();
let params = (&config, &whitelist);
add_benchmarks!(params, batches);
if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
Ok(batches)
}
if batches.is_empty() {
return Err("Benchmark not found for this pallet.".into());
}
Ok(batches)
}
};
}
}};}
// Copyright 2021 Axiom-Team
//
// This file is part of Duniter-v2S.
//
// Duniter-v2S is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Duniter-v2S is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
#![cfg(feature = "runtime-benchmarks")]
#[macro_export]
macro_rules! benchmarks_config {
() => {
#[macro_use]
extern crate frame_benchmarking;
pub use pallet_collective::RawOrigin;
type WorstOrigin = RawOrigin<AccountId, TechnicalCommitteeInstance>;
mod benches {
define_benchmarks!(
[pallet_certification, Certification]
[pallet_distance, Distance]
[pallet_oneshot_account, OneshotAccount]
[pallet_universal_dividend, UniversalDividend]
[pallet_provide_randomness, ProvideRandomness]
[pallet_upgrade_origin, UpgradeOrigin]
[pallet_duniter_account, Account]
[pallet_quota, Quota]
[pallet_identity, Identity]
[pallet_membership, Membership]
[pallet_smith_members, SmithMembers]
[pallet_authority_members, AuthorityMembers]
// Substrate
[frame_system_extensions, SystemExtensionsBench::<Runtime>]
[pallet_balances, Balances]
[frame_benchmarking::baseline, Baseline::<Runtime>]
[pallet_collective, TechnicalCommittee]
[pallet_session, SessionBench::<Runtime>]
[pallet_im_online, ImOnline]
[pallet_sudo, Sudo]
[pallet_multisig, Multisig]
[pallet_preimage, Preimage]
[pallet_proxy, Proxy]
[pallet_scheduler, Scheduler]
[frame_system, SystemBench::<Runtime>]
[pallet_timestamp, Timestamp]
[pallet_transaction_payment, TransactionPayment]
[pallet_treasury, Treasury]
[pallet_utility, Utility]
);
}
};
}
......@@ -15,17 +15,13 @@
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
use crate::{Balance, BlockNumber};
use frame_support::weights::Weight;
use sp_runtime::Perbill;
pub use crate::weights::paritydb_weights::constants::ParityDbWeight as DbWeight;
/// This determines the average expected block time that we are targeting.
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
/// up by `pallet_babe` to implement `fn slot_duration()`.
///
/// Change this to adjust the block time.
// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
// up by `pallet_babe` to implement `fn slot_duration()`.
// Change this to adjust the block time.
pub const MILLISECS_PER_BLOCK: u64 = 6000;
pub const SECS_PER_BLOCK: u64 = MILLISECS_PER_BLOCK / 1_000;
......@@ -44,7 +40,7 @@ pub const YEARS: BlockNumber = (SECS_PER_YEAR / SECS_PER_BLOCK) as BlockNumber;
// 1 in 4 blocks (on average, not counting collisions) will be primary babe blocks.
pub const PRIMARY_PROBABILITY: (u64, u64) = (1, 4);
/// The BABE epoch configuration at genesis.
// The BABE epoch configuration at genesis.
pub const BABE_GENESIS_EPOCH_CONFIG: sp_consensus_babe::BabeEpochConfiguration =
sp_consensus_babe::BabeEpochConfiguration {
c: PRIMARY_PROBABILITY,
......@@ -61,32 +57,3 @@ pub const fn deposit(items: u32, bytes: u32) -> Balance {
// Maximal weight proportion of normal extrinsics per block
pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
// WEIGHTS CONSTANTS //
// Block weights limits
pub fn block_weights(
expected_block_weight: Weight,
normal_ratio: sp_arithmetic::Perbill,
) -> frame_system::limits::BlockWeights {
let base_weight = DbWeight::get().reads(1) + DbWeight::get().writes(1);
let normal_weight = normal_ratio * expected_block_weight;
frame_system::limits::BlockWeights::builder()
.base_block(crate::weights::block_weights::BlockExecutionWeight::get())
.for_class(frame_support::dispatch::DispatchClass::all(), |weights| {
weights.base_extrinsic = base_weight;
})
.for_class(frame_support::dispatch::DispatchClass::Normal, |weights| {
weights.max_total = normal_weight.into();
})
.for_class(
frame_support::dispatch::DispatchClass::Operational,
|weights| {
weights.max_total = expected_block_weight.into();
weights.reserved = (expected_block_weight - normal_weight).into();
},
)
.avg_block_initialization(sp_arithmetic::Perbill::from_percent(10))
.build()
.expect("Fatal error: invalid BlockWeights configuration")
}
......@@ -14,11 +14,8 @@
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
use super::AccountId;
use frame_support::pallet_prelude::*;
use scale_info::TypeInfo;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
#[macro_export]
macro_rules! declare_session_keys {
......@@ -34,93 +31,49 @@ macro_rules! declare_session_keys {
pub authority_discovery: AuthorityDiscovery,
}
}
#[derive(Clone, codec::Decode, Debug, codec::Encode, Eq, PartialEq)]
pub struct SessionKeysWrapper(pub SessionKeys);
impl From<SessionKeysWrapper> for SessionKeys {
fn from(keys_wrapper: SessionKeysWrapper) -> SessionKeys {
keys_wrapper.0
}
}
impl scale_info::TypeInfo for SessionKeysWrapper {
type Identity = [u8; 128];
fn type_info() -> scale_info::Type {
Self::Identity::type_info()
}
}
}
}
}
#[cfg_attr(feature = "std", derive(Deserialize, Serialize))]
#[derive(Clone, Encode, Decode, Default, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[derive(
Clone,
Encode,
Decode,
DecodeWithMemTracking,
Default,
Eq,
PartialEq,
RuntimeDebug,
TypeInfo,
MaxEncodedLen,
serde::Deserialize,
serde::Serialize,
)]
pub struct IdtyData {
/// number of the first claimable UD
pub first_eligible_ud: pallet_universal_dividend::FirstEligibleUd,
}
#[cfg(feature = "std")]
impl IdtyData {
pub fn new() -> Self {
Self {
first_eligible_ud: pallet_universal_dividend::FirstEligibleUd::min(),
}
}
}
impl From<IdtyData> for pallet_universal_dividend::FirstEligibleUd {
fn from(idty_data: IdtyData) -> Self {
idty_data.first_eligible_ud
}
}
pub struct NewOwnerKeySigner(sp_core::sr25519::Public);
impl sp_runtime::traits::IdentifyAccount for NewOwnerKeySigner {
type AccountId = crate::AccountId;
fn into_account(self) -> crate::AccountId {
<[u8; 32]>::from(self.0).into()
}
}
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub struct NewOwnerKeySignature(sp_core::sr25519::Signature);
impl sp_runtime::traits::Verify for NewOwnerKeySignature {
type Signer = NewOwnerKeySigner;
fn verify<L: sp_runtime::traits::Lazy<[u8]>>(&self, msg: L, signer: &crate::AccountId) -> bool {
use sp_core::crypto::ByteArray as _;
match sp_core::sr25519::Public::from_slice(signer.as_ref()) {
Ok(signer) => self.0.verify(msg, &signer),
Err(()) => false,
}
}
}
#[cfg_attr(feature = "std", derive(Deserialize, Serialize))]
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo)]
pub struct SmithsMembershipMetaData<SessionKeysWrapper> {
pub owner_key: AccountId,
pub p2p_endpoint: sp_runtime::RuntimeString,
pub session_keys: SessionKeysWrapper,
}
impl<SessionKeysWrapper> Default for SmithsMembershipMetaData<SessionKeysWrapper> {
fn default() -> Self {
unreachable!()
}
}
impl<SessionKeysWrapper> sp_membership::traits::Validate<AccountId>
for SmithsMembershipMetaData<SessionKeysWrapper>
{
fn validate(&self, who: &AccountId) -> bool {
&self.owner_key == who
}
}
#[cfg_attr(feature = "std", derive(Deserialize, Serialize))]
#[derive(
Encode, Decode, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, RuntimeDebug, TypeInfo,
Encode,
Decode,
DecodeWithMemTracking,
Default,
Clone,
Copy,
PartialEq,
Eq,
PartialOrd,
Ord,
RuntimeDebug,
TypeInfo,
serde::Deserialize,
serde::Serialize,
)]
pub struct ValidatorFullIdentification;
......@@ -14,34 +14,282 @@
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
/// In our deployed fee model, users will not pay any fees if blockchain usage remains below a
/// specified threshold, and fees are applied based on transaction weight and length once this
/// threshold is exceeded, helping to prevent spamming attacks.
///
/// When the current block's weight and length are below the targeted thresholds, no fees are charged,
/// as the weight-to-fee conversion results in zero. Once the block's weight and length exceed these
/// targets, the weight-to-fee conversion maps BASE_EXTRINSIC_WEIGHT_COST to a base extrinsic weight.
/// Additionally, a fee is applied based on the length of the extrinsic and is mapped affinely:
/// 2_000 (20G) corresponds to an extrinsic length of BYTES_PER_UNIT*10 plus the BASE_EXTRINSIC_LENGTH_COST and will be applied only if the extrinsic
/// exceeds MAX_EXTRINSIC_LENGTH bytes or if the block target in weight or length is surpassed.
///
/// To further deter abuse, if the previous block's weight or length the target thresholds,
/// the chain increases the fees by multiplying the transaction weight with a `FeeMultiplier`. For each
/// consecutive block that exceeds the targets, this multiplier increases by one. If the targets are
/// not reached, the multiplier decreases by one. The `FeeMultiplier` ranges from 1 (normal usage) to
/// `MaxMultiplier`, where heavy usage causes a number `MaxMultiplier` of consecutive blocks to exceed targets.
///
/// For testing purposes, a simplified, human-predictable weight system is used. This test model sets
/// a constant `weight_to_fee` of 1 and a `length_to_fee` of 0, making each extrinsic cost 2 (2cG),
/// and can be activated with the #[cfg(feature = "constant-fees")] feature.
pub use frame_support::weights::{Weight, WeightToFee};
use sp_arithmetic::traits::{BaseArithmetic, One, Unsigned};
use pallet_transaction_payment::{Multiplier, MultiplierUpdate};
use scale_info::prelude::marker::PhantomData;
use sp_arithmetic::traits::{BaseArithmetic, Unsigned};
use sp_core::Get;
use sp_runtime::{traits::Convert, Perquintill};
#[cfg(not(feature = "constant-fees"))]
use {
frame_support::pallet_prelude::DispatchClass,
frame_support::weights::{
WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial,
},
smallvec::smallvec,
sp_arithmetic::MultiplyRational,
sp_runtime::traits::One,
sp_runtime::Perbill,
sp_runtime::SaturatedConversion,
sp_runtime::Saturating,
};
pub struct LengthToFeeImpl<T>(sp_std::marker::PhantomData<T>);
/// A structure to implement Length to Fee conversion.
/// - `Balance`: The balance type.
/// - `Runtime`: The system configuration type, providing access to block weights.
/// - `Target`: A type providing the target block fullness.
pub struct LengthToFeeImpl<Balance, Runtime, Target>(
PhantomData<Balance>,
PhantomData<Runtime>,
PhantomData<Target>,
);
impl<T> WeightToFee for LengthToFeeImpl<T>
/// Trait implementation for converting transaction length to fee.
impl<Balance, Runtime, Target> WeightToFee for LengthToFeeImpl<Balance, Runtime, Target>
where
T: BaseArithmetic + From<u32> + Copy + Unsigned,
Balance: BaseArithmetic + From<u32> + Copy + Unsigned,
Runtime: frame_system::Config + pallet_transaction_payment::Config,
Target: Get<Perquintill>,
{
type Balance = T;
type Balance = Balance;
// Force constant fees
/// Function to convert weight to fee when "constant-fees" feature is not enabled.
///
/// This function calculates the fee based on the length of the transaction in bytes.
/// If the current block weight and length are less than a fraction of the max block weight and length, the fee multiplier is one,
/// and the extrinsic length is less than MAX_EXTRINSIC_LENGTH bytes, no fees are applied. Otherwise, it calculates the fee based on the length in bytes.
#[cfg(not(feature = "constant-fees"))]
fn weight_to_fee(length_in_bytes: &Weight) -> Self::Balance {
((length_in_bytes.ref_time() as u32 + length_in_bytes.proof_size() as u32) / 1_000_u32)
.into()
// The extrinsic overhead for a remark is approximately 110 bytes.
// This leaves 146 bytes available for the actual remark content.
const MAX_EXTRINSIC_LENGTH: u64 = 256;
const BYTES_PER_UNIT: u64 = 350;
const BASE_EXTRINSIC_LENGTH_COST: u64 = 5;
let weights = Runtime::BlockWeights::get();
let fee_multiplier = pallet_transaction_payment::Pallet::<Runtime>::next_fee_multiplier();
let normal_max_weight = weights
.get(DispatchClass::Normal)
.max_total
.unwrap_or(weights.max_block);
let current_block_weight = <frame_system::Pallet<Runtime>>::block_weight();
let length = Runtime::BlockLength::get();
let normal_max_length = *length.max.get(DispatchClass::Normal) as u64;
let current_block_length = <frame_system::Pallet<Runtime>>::all_extrinsics_len() as u64;
if current_block_weight
.get(DispatchClass::Normal)
.all_lt(Target::get() * normal_max_weight)
&& current_block_length < (Target::get() * normal_max_length)
&& fee_multiplier.is_one()
&& length_in_bytes.ref_time() < MAX_EXTRINSIC_LENGTH
{
0u32.into()
} else {
Self::Balance::saturated_from(
length_in_bytes.ref_time() / BYTES_PER_UNIT + BASE_EXTRINSIC_LENGTH_COST,
)
}
}
pub struct WeightToFeeImpl<T>(sp_std::marker::PhantomData<T>);
/// Function to convert weight to fee when "constant-fees" feature is enabled.
///
/// This function always returns a constant fee of zero when the "constant-fees" feature is enabled.
#[cfg(feature = "constant-fees")]
fn weight_to_fee(_length_in_bytes: &Weight) -> Self::Balance {
0u32.into()
}
}
impl<T> WeightToFee for WeightToFeeImpl<T>
/// A structure to implement Weight to Fee conversion.
/// - `Balance`: The balance type.
/// - `Runtime`: The system configuration type, providing access to block weights.
/// - `Target`: A type providing the target block fullness.
pub struct WeightToFeeImpl<Balance, Runtime, Target>(
PhantomData<Balance>,
PhantomData<Runtime>,
PhantomData<Target>,
);
/// Trait implementation for converting transaction weight to fee.
///
/// This implementation is only included when the "constant-fees" feature is not enabled.
#[cfg(not(feature = "constant-fees"))]
impl<Balance, Runtime, Target> WeightToFeePolynomial for WeightToFeeImpl<Balance, Runtime, Target>
where
T: BaseArithmetic + From<u32> + Copy + Unsigned,
Balance: BaseArithmetic + From<u64> + Copy + Unsigned + From<u32> + MultiplyRational,
Runtime: frame_system::Config + pallet_transaction_payment::Config,
Target: Get<Perquintill>,
{
type Balance = T;
type Balance = Balance;
/// Function to get the polynomial coefficients for weight to fee conversion.
///
/// This function calculates the polynomial coefficients for converting transaction weight to fee.
/// If the current block weight and length are less than a fraction of the block max weight and length, and the fee multiplier is one,
/// it returns zero. Otherwise, it calculates the coefficients based on the extrinsic base weight mapped to 5 cents.
fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
let weights = Runtime::BlockWeights::get();
let fee_multiplier = pallet_transaction_payment::Pallet::<Runtime>::next_fee_multiplier();
let normal_max_weight = weights
.get(DispatchClass::Normal)
.max_total
.unwrap_or(weights.max_block);
let current_block_weight = <frame_system::Pallet<Runtime>>::block_weight();
let length = Runtime::BlockLength::get();
let normal_max_length = *length.max.get(DispatchClass::Normal) as u64;
let current_block_length = <frame_system::Pallet<Runtime>>::all_extrinsics_len() as u64;
if current_block_weight
.get(DispatchClass::Normal)
.all_lt(Target::get() * normal_max_weight)
&& current_block_length < (Target::get() * normal_max_length)
&& fee_multiplier.is_one()
{
smallvec![WeightToFeeCoefficient {
degree: 1,
negative: false,
coeff_frac: Perbill::zero(),
coeff_integer: Self::Balance::zero(),
}]
} else {
// The extrinsic base weight (smallest non-zero weight) is mapped to 5 cents
const BASE_EXTRINSIC_WEIGHT_COST: u64 = 5;
let p: Self::Balance = BASE_EXTRINSIC_WEIGHT_COST.into();
let q: Self::Balance =
Self::Balance::from(weights.get(DispatchClass::Normal).base_extrinsic.ref_time());
smallvec![WeightToFeeCoefficient {
degree: 1,
negative: false,
coeff_frac: Perbill::from_rational(p % q, q),
coeff_integer: p / q,
}]
}
}
}
/// Trait implementation for converting transaction weight to a constant fee.
///
/// This implementation is only included when the "constant-fees" feature is enabled.
#[cfg(feature = "constant-fees")]
impl<Balance, Runtime, Target> WeightToFee for WeightToFeeImpl<Balance, Runtime, Target>
where
Balance: BaseArithmetic + From<u32> + Copy + Unsigned,
{
type Balance = Balance;
fn weight_to_fee(_weight: &Weight) -> Self::Balance {
// Force constant fees for now
One::one()
1u32.into()
}
}
/// A structure to implement fee multiplier adjustments.
///
/// - `Runtime`: The system configuration type.
/// - `Target`: A type providing the target block fullness.
/// - `MaxMultiplier`: A type providing the maximum multiplier value.
pub struct FeeMultiplier<Runtime, Target, MaxMultiplier>(
PhantomData<Runtime>,
PhantomData<Target>,
PhantomData<MaxMultiplier>,
);
/// Trait implementation for updating the fee multiplier.
impl<Runtime, Target, MaxMultiplier> MultiplierUpdate
for FeeMultiplier<Runtime, Target, MaxMultiplier>
where
Runtime: frame_system::Config,
Target: Get<Perquintill>,
MaxMultiplier: Get<Multiplier>,
{
fn min() -> Multiplier {
0.into()
}
fn max() -> Multiplier {
MaxMultiplier::get()
}
fn target() -> Perquintill {
Target::get()
}
fn variability() -> Multiplier {
Default::default()
}
}
/// Trait implementation for converting previous `Multiplier` to another for fee adjustment.
impl<Runtime, Target, MaxMultiplier> Convert<Multiplier, Multiplier>
for FeeMultiplier<Runtime, Target, MaxMultiplier>
where
Runtime: frame_system::Config,
Target: Get<Perquintill>,
MaxMultiplier: Get<Multiplier>,
{
/// Function to convert the previous fee multiplier to a new fee multiplier.
///
/// This function adjusts the fee multiplier based on the current block weight, length and target block fullness.
/// - If the current block weight and length are less than the target, it decreases the multiplier by one, with a minimum of one.
/// - If the current block weight or length is more than the target, it increases the multiplier by one, up to the maximum multiplier.
#[cfg(not(feature = "constant-fees"))]
fn convert(previous: Multiplier) -> Multiplier {
let max_multiplier = MaxMultiplier::get();
let target_block_fullness = Target::get();
let weights = Runtime::BlockWeights::get();
let normal_max_weight = weights
.get(DispatchClass::Normal)
.max_total
.unwrap_or(weights.max_block);
let length = Runtime::BlockLength::get();
let normal_max_length = *length.max.get(DispatchClass::Normal) as u64;
let current_block_length = <frame_system::Pallet<Runtime>>::all_extrinsics_len() as u64;
if <frame_system::Pallet<Runtime>>::block_weight()
.get(DispatchClass::Normal)
.all_lt(target_block_fullness * normal_max_weight)
&& current_block_length < (target_block_fullness * normal_max_length)
{
// If the current block weight and length are less than the target, keep the
// multiplier at the minimum or decrease it by one to slowly
// return to the minimum.
previous.saturating_sub(1.into()).max(1.into())
} else {
// If the current block weight or length is more than the target, increase
// the multiplier by one.
previous.saturating_add(1.into()).min(max_multiplier)
}
}
/// Function to convert the previous fee multiplier to a constant fee multiplier when "constant-fees" feature is enabled.
///
/// This function always returns a constant multiplier of 1 when the "constant-fees" feature is enabled.
#[cfg(feature = "constant-fees")]
fn convert(_previous: Multiplier) -> Multiplier {
1.into()
}
}
......@@ -14,228 +14,226 @@
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
use super::entities::*;
use super::{AccountId, IdtyIndex};
use frame_support::dispatch::UnfilteredDispatchable;
use frame_support::instances::{Instance1, Instance2};
use frame_support::pallet_prelude::Weight;
use frame_support::traits::Get;
use frame_support::Parameter;
use pallet_identity::IdtyEvent;
use sp_runtime::traits::IsMember;
use super::{entities::*, AccountId, IdtyIndex};
use frame_support::{
pallet_prelude::Weight,
traits::{Imbalance, UnfilteredDispatchable},
};
use frame_system::pallet_prelude::BlockNumberFor;
use pallet_smith_members::SmithRemovalReason;
use sp_core::Get;
/// OnNewSession handler for the runtime calling all the implementation
/// of OnNewSession
pub struct OnNewSessionHandler<Runtime>(core::marker::PhantomData<Runtime>);
impl<Runtime> pallet_authority_members::traits::OnNewSession for OnNewSessionHandler<Runtime>
where
Runtime: pallet_provide_randomness::Config,
Runtime: pallet_provide_randomness::Config + pallet_smith_members::Config,
{
fn on_new_session(_index: sp_staking::SessionIndex) -> Weight {
fn on_new_session(index: sp_staking::SessionIndex) {
pallet_provide_randomness::Pallet::<Runtime>::on_new_epoch();
Weight::zero()
pallet_smith_members::Pallet::<Runtime>::on_new_session(index);
}
}
pub struct OnIdtyChangeHandler<Runtime>(core::marker::PhantomData<Runtime>);
impl<T> pallet_identity::traits::OnIdtyChange<T> for OnIdtyChangeHandler<T>
where
T: frame_system::Config<AccountId = AccountId>,
T: pallet_authority_members::Config<MemberId = IdtyIndex>,
T: pallet_identity::Config<IdtyIndex = IdtyIndex, IdtyData = IdtyData>,
T: pallet_universal_dividend::Config,
/// Runtime handler for OnNewIdty, calling all implementations of
/// OnNewIdty and implementing logic at the runtime level.
pub struct OnNewIdtyHandler<Runtime>(core::marker::PhantomData<Runtime>);
impl<Runtime: pallet_duniter_wot::Config> pallet_identity::traits::OnNewIdty<Runtime>
for OnNewIdtyHandler<Runtime>
{
fn on_idty_change(idty_index: IdtyIndex, idty_event: &IdtyEvent<T>) -> Weight {
match idty_event {
IdtyEvent::Validated => {
pallet_identity::Identities::<T>::mutate_exists(idty_index, |idty_val_opt| {
if let Some(ref mut idty_val) = idty_val_opt {
idty_val.data = IdtyData {
first_eligible_ud:
pallet_universal_dividend::Pallet::<T>::init_first_eligible_ud(),
}
}
});
}
IdtyEvent::ChangedOwnerKey { new_owner_key } => {
if let Err(e) = pallet_authority_members::Pallet::<T>::change_owner_key(
idty_index,
new_owner_key.clone(),
) {
log::error!(
"on_idty_change: pallet_authority_members.change_owner_key(): {:?}",
e
);
fn on_created(idty_index: &IdtyIndex, creator: &IdtyIndex) {
pallet_duniter_wot::Pallet::<Runtime>::on_created(idty_index, creator);
}
}
IdtyEvent::Created { .. } | IdtyEvent::Confirmed | IdtyEvent::Removed { .. } => {}
/// Runtime handler for OnRemoveIdty, calling all implementations of
/// OnRemoveIdty and implementing logic at the runtime level.
pub struct OnRemoveIdtyHandler<Runtime>(core::marker::PhantomData<Runtime>);
impl<Runtime: pallet_duniter_wot::Config + pallet_duniter_account::Config>
pallet_identity::traits::OnRemoveIdty<Runtime> for OnRemoveIdtyHandler<Runtime>
{
fn on_removed(idty_index: &IdtyIndex) -> Weight {
pallet_duniter_wot::Pallet::<Runtime>::on_removed(idty_index)
}
Weight::zero()
fn on_revoked(idty_index: &IdtyIndex) -> Weight {
pallet_duniter_wot::Pallet::<Runtime>::on_revoked(idty_index).saturating_add(
pallet_duniter_account::Pallet::<Runtime>::on_revoked(idty_index),
)
}
}
pub struct OnMembershipEventHandler<Inner, Runtime>(core::marker::PhantomData<(Inner, Runtime)>);
/// Runtime handler for OnNewMembership, calling all implementations of
/// OnNewMembership and implementing logic at the runtime level.
pub struct OnNewMembershipHandler<Runtime>(core::marker::PhantomData<Runtime>);
impl<
Inner: sp_membership::traits::OnEvent<IdtyIndex, ()>,
Runtime: frame_system::Config<AccountId = AccountId>
+ pallet_identity::Config<IdtyData = IdtyData, IdtyIndex = IdtyIndex>
+ pallet_membership::Config<Instance1, MetaData = ()>
+ pallet_universal_dividend::Config,
> sp_membership::traits::OnEvent<IdtyIndex, ()> for OnMembershipEventHandler<Inner, Runtime>
+ pallet_duniter_wot::Config
+ pallet_universal_dividend::Config
+ pallet_quota::Config,
> sp_membership::traits::OnNewMembership<IdtyIndex> for OnNewMembershipHandler<Runtime>
{
fn on_event(membership_event: &sp_membership::Event<IdtyIndex, ()>) -> Weight {
(match membership_event {
sp_membership::Event::MembershipRevoked(idty_index) => {
if let Some(idty_value) = pallet_identity::Identities::<Runtime>::get(idty_index) {
if let Some(first_ud_index) = idty_value.data.first_eligible_ud.into() {
pallet_universal_dividend::Pallet::<Runtime>::on_removed_member(
first_ud_index,
&idty_value.owner_key,
)
} else {
Runtime::DbWeight::get().reads(1)
}
} else {
Runtime::DbWeight::get().reads(1)
}
}
_ => Weight::zero(),
}) + Inner::on_event(membership_event)
}
}
fn on_created(idty_index: &IdtyIndex) {
// duniter-wot related actions
pallet_duniter_wot::Pallet::<Runtime>::on_created(idty_index);
pub struct OnSmithMembershipEventHandler<Inner, Runtime>(
core::marker::PhantomData<(Inner, Runtime)>,
);
pallet_quota::Pallet::<Runtime>::on_created(idty_index);
impl<
IdtyIndex: Copy + Parameter,
SessionKeysWrapper: Clone,
Inner: sp_membership::traits::OnEvent<IdtyIndex, SmithsMembershipMetaData<SessionKeysWrapper>>,
Runtime: frame_system::Config<AccountId = AccountId>
+ pallet_identity::Config<IdtyIndex = IdtyIndex>
+ pallet_authority_members::Config<KeysWrapper = SessionKeysWrapper, MemberId = IdtyIndex>
+ pallet_membership::Config<
Instance2,
MetaData = SmithsMembershipMetaData<SessionKeysWrapper>,
>,
> sp_membership::traits::OnEvent<IdtyIndex, SmithsMembershipMetaData<SessionKeysWrapper>>
for OnSmithMembershipEventHandler<Inner, Runtime>
{
fn on_event(
membership_event: &sp_membership::Event<
IdtyIndex,
SmithsMembershipMetaData<SessionKeysWrapper>,
>,
) -> Weight {
(match membership_event {
sp_membership::Event::MembershipAcquired(
_idty_index,
SmithsMembershipMetaData {
owner_key,
session_keys,
..
},
) => {
let call = pallet_authority_members::Call::<Runtime>::set_session_keys {
keys: session_keys.clone(),
// When main membership is acquired, it starts getting right to UD.
pallet_identity::Identities::<Runtime>::mutate_exists(idty_index, |idty_val_opt| {
if let Some(ref mut idty_val) = idty_val_opt {
idty_val.data = IdtyData {
first_eligible_ud:
pallet_universal_dividend::Pallet::<Runtime>::init_first_eligible_ud(),
};
if let Err(e) = call.dispatch_bypass_filter(
frame_system::Origin::<Runtime>::Signed(owner_key.clone()).into(),
) {
sp_std::if_std! {
println!("fail to set session keys: {:?}", e)
}
});
}
Weight::zero()
fn on_renewed(_idty_index: &IdtyIndex) {}
}
sp_membership::Event::MembershipRevoked(idty_index) => {
let call = pallet_authority_members::Call::<Runtime>::remove_member {
member_id: *idty_index,
};
if let Err(e) =
call.dispatch_bypass_filter(frame_system::Origin::<Runtime>::Root.into())
/// Runtime handler for OnRemoveMembership, calling all implementations of
///
/// OnRemoveMembership and implementing logic at the runtime level.
/// As the weight accounting is not trivial in this handler, the weight is
/// done at the handler level.
pub struct OnRemoveMembershipHandler<Runtime>(core::marker::PhantomData<Runtime>);
impl<
Runtime: frame_system::Config
+ pallet_identity::Config<IdtyData = IdtyData, IdtyIndex = IdtyIndex>
+ pallet_smith_members::Config<IdtyIndex = IdtyIndex>
+ pallet_duniter_wot::Config
+ pallet_quota::Config
+ pallet_universal_dividend::Config,
> sp_membership::traits::OnRemoveMembership<IdtyIndex> for OnRemoveMembershipHandler<Runtime>
{
sp_std::if_std! {
println!("faid to remove member: {:?}", e)
}
fn on_removed(idty_index: &IdtyIndex) -> Weight {
// duniter-wot related actions
let mut weight = pallet_duniter_wot::Pallet::<Runtime>::on_removed(idty_index);
// When membership is removed:
// - call on_removed_member handler which auto claims UD;
// - set the first_eligible_ud to None so the identity cannot claim UD anymore.
pallet_identity::Identities::<Runtime>::mutate(idty_index, |maybe_idty_value| {
if let Some(idty_value) = maybe_idty_value {
if let Some(first_ud_index) = idty_value.data.first_eligible_ud.0.take() {
weight += pallet_universal_dividend::Pallet::<Runtime>::on_removed_member(
first_ud_index.into(),
&idty_value.owner_key,
);
}
Weight::zero()
}
_ => Weight::zero(),
}) + Inner::on_event(membership_event)
});
weight.saturating_add(pallet_quota::Pallet::<Runtime>::on_removed(idty_index));
weight.saturating_add(Runtime::DbWeight::get().reads_writes(1, 1));
// When membership is removed, also remove from smith member.
weight.saturating_add(
pallet_smith_members::Pallet::<Runtime>::on_removed_wot_member(*idty_index),
)
}
}
pub struct OnRemovedAuthorityMemberHandler<Runtime>(core::marker::PhantomData<Runtime>);
impl<Runtime> pallet_authority_members::traits::OnRemovedMember<IdtyIndex>
for OnRemovedAuthorityMemberHandler<Runtime>
/// Runtime handler for TreasurySpendFunds.
pub struct TreasurySpendFunds<Runtime>(core::marker::PhantomData<Runtime>);
impl<Runtime> pallet_treasury::SpendFunds<Runtime> for TreasurySpendFunds<Runtime>
where
Runtime: frame_system::Config + pallet_membership::Config<Instance2, IdtyId = IdtyIndex>,
Runtime: pallet_treasury::Config,
{
fn on_removed_member(idty_index: IdtyIndex) -> Weight {
if let Err(e) = pallet_membership::Pallet::<Runtime, Instance2>::revoke_membership(
frame_system::RawOrigin::Root.into(),
Some(idty_index),
fn spend_funds(
_budget_remaining: &mut pallet_treasury::BalanceOf<Runtime>,
_imbalance: &mut pallet_treasury::PositiveImbalanceOf<Runtime>,
_total_weight: &mut Weight,
missed_any: &mut bool,
) {
sp_std::if_std! {
println!("fail to revoke membership: {:?}", e)
*missed_any = true;
}
}
/// Runtime handler for OnSmithDelete.
pub struct OnSmithDeletedHandler<Runtime>(core::marker::PhantomData<Runtime>);
impl<Runtime> pallet_smith_members::traits::OnSmithDelete<Runtime::MemberId>
for OnSmithDeletedHandler<Runtime>
where
Runtime: pallet_authority_members::Config,
{
fn on_smith_delete(idty_index: Runtime::MemberId, _reason: SmithRemovalReason) {
let call = pallet_authority_members::Call::<Runtime>::remove_member {
member_id: idty_index,
};
if let Err(e) = call.dispatch_bypass_filter(frame_system::Origin::<Runtime>::Root.into()) {
#[cfg(feature = "std")]
println!("faid to remove member: {:?}", e)
}
Weight::zero()
}
}
pub struct RemoveIdentityConsumersImpl<Runtime>(core::marker::PhantomData<Runtime>);
impl<Runtime> pallet_identity::traits::RemoveIdentityConsumers<IdtyIndex>
for RemoveIdentityConsumersImpl<Runtime>
where
Runtime: pallet_identity::Config<IdtyIndex = IdtyIndex>
/// Runtime handler OwnerKeyChangePermission.
pub struct KeyChangeHandler<Runtime, ReportLongevity>(
core::marker::PhantomData<(Runtime, ReportLongevity)>,
);
impl<
Runtime: frame_system::Config<AccountId = AccountId>
+ pallet_identity::Config<IdtyIndex = IdtyIndex>
+ pallet_authority_members::Config<MemberId = IdtyIndex>
+ pallet_membership::Config<Instance1, IdtyId = IdtyIndex>
+ pallet_membership::Config<Instance2, IdtyId = IdtyIndex>,
+ pallet_smith_members::Config<IdtyIndex = IdtyIndex>,
ReportLongevity: Get<BlockNumberFor<Runtime>>,
> pallet_identity::traits::KeyChange<Runtime> for KeyChangeHandler<Runtime, ReportLongevity>
{
fn remove_idty_consumers(idty_index: IdtyIndex) -> Weight {
// Remove smith member
if pallet_membership::Pallet::<Runtime, Instance2>::is_member(&idty_index) {
if let Err(e) = pallet_membership::Pallet::<Runtime, Instance2>::revoke_membership(
frame_system::RawOrigin::Root.into(),
Some(idty_index),
) {
log::error!(
target: "runtime::common",
"Logic error: fail to revoke smith membership in remove_idty_consumers(): {:?}",
e
);
/// Handles the event when an identity's owner key is changed.
///
/// # Errors
/// * Returns `OwnerKeyInBound` if the smith was a validator and the bond period is not finished, meaning it can still be punished for past actions.
/// * Returns `OwnerKeyUsedAsValidator` if the owner key is currently used as a validator.
///
/// # Behavior
/// * If the smith is online, the operation is rejected.
/// * If the smith was a validator and is still within the bond period, the operation is rejected. It means they can still be punished for past actions.
/// * If the smith is neither online nor within the bond period, the owner key is changed successfully and the change is reflected in the validator member data if available.
fn on_changed(
idty_index: IdtyIndex,
account_id: AccountId,
) -> Result<(), sp_runtime::DispatchError> {
if let Some(smith) = pallet_smith_members::Pallet::<Runtime>::smiths(&idty_index) {
if let Some(last_online) = smith.last_online {
if last_online + ReportLongevity::get()
> frame_system::pallet::Pallet::<Runtime>::block_number()
{
return Err(pallet_identity::Error::<Runtime>::OwnerKeyInBound.into());
} else {
pallet_authority_members::Pallet::<Runtime>::change_owner_key(
idty_index, account_id,
)
.map_err(|e| e.error)?;
}
} else {
return Err(pallet_identity::Error::<Runtime>::OwnerKeyUsedAsValidator.into());
}
// Remove "classic" member
if let Err(e) = pallet_membership::Pallet::<Runtime, Instance1>::revoke_membership(
frame_system::RawOrigin::Root.into(),
Some(idty_index),
) {
log::error!(
target: "runtime::common",
"Logic error: fail to revoke membership in remove_idty_consumers(): {:?}",
e
);
}
Weight::zero()
Ok(())
}
}
pub struct TreasurySpendFunds<Runtime>(core::marker::PhantomData<Runtime>);
impl<Runtime> pallet_treasury::SpendFunds<Runtime> for TreasurySpendFunds<Runtime>
/// Runtime handler for managing fee handling by transferring unbalanced amounts to a treasury account.
pub struct HandleFees<TreasuryAccount, Balances>(
frame_support::pallet_prelude::PhantomData<(TreasuryAccount, Balances)>,
);
type CreditOf<Balances> = frame_support::traits::tokens::fungible::Credit<AccountId, Balances>;
impl<TreasuryAccount, Balances> frame_support::traits::OnUnbalanced<CreditOf<Balances>>
for HandleFees<TreasuryAccount, Balances>
where
Runtime: pallet_treasury::Config,
TreasuryAccount: Get<AccountId>,
Balances: frame_support::traits::fungible::Balanced<AccountId>,
{
fn spend_funds(
_budget_remaining: &mut pallet_treasury::BalanceOf<Runtime>,
_imbalance: &mut pallet_treasury::PositiveImbalanceOf<Runtime>,
_total_weight: &mut Weight,
missed_any: &mut bool,
) {
*missed_any = true;
fn on_nonzero_unbalanced(amount: CreditOf<Balances>) {
// fee is moved to treasury
let _ = Balances::deposit(
&TreasuryAccount::get(),
amount.peek(),
frame_support::traits::tokens::Precision::Exact,
);
}
}
......@@ -17,13 +17,14 @@
#![cfg_attr(not(feature = "std"), no_std)]
mod apis;
mod benchmarks;
pub mod constants;
pub mod entities;
pub mod fees;
pub mod handlers;
mod offchain;
mod pallets_config;
pub mod providers;
pub mod weights;
pub use pallet_duniter_account::GenesisAccountData;
pub use pallet_identity::{GenesisIdty, IdtyName, IdtyStatus, IdtyValue};
......@@ -63,6 +64,9 @@ pub type Signature = sp_runtime::MultiSignature;
/// Index of an identity
pub type IdtyIndex = u32;
/// Time in milliseconds
pub type Moment = u64;
pub struct FullIdentificationOfImpl;
impl sp_runtime::traits::Convert<AccountId, Option<entities::ValidatorFullIdentification>>
for FullIdentificationOfImpl
......
// Copyright 2021 Axiom-Team
//
// This file is part of Duniter-v2S.
//
// Duniter-v2S is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Duniter-v2S is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
#[macro_export]
macro_rules! offchain_config {
() => {
impl<LocalCall> frame_system::offchain::CreateTransaction<LocalCall> for Runtime
where
RuntimeCall: From<LocalCall>,
{
type Extension = TxExtension;
fn create_transaction(call: RuntimeCall, extension: TxExtension) -> UncheckedExtrinsic {
generic::UncheckedExtrinsic::new_transaction(call, extension)
}
}
impl<LocalCall> frame_system::offchain::CreateInherent<LocalCall> for Runtime
where
RuntimeCall: From<LocalCall>,
{
fn create_inherent(call: RuntimeCall) -> UncheckedExtrinsic {
generic::UncheckedExtrinsic::new_bare(call)
}
}
impl<LocalCall> frame_system::offchain::CreateTransactionBase<LocalCall> for Runtime
where
RuntimeCall: From<LocalCall>,
{
type Extrinsic = UncheckedExtrinsic;
type RuntimeCall = RuntimeCall;
}
};
}
......@@ -16,9 +16,7 @@
#[macro_export]
macro_rules! pallets_config {
{$($custom:tt)*} => {
$($custom)*
() => {
// SYSTEM //
parameter_types! {
......@@ -26,55 +24,61 @@ macro_rules! pallets_config {
}
impl frame_system::Config for Runtime {
/// The data to be stored in an account.
type AccountData = pallet_duniter_account::AccountData<Balance, IdtyIndex>;
/// The identifier used to distinguish between accounts.
type AccountId = AccountId;
/// The basic call filter to use in dispatchable.
type BaseCallFilter = BaseCallFilter;
/// Block & extrinsics weights: base values and limits.
type BlockWeights = BlockWeights;
/// The block type for the runtime.
type Block = Block;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = BlockHashCount;
/// The maximum length of a block (in bytes).
type BlockLength = BlockLength;
/// The identifier used to distinguish between accounts.
type AccountId = AccountId;
/// The aggregated dispatch type that is available for extrinsics.
type RuntimeCall = RuntimeCall;
/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
type Lookup = AccountIdLookup<AccountId, ()>;
/// The index type for storing how many extrinsics an account has signed.
type Index = Index;
/// The index type for blocks.
type BlockNumber = BlockNumber;
/// Block & extrinsics weights: base values and limits.
type BlockWeights = BlockWeights;
/// The weight of database operations that the runtime can invoke.
type DbWeight = DbWeight;
/// The weight of transaction extensions.
type ExtensionsWeightInfo = weights::frame_system_extensions::WeightInfo<Runtime>;
/// The type for hashing blocks and tries.
type Hash = Hash;
/// The hashing algorithm used.
type Hashing = BlakeTwo256;
/// The header type.
type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
/// The ubiquitous origin type.
type RuntimeOrigin = RuntimeOrigin;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = BlockHashCount;
/// The weight of database operations that the runtime can invoke.
type DbWeight = DbWeight;
/// Version of the runtime.
type Version = Version;
/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
type Lookup = AccountIdLookup<AccountId, ()>;
type MaxConsumers = frame_support::traits::ConstU32<16>;
type MultiBlockMigrator = ();
/// The type for storing how many extrinsics an account has signed.
type Nonce = node_primitives::Nonce;
/// What to do if an account is fully reaped from the system.
type OnKilledAccount = ();
/// What to do if a new account is created.
type OnNewAccount = ();
/// The set code logic, just the default since we're not a parachain.
type OnSetCode = ();
/// Converts a module to the index of the module in `construct_runtime!`.
///
/// This type is being generated by `construct_runtime!`.
type PalletInfo = PalletInfo;
/// What to do if a new account is created.
type OnNewAccount = ();
/// What to do if an account is fully reaped from the system.
type OnKilledAccount = ();
/// The data to be stored in an account.
type AccountData = pallet_duniter_account::AccountData<Balance>;
/// Weight information for the extrinsics of this pallet.
type SystemWeightInfo = common_runtime::weights::frame_system::WeightInfo<Runtime>;
type PostInherents = ();
type PostTransactions = ();
type PreInherents = ();
/// The aggregated dispatch type that is available for extrinsics.
type RuntimeCall = RuntimeCall;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
/// The ubiquitous origin type.
type RuntimeOrigin = RuntimeOrigin;
type RuntimeTask = ();
/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
type SS58Prefix = SS58Prefix;
/// The set code logic, just the default since we're not a parachain.
type OnSetCode = ();
type MaxConsumers = frame_support::traits::ConstU32<16>;
type SingleBlockMigrations = ();
/// Weight information for the extrinsics of this pallet.
type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
/// Version of the runtime.
type Version = Version;
}
// SCHEDULER //
......@@ -86,105 +90,108 @@ macro_rules! pallets_config {
pub const NoPreimagePostponement: Option<u32> = Some(10);
}
impl pallet_scheduler::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
type PalletsOrigin = OriginCaller;
type RuntimeCall = RuntimeCall;
type BlockNumberProvider = frame_system::Pallet<Runtime>;
type MaxScheduledPerBlock = MaxScheduledPerBlock;
type MaximumWeight = MaximumSchedulerWeight;
type ScheduleOrigin = EnsureRoot<AccountId>;
type OriginPrivilegeCmp = EqualPrivilegeOnly;
type MaxScheduledPerBlock = MaxScheduledPerBlock;
type WeightInfo = common_runtime::weights::pallet_scheduler::WeightInfo<Runtime>;
type PalletsOrigin = OriginCaller;
type Preimages = Preimage;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
type ScheduleOrigin = EnsureRoot<AccountId>;
type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
}
// ACCOUNT //
impl pallet_duniter_account::Config for Runtime {
type AccountIdToSalt = sp_runtime::traits::ConvertInto;
type MaxNewAccountsPerBlock = frame_support::pallet_prelude::ConstU32<1>;
type NewAccountPrice = frame_support::traits::ConstU64<300>;
// does currency adapter in any case, but adds "refund with quota" feature
type InnerOnChargeTransaction =
FungibleAdapter<Balances, HandleFees<TreasuryAccount, Balances>>;
type Refund = Quota;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = weights::pallet_duniter_account::WeightInfo<Runtime>;
}
parameter_types! {
pub const ReloadRate: BlockNumber = 1 * HOURS; // faster than DAYS
pub const MaxQuota: Balance = 1000; // 10 ĞD
pub const MaxNominators: u32 = 64;
pub TreasuryAccount: AccountId = Treasury::account_id();
}
impl pallet_quota::Config for Runtime {
type MaxQuota = MaxQuota;
type RefundAccount = TreasuryAccount;
type ReloadRate = ReloadRate;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = weights::pallet_quota::WeightInfo<Runtime>;
}
// BLOCK CREATION //
impl pallet_babe::Config for Runtime {
type EpochDuration = EpochDuration;
type ExpectedBlockTime = ExpectedBlockTime;
type DisabledValidators = Session;
// session module is the trigger
type EpochChangeTrigger = pallet_babe::ExternalTrigger;
type DisabledValidators = Session;
type KeyOwnerProofSystem = Historical;
type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
pallet_babe::AuthorityId,
)>>::Proof;
type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
pallet_babe::AuthorityId,
)>>::IdentificationTuple;
type HandleEquivocation =
pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
type WeightInfo = common_runtime::weights::pallet_babe::WeightInfo<Runtime>;
type EpochDuration = EpochDuration;
type EquivocationReportSystem =
pallet_babe::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
type ExpectedBlockTime = ExpectedBlockTime;
type KeyOwnerProof =
<Historical as KeyOwnerProofSystem<(KeyTypeId, pallet_babe::AuthorityId)>>::Proof;
type MaxAuthorities = MaxAuthorities;
type MaxNominators = MaxNominators;
type WeightInfo = weights::pallet_babe::WeightInfo<Runtime>;
}
impl pallet_timestamp::Config for Runtime {
type Moment = u64;
type OnTimestampSet = Babe;
type MinimumPeriod = MinimumPeriod;
type WeightInfo = common_runtime::weights::pallet_timestamp::WeightInfo<Runtime>;
type Moment = u64;
type OnTimestampSet = (Babe, UniversalDividend);
type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
}
// MONEY MANAGEMENT //
impl pallet_balances::Config for Runtime {
type AccountStore = Account;
type Balance = Balance;
type DoneSlashHandler = ();
type DustRemoval = HandleFees<TreasuryAccount, Balances>;
type ExistentialDeposit = ExistentialDeposit;
type FreezeIdentifier = ();
type MaxFreezes = frame_support::pallet_prelude::ConstU32<0>;
type MaxLocks = MaxLocks;
type MaxReserves = frame_support::pallet_prelude::ConstU32<5>;
type ReserveIdentifier = [u8; 8];
/// The type for recording an account's balance.
type Balance = Balance;
type DustRemoval = Treasury;
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = Account;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
type WeightInfo = common_runtime::weights::pallet_balances::WeightInfo<Runtime>;
type RuntimeFreezeReason = ();
type RuntimeHoldReason = RuntimeHoldReason;
type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
}
pub struct HandleFees;
type NegativeImbalance = <Balances as frame_support::traits::Currency<AccountId>>::NegativeImbalance;
impl frame_support::traits::OnUnbalanced<NegativeImbalance> for HandleFees {
fn on_nonzero_unbalanced(amount: NegativeImbalance) {
use frame_support::traits::Currency as _;
if let Some(author) = Authorship::author() {
Balances::resolve_creating(&author, amount);
}
}
parameter_types! {
pub Target: Perquintill = Perquintill::from_percent(25);
pub MaxMultiplier: sp_runtime::FixedU128 = 10.into();
}
pub struct OnChargeTransaction;
impl pallet_transaction_payment::Config for Runtime {
type FeeMultiplierUpdate =
common_runtime::fees::FeeMultiplier<Self, Target, MaxMultiplier>;
type LengthToFee = common_runtime::fees::LengthToFeeImpl<Balance, Self, Target>;
// does a filter on the call
type OnChargeTransaction = OneshotAccount;
type OperationalFeeMultiplier = frame_support::traits::ConstU8<5>;
type WeightToFee = common_runtime::fees::WeightToFeeImpl<Balance>;
type LengthToFee = common_runtime::fees::LengthToFeeImpl<Balance>;
type FeeMultiplierUpdate = ();
type RuntimeEvent = RuntimeEvent;
type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
type WeightToFee = common_runtime::fees::WeightToFeeImpl<Balance, Self, Target>;
}
impl pallet_oneshot_account::Config for Runtime {
type Currency = Balances;
// when call is not oneshot account, fall back to duniter-account implementation
type InnerOnChargeTransaction = Account;
type RuntimeEvent = RuntimeEvent;
type InnerOnChargeTransaction = CurrencyAdapter<Balances, HandleFees>;
type WeightInfo = weights::pallet_oneshot_account::WeightInfo<Runtime>;
}
// CONSENSUS //
......@@ -193,93 +200,98 @@ macro_rules! pallets_config {
type MaxAuthorities = MaxAuthorities;
}
impl pallet_authority_members::Config for Runtime {
type KeysWrapper = opaque::SessionKeysWrapper;
type IsMember = SmithsMembership;
type OnNewSession = OnNewSessionHandler<Runtime>;
type OnRemovedMember = OnRemovedAuthorityMemberHandler<Runtime>;
type IsMember = SmithMembers;
type MaxAuthorities = MaxAuthorities;
type MemberId = IdtyIndex;
type MemberIdOf = common_runtime::providers::IdentityIndexOf<Self>;
type MaxAuthorities = MaxAuthorities;
type MaxKeysLife = frame_support::pallet_prelude::ConstU32<1_500>;
type MaxOfflineSessions = frame_support::pallet_prelude::ConstU32<2_400>;
type OnIncomingMember = SmithMembers;
type OnNewSession = OnNewSessionHandler<Runtime>;
type OnOutgoingMember = SmithMembers;
type RemoveMemberOrigin = EnsureRoot<Self::AccountId>;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = weights::pallet_authority_members::WeightInfo<Runtime>;
}
impl pallet_authorship::Config for Runtime {
type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
type UncleGenerations = UncleGenerations;
type FilterUncle = ();
type EventHandler = ImOnline;
type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
}
impl pallet_im_online::Config for Runtime {
type AuthorityId = ImOnlineId;
type RuntimeEvent = RuntimeEvent;
type ValidatorSet = Historical;
#[cfg(not(feature = "runtime-benchmarks"))]
type MaxKeys = MaxAuthorities;
#[cfg(feature = "runtime-benchmarks")]
type MaxKeys = frame_support::traits::ConstU32<1_000>;
type MaxPeerInHeartbeats = MaxPeerInHeartbeats;
type NextSessionRotation = Babe;
type ReportUnresponsiveness = Offences;
type RuntimeEvent = RuntimeEvent;
type UnsignedPriority = ImOnlineUnsignedPriority;
type WeightInfo = pallet_im_online::weights::SubstrateWeight<Runtime>;
type MaxKeys = MaxAuthorities;
type MaxPeerInHeartbeats = MaxPeerInHeartbeats;
type MaxPeerDataEncodingSize = MaxPeerDataEncodingSize;
type ValidatorSet = Historical;
type WeightInfo = weights::pallet_im_online::WeightInfo<Runtime>;
}
impl pallet_offences::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
type OnOffenceHandler = ();
type OnOffenceHandler = AuthorityMembers;
type RuntimeEvent = RuntimeEvent;
}
impl pallet_session::Config for Runtime {
type DisablingStrategy =
pallet_session::disabling::UpToLimitWithReEnablingDisablingStrategy;
type Keys = opaque::SessionKeys;
type NextSessionRotation = Babe;
type RuntimeEvent = RuntimeEvent;
type SessionHandler = <opaque::SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type SessionManager =
pallet_session::historical::NoteHistoricalRoot<Self, AuthorityMembers>;
type ShouldEndSession = Babe;
type ValidatorId = AccountId;
type ValidatorIdOf = sp_runtime::traits::ConvertInto;
type ShouldEndSession = Babe;
type NextSessionRotation = Babe;
type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, AuthorityMembers>;
type SessionHandler = <opaque::SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type Keys = opaque::SessionKeys;
type WeightInfo = pallet_session::weights::SubstrateWeight<Runtime>;
type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
}
impl pallet_session::historical::Config for Runtime {
type FullIdentification = ValidatorFullIdentification;
type FullIdentificationOf = FullIdentificationOfImpl;
}
impl pallet_grandpa::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type KeyOwnerProofSystem = ();
type KeyOwnerProof =
<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
GrandpaId,
)>>::IdentificationTuple;
type HandleEquivocation = ();
type WeightInfo = common_runtime::weights::pallet_grandpa::WeightInfo<Runtime>;
type EquivocationReportSystem = pallet_grandpa::EquivocationReportSystem<
Self,
Offences,
Historical,
ReportLongevity,
>;
type KeyOwnerProof = <Historical as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
type MaxAuthorities = MaxAuthorities;
type MaxNominators = frame_support::traits::ConstU32<64>;
type MaxSetIdSessionEntries = MaxSetIdSessionEntries;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = weights::pallet_grandpa::WeightInfo<Runtime>;
}
parameter_types! {
// BondingDuration::get() * SessionsPerEra::get();
pub const MaxSetIdSessionEntries: u32 = 1000;
}
// ONCHAIN GOVERNANCE //
#[cfg(feature = "runtime-benchmarks")]
parameter_types! {
pub const WorstCaseOrigin: pallet_collective::RawOrigin<AccountId, TechnicalCommitteeInstance> =
pallet_collective::RawOrigin::<AccountId, TechnicalCommitteeInstance>::Members(2, 3);
pub const WorstCaseOrigin: WorstOrigin = WorstOrigin::Members(2, 3);
}
impl pallet_upgrade_origin::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Call = RuntimeCall;
type UpgradableOrigin = pallet_collective::EnsureProportionAtLeast<AccountId, TechnicalCommitteeInstance, 2, 3>;
type WeightInfo = common_runtime::weights::pallet_upgrade_origin::WeightInfo<Runtime>;
#[cfg(feature = "runtime-benchmarks")]
type WorstCaseOriginType = pallet_collective::RawOrigin<AccountId, TechnicalCommitteeInstance>;
type RuntimeEvent = RuntimeEvent;
type UpgradableOrigin = pallet_collective::EnsureProportionAtLeast<
AccountId,
TechnicalCommitteeInstance,
2,
3,
>;
type WeightInfo = weights::pallet_upgrade_origin::WeightInfo<Runtime>;
#[cfg(feature = "runtime-benchmarks")]
type WorstCaseOrigin = WorstCaseOrigin;
#[cfg(feature = "runtime-benchmarks")]
type WorstCaseOriginType = RawOrigin<AccountId, TechnicalCommitteeInstance>;
}
parameter_types! {
......@@ -289,32 +301,32 @@ macro_rules! pallets_config {
}
impl pallet_preimage::Config for Runtime {
type WeightInfo = pallet_preimage::weights::SubstrateWeight<Runtime>;
type RuntimeEvent = RuntimeEvent;
type Consideration = ();
type Currency = Balances;
type ManagerOrigin = EnsureRoot<AccountId>;
type BaseDeposit = PreimageBaseDeposit;
type ByteDeposit = PreimageByteDeposit;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = weights::pallet_preimage::WeightInfo<Runtime>;
}
// UTILITIES //
impl pallet_atomic_swap::Config for Runtime {
type ProofLimit = frame_support::traits::ConstU32<1_024>;
type RuntimeEvent = RuntimeEvent;
type SwapAction = pallet_atomic_swap::BalanceSwapAction<AccountId, Balances>;
type ProofLimit = frame_support::traits::ConstU32<1_024>;
}
impl pallet_provide_randomness::Config for Runtime {
type Currency = Balances;
type GetCurrentEpochIndex = GetCurrentEpochIndex<Self>;
type MaxRequests = frame_support::traits::ConstU32<100>;
type RequestPrice = frame_support::traits::ConstU64<2_000>;
type OnFilledRandomness = Account;
type OnUnbalanced = Treasury;
type OnFilledRandomness = ();
type OnUnbalanced = HandleFees<TreasuryAccount, Balances>;
type ParentBlockRandomness = pallet_babe::ParentBlockRandomness<Self>;
type RandomnessFromOneEpochAgo = pallet_babe::RandomnessFromOneEpochAgo<Self>;
type RequestPrice = frame_support::traits::ConstU64<2_000>;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = weights::pallet_provide_randomness::WeightInfo<Runtime>;
}
parameter_types! {
......@@ -326,18 +338,19 @@ macro_rules! pallets_config {
pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
}
impl pallet_proxy::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type AnnouncementDepositBase = AnnouncementDepositBase;
type AnnouncementDepositFactor = AnnouncementDepositFactor;
type BlockNumberProvider = frame_system::Pallet<Runtime>;
type CallHasher = BlakeTwo256;
type Currency = Balances;
type ProxyType = ProxyType;
type MaxPending = frame_support::traits::ConstU32<32>;
type MaxProxies = frame_support::traits::ConstU32<32>;
type ProxyDepositBase = ProxyDepositBase;
type ProxyDepositFactor = ProxyDepositFactor;
type MaxProxies = frame_support::traits::ConstU32<32>;
type MaxPending = frame_support::traits::ConstU32<32>;
type CallHasher = BlakeTwo256;
type AnnouncementDepositBase = AnnouncementDepositBase;
type AnnouncementDepositFactor = AnnouncementDepositFactor;
type WeightInfo = common_runtime::weights::pallet_proxy::WeightInfo<Self>;
type ProxyType = ProxyType;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = weights::pallet_proxy::WeightInfo<Runtime>;
}
parameter_types! {
......@@ -345,20 +358,21 @@ macro_rules! pallets_config {
pub const DepositFactor: Balance = DEPOSIT_PER_BYTE * 32;
}
impl pallet_multisig::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type BlockNumberProvider = frame_system::Pallet<Runtime>;
type Currency = Balances;
type DepositBase = DepositBase;
type DepositFactor = DepositFactor;
type MaxSignatories = MaxSignatories;
type WeightInfo = common_runtime::weights::pallet_multisig::WeightInfo<Self>;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
}
impl pallet_utility::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type PalletsOrigin = OriginCaller;
type WeightInfo = pallet_utility::weights::SubstrateWeight<Self>;
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
}
parameter_types! {
......@@ -371,131 +385,141 @@ macro_rules! pallets_config {
pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
}
impl pallet_treasury::Config for Runtime {
type ApproveOrigin = TreasuryApproveOrigin;
type AssetKind = ();
type BalanceConverter = frame_support::traits::tokens::UnityAssetBalanceConversion;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
type Beneficiary = AccountId;
type BeneficiaryLookup = AccountIdLookup<AccountId, ()>;
type BlockNumberProvider = System;
type Burn = Burn;
type BurnDestination = ();
type Currency = Balances;
type RuntimeEvent = RuntimeEvent;
type OnSlash = Treasury;
type ProposalBond = ProposalBond;
type ProposalBondMinimum = frame_support::traits::ConstU64<10_000>;
type ProposalBondMaximum = ProposalBondMaximum;
type MaxApprovals = frame_support::traits::ConstU32<100>;
type PalletId = TreasuryPalletId;
type Paymaster =
frame_support::traits::tokens::pay::PayFromAccount<Balances, TreasuryAccount>;
type PayoutPeriod = sp_core::ConstU32<10>;
type RejectOrigin = TreasuryRejectOrigin;
type RuntimeEvent = RuntimeEvent;
type SpendFunds = TreasurySpendFunds<Self>;
type SpendOrigin = frame_support::traits::NeverEnsureOrigin<Balance>;
type SpendPeriod = SpendPeriod;
type SpendOrigin = frame_support::traits::NeverEnsureOrigin<u64>;
type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;
type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>;
}
// UNIVERSAL DIVIDEND //
pub struct MembersCount;
impl frame_support::pallet_prelude::Get<Balance> for MembersCount {
fn get() -> Balance {
<Membership as sp_membership::traits::MembersCount>::members_count() as Balance
}
}
impl pallet_universal_dividend::Config for Runtime {
type BlockNumberIntoBalance = sp_runtime::traits::ConvertInto;
type Currency = pallet_balances::Pallet<Runtime>;
type RuntimeEvent = RuntimeEvent;
type MaxPastReeval = frame_support::traits::ConstU32<4>;
type MembersCount = MembersCount;
type Currency = Balances;
#[cfg(feature = "runtime-benchmarks")]
type IdtyAttr = Identity;
type MaxPastReeval = frame_support::traits::ConstU32<160>;
type MembersCount = common_runtime::providers::MembersCount<Membership>;
type MembersStorage = common_runtime::providers::UdMembersStorage<Runtime>;
type MembersStorageIter = common_runtime::providers::UdMembersStorageIter<Runtime>;
type MomentIntoBalance = sp_runtime::traits::ConvertInto;
type RuntimeEvent = RuntimeEvent;
type SquareMoneyGrowthRate = SquareMoneyGrowthRate;
type UdCreationPeriod = UdCreationPeriod;
type UdReevalPeriod = UdReevalPeriod;
type UnitsPerUd = frame_support::traits::ConstU64<1_000>;
type WeightInfo = common_runtime::weights::pallet_universal_dividend::WeightInfo<Runtime>;
type WeightInfo = weights::pallet_universal_dividend::WeightInfo<Runtime>;
}
// WEB OF TRUST //
use frame_support::instances::Instance1;
impl pallet_duniter_wot::Config<Instance1> for Runtime {
impl pallet_duniter_wot::Config for Runtime {
type FirstIssuableOn = WotFirstCertIssuableOn;
type IsSubWot = frame_support::traits::ConstBool<false>;
type MinCertForMembership = WotMinCertForMembership;
type MinCertForCreateIdtyRight = WotMinCertForCreateIdtyRight;
type MinCertForMembership = WotMinCertForMembership;
}
parameter_types! {
pub const ValidationPeriod: BlockNumber = 2 * MONTHS;
}
impl pallet_identity::Config for Runtime {
type AccountId32 = AccountId;
type AccountLinker = Account;
type AutorevocationPeriod = AutorevocationPeriod;
type ChangeOwnerKeyPeriod = ChangeOwnerKeyPeriod;
type CheckAccountWorthiness = Account;
type CheckIdtyCallAllowed = Wot;
type ConfirmPeriod = ConfirmPeriod;
type CheckIdtyCallAllowed = (Wot, SmithsSubWot);
type DeletionPeriod = DeletionPeriod;
type IdtyCreationPeriod = IdtyCreationPeriod;
type IdtyData = IdtyData;
type IdtyIndex = IdtyIndex;
type IdtyNameValidator = IdtyNameValidatorImpl;
type NewOwnerKeySigner = <NewOwnerKeySignature as sp_runtime::traits::Verify>::Signer;
type NewOwnerKeySignature = NewOwnerKeySignature;
type OnIdtyChange = (common_runtime::handlers::OnIdtyChangeHandler<Runtime>, Wot);
type RemoveIdentityConsumers = RemoveIdentityConsumersImpl<Self>;
type RevocationSigner = <Signature as sp_runtime::traits::Verify>::Signer;
type RevocationSignature = Signature;
type OnKeyChange = KeyChangeHandler<Runtime, ReportLongevity>;
type OnNewIdty = OnNewIdtyHandler<Runtime>;
type OnRemoveIdty = OnRemoveIdtyHandler<Runtime>;
type RuntimeEvent = RuntimeEvent;
type Signature = Signature;
type Signer = <Signature as sp_runtime::traits::Verify>::Signer;
type ValidationPeriod = ValidationPeriod;
type WeightInfo = weights::pallet_identity::WeightInfo<Runtime>;
}
impl pallet_membership::Config<frame_support::instances::Instance1> for Runtime {
type CheckCallAllowed = Wot;
impl pallet_sudo::Config for Runtime {
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = weights::pallet_sudo::WeightInfo<Runtime>;
}
impl pallet_membership::Config for Runtime {
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkSetupHandler = common_runtime::providers::BenchmarkSetupHandler<Runtime>;
type CheckMembershipOpAllowed = Wot;
type IdtyAttr = Identity;
type IdtyId = IdtyIndex;
type IdtyIdOf = common_runtime::providers::IdentityIndexOf<Self>;
type MembershipPeriod = MembershipPeriod;
type MetaData = ();
type OnEvent = OnMembershipEventHandler<Wot, Runtime>;
type PendingMembershipPeriod = PendingMembershipPeriod;
type MembershipRenewalPeriod = MembershipRenewalPeriod;
type OnNewMembership = OnNewMembershipHandler<Runtime>;
type OnRemoveMembership = OnRemoveMembershipHandler<Runtime>;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = weights::pallet_membership::WeightInfo<Runtime>;
}
impl pallet_certification::Config<Instance1> for Runtime {
impl pallet_certification::Config for Runtime {
type CertPeriod = CertPeriod;
type IdtyIndex = IdtyIndex;
type OwnerKeyOf = Identity;
type CheckCertAllowed = Wot;
type IdtyAttr = Identity;
type IdtyIndex = IdtyIndex;
type MaxByIssuer = MaxByIssuer;
type MinReceivedCertToBeAbleToIssueCert = MinReceivedCertToBeAbleToIssueCert;
type OnNewcert = Wot;
type OnRemovedCert = Wot;
type RuntimeEvent = RuntimeEvent;
type ValidityPeriod = ValidityPeriod;
type WeightInfo = weights::pallet_certification::WeightInfo<Runtime>;
}
// SMITHS SUB-WOT //
use frame_support::instances::Instance2;
impl pallet_duniter_wot::Config<Instance2> for Runtime {
type FirstIssuableOn = SmithsWotFirstCertIssuableOn;
type IsSubWot = frame_support::traits::ConstBool<true>;
type MinCertForMembership = SmithsWotMinCertForMembership;
type MinCertForCreateIdtyRight = frame_support::traits::ConstU32<0>;
}
impl pallet_membership::Config<Instance2> for Runtime {
type CheckCallAllowed = SmithsSubWot;
type IdtyId = IdtyIndex;
type IdtyIdOf = common_runtime::providers::IdentityIndexOf<Self>;
type MembershipPeriod = SmithMembershipPeriod;
type MetaData = SmithsMembershipMetaData<opaque::SessionKeysWrapper>;
type OnEvent = OnSmithMembershipEventHandler<SmithsSubWot, Runtime>;
type PendingMembershipPeriod = SmithPendingMembershipPeriod;
impl pallet_distance::Config for Runtime {
type CheckRequestDistanceEvaluation = Wot;
type Currency = Balances;
type EvaluationPeriod = frame_support::traits::ConstU32<7>;
type EvaluationPrice = frame_support::traits::ConstU64<1000>;
type MaxRefereeDistance = MaxRefereeDistance;
type MinAccessibleReferees = MinAccessibleReferees;
type OnUnbalanced = HandleFees<TreasuryAccount, Balances>;
type OnValidDistanceStatus = Wot;
type RuntimeEvent = RuntimeEvent;
type RuntimeHoldReason = RuntimeHoldReason;
type WeightInfo = weights::pallet_distance::WeightInfo<Runtime>;
}
impl pallet_certification::Config<Instance2> for Runtime {
type CertPeriod = SmithCertPeriod;
// SMITH-MEMBERS
impl pallet_smith_members::Config for Runtime {
type IdtyAttr = Identity;
type IdtyIdOfAuthorityId = sp_runtime::traits::ConvertInto;
type IdtyIndex = IdtyIndex;
type OwnerKeyOf = Identity;
type CheckCertAllowed = SmithsSubWot;
type IsWoTMember = common_runtime::providers::IsWoTMemberProvider<Runtime>;
type MaxByIssuer = SmithMaxByIssuer;
type MinReceivedCertToBeAbleToIssueCert = SmithMinReceivedCertToBeAbleToIssueCert;
type OnNewcert = SmithsSubWot;
type OnRemovedCert = SmithsSubWot;
type MemberId = IdtyIndex;
type MinCertForMembership = SmithWotMinCertForMembership;
type OnSmithDelete = OnSmithDeletedHandler<Runtime>;
type RuntimeEvent = RuntimeEvent;
type ValidityPeriod = SmithValidityPeriod;
type SmithInactivityMaxDuration = SmithInactivityMaxDuration;
type WeightInfo = weights::pallet_smith_members::WeightInfo<Runtime>;
}
pub struct TechnicalCommitteeDefaultVote;
......@@ -511,16 +535,25 @@ macro_rules! pallets_config {
}
parameter_types! {
pub const TechnicalCommitteeMotionDuration: BlockNumber = 7 * DAYS;
pub MaxWeight: Weight = Perbill::from_percent(50) * BlockWeights::get().max_block;
}
impl pallet_collective::Config<Instance2> for Runtime {
type RuntimeOrigin = RuntimeOrigin;
type Consideration = ();
#[cfg(not(feature = "runtime-benchmarks"))]
type DefaultVote = TechnicalCommitteeDefaultVote;
#[cfg(feature = "runtime-benchmarks")]
type DefaultVote = pallet_collective::PrimeDefaultVote;
type DisapproveOrigin = EnsureRoot<Self::AccountId>;
type KillOrigin = EnsureRoot<Self::AccountId>;
type MaxMembers = frame_support::pallet_prelude::ConstU32<100>;
type MaxProposalWeight = MaxWeight;
type MaxProposals = frame_support::pallet_prelude::ConstU32<20>;
type MotionDuration = TechnicalCommitteeMotionDuration;
type Proposal = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type MotionDuration = TechnicalCommitteeMotionDuration;
type MaxProposals = frame_support::pallet_prelude::ConstU32<20>;
type MaxMembers = frame_support::pallet_prelude::ConstU32<100>;
type DefaultVote = TechnicalCommitteeDefaultVote;
type WeightInfo = pallet_collective::weights::SubstrateWeight<Runtime>;
type RuntimeOrigin = RuntimeOrigin;
type SetMembersOrigin = EnsureRoot<AccountId>;
type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
}
};
}
......@@ -14,37 +14,36 @@
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
use crate::{entities::IdtyData, AccountId, IdtyIndex};
use crate::{entities::IdtyData, AccountId, Balance, IdtyIndex};
use core::marker::PhantomData;
use pallet_universal_dividend::FirstEligibleUd;
use sp_std::boxed::Box;
use sp_std::vec::Vec;
/// A provider for converting IdtyIndex to associated AccountId.
pub struct IdentityAccountIdProvider<Runtime>(PhantomData<Runtime>);
impl<
impl<Runtime> sp_runtime::traits::Convert<IdtyIndex, Option<AccountId>>
for IdentityAccountIdProvider<Runtime>
where
Runtime: frame_system::Config<AccountId = AccountId>
+ pallet_identity::Config<IdtyIndex = IdtyIndex>,
> sp_runtime::traits::Convert<IdtyIndex, Option<AccountId>>
for IdentityAccountIdProvider<Runtime>
{
fn convert(idty_index: IdtyIndex) -> Option<AccountId> {
pallet_identity::Pallet::<Runtime>::identity(idty_index).map(|idty| idty.owner_key)
}
}
/// A provider for converting AccountId to their associated IdtyIndex.
pub struct IdentityIndexOf<T: pallet_identity::Config>(PhantomData<T>);
impl<T: pallet_identity::Config> sp_runtime::traits::Convert<T::AccountId, Option<T::IdtyIndex>>
for IdentityIndexOf<T>
impl<T> sp_runtime::traits::Convert<T::AccountId, Option<T::IdtyIndex>> for IdentityIndexOf<T>
where
T: pallet_identity::Config,
{
fn convert(account_id: T::AccountId) -> Option<T::IdtyIndex> {
pallet_identity::Pallet::<T>::identity_index_of(account_id)
}
}
/// A provider associating an AccountId to their first eligible UD creation time.
pub struct UdMembersStorage<T: pallet_identity::Config>(PhantomData<T>);
impl<T> frame_support::traits::StoredMap<AccountId, FirstEligibleUd> for UdMembersStorage<T>
where
T: frame_system::Config<AccountId = AccountId>,
......@@ -53,13 +52,14 @@ where
fn get(key: &T::AccountId) -> FirstEligibleUd {
pallet_identity::Pallet::<T>::get(key).first_eligible_ud
}
fn try_mutate_exists<R, E: From<sp_runtime::DispatchError>>(
key: &T::AccountId,
f: impl FnOnce(&mut Option<FirstEligibleUd>) -> Result<R, E>,
) -> Result<R, E> {
pallet_identity::Pallet::<T>::try_mutate_exists(key, |maybe_idty_data| {
if let Some(ref mut idty_data) = maybe_idty_data {
let mut maybe_first_eligible_ud = Some(idty_data.first_eligible_ud);
let mut maybe_first_eligible_ud = Some(idty_data.first_eligible_ud.clone());
let result = f(&mut maybe_first_eligible_ud)?;
if let Some(first_eligible_ud) = maybe_first_eligible_ud {
idty_data.first_eligible_ud = first_eligible_ud;
......@@ -72,37 +72,59 @@ where
}
}
#[allow(clippy::type_complexity)]
pub struct UdMembersStorageIter<T: pallet_identity::Config>(
Box<dyn Iterator<Item = pallet_identity::IdtyValue<T::BlockNumber, T::AccountId, T::IdtyData>>>,
PhantomData<T>,
/// A provider to WoT membership status based on an IdtyIndex.
pub struct IsWoTMemberProvider<T>(PhantomData<T>);
impl<T> sp_runtime::traits::IsMember<<T as pallet_membership::Config>::IdtyId>
for IsWoTMemberProvider<T>
where
T: pallet_distance::Config + pallet_membership::Config + pallet_smith_members::Config,
{
fn is_member(idty_id: &T::IdtyId) -> bool {
pallet_membership::Pallet::<T>::is_member(idty_id)
}
}
#[cfg(feature = "runtime-benchmarks")]
pub struct BenchmarkSetupHandler<T>(PhantomData<T>);
// Macro implementing the BenchmarkSetupHandler trait for pallets requiring identity preparation for benchmarks.
#[cfg(feature = "runtime-benchmarks")]
macro_rules! impl_benchmark_setup_handler {
($t:ty) => {
impl<T> $t for BenchmarkSetupHandler<T>
where
T: pallet_distance::Config,
T: pallet_certification::Config,
<T as pallet_certification::Config>::IdtyIndex: From<u32>,
{
fn force_valid_distance_status(idty_id: &IdtyIndex) -> () {
let _ = pallet_distance::Pallet::<T>::do_valid_distance_status(
*idty_id,
sp_runtime::Perbill::one(),
);
}
impl<T: pallet_identity::Config> From<Option<Vec<u8>>> for UdMembersStorageIter<T> {
fn from(maybe_key: Option<Vec<u8>>) -> Self {
let mut iter = pallet_identity::Identities::<T>::iter_values();
if let Some(key) = maybe_key {
iter.set_last_raw_key(key);
fn add_cert(issuer: &IdtyIndex, receiver: &IdtyIndex) {
let _ = pallet_certification::Pallet::<T>::do_add_cert_checked(
(*issuer).into(),
(*receiver).into(),
false,
);
}
Self(Box::new(iter), PhantomData)
}
};
}
impl<T> Iterator for UdMembersStorageIter<T>
where
T: pallet_identity::Config,
T::IdtyData: Into<FirstEligibleUd>,
{
type Item = (T::AccountId, FirstEligibleUd);
#[cfg(feature = "runtime-benchmarks")]
impl_benchmark_setup_handler!(pallet_membership::SetupBenchmark<<T as pallet_identity::Config>::IdtyIndex, T::AccountId>);
fn next(&mut self) -> Option<Self::Item> {
if let Some(pallet_identity::IdtyValue {
owner_key, data, ..
}) = self.0.next()
/// A provider for retrieving the number of accounts allowed to create the universal dividend.
pub struct MembersCount<T>(PhantomData<T>);
impl<T> frame_support::pallet_prelude::Get<Balance> for MembersCount<T>
where
T: sp_membership::traits::MembersCount,
{
Some((owner_key, data.into()))
} else {
None
}
fn get() -> Balance {
T::members_count() as Balance
}
}
// Copyright 2021 Axiom-Team
//
// This file is part of Duniter-v2S.
//
// Duniter-v2S is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Duniter-v2S is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2022-11-18 (Y/M/D)
//! HOSTNAME: `raspberrypi`, CPU: `ARMv7 Processor rev 3 (v7l)`
//!
//! SHORT-NAME: `block`, LONG-NAME: `BlockExecution`, RUNTIME: `Ğdev`
//! WARMUPS: `10`, REPEAT: `100`
//! WEIGHT-PATH: `.`
//! WEIGHT-METRIC: `Average`, WEIGHT-MUL: `1`, WEIGHT-ADD: `0`
// Executed Command:
// ./duniter
// benchmark
// overhead
// --chain=gdev
// --execution=wasm
// --wasm-execution=interpreted-i-know-what-i-do
// --weight-path=.
// --warmup=10
// --repeat=100
use frame_support::{
parameter_types,
weights::{constants::WEIGHT_PER_NANOS, Weight},
};
parameter_types! {
/// Time to execute an empty block.
/// Calculated by multiplying the *Average* with `1` and adding `0`.
///
/// Stats nanoseconds:
/// Min, Max: 23_866_638, 90_077_105
/// Average: 24_871_527
/// Median: 23_915_377
/// Std-Dev: 6645558.32
///
/// Percentiles nanoseconds:
/// 99th: 30_529_787
/// 95th: 27_134_555
/// 75th: 23_951_395
pub const BlockExecutionWeight: Weight = WEIGHT_PER_NANOS.saturating_mul(24_871_527);
}
#[cfg(test)]
mod test_weights {
use frame_support::weights::constants;
/// Checks that the weight exists and is sane.
// NOTE: If this test fails but you are sure that the generated values are fine,
// you can delete it.
#[test]
fn sane() {
let w = super::BlockExecutionWeight::get();
// At least 100 µs.
assert!(
w.ref_time() >= 100u64 * constants::WEIGHT_PER_MICROS.ref_time(),
"Weight should be at least 100 µs."
);
// At most 50 ms.
assert!(
w.ref_time() <= 50u64 * constants::WEIGHT_PER_MILLIS.ref_time(),
"Weight should be at most 50 ms."
);
}
}
// Copyright 2021-2022 Axiom-Team
//
// This file is part of Duniter-v2S.
//
// Duniter-v2S is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Duniter-v2S is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
//! Autogenerated weights for `pallet_multisig`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2022-06-13, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Interpreted, CHAIN: Some("dev"), DB CACHE: 1024
// Executed Command:
// ./duniter
// benchmark
// --chain=dev
// --steps=50
// --repeat=20
// --pallet=pallet_multisig
// --extrinsic=*
// --execution=wasm
// --wasm-execution=interpreted-i-know-what-i-do
// --heap-pages=4096
// --header=./file_header.txt
// --output=.
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(clippy::unnecessary_cast)]
use frame_support::{traits::Get, weights::Weight};
use sp_std::marker::PhantomData;
/// Weight functions for `pallet_multisig`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_multisig::WeightInfo for WeightInfo<T> {
fn as_multi_threshold_1(z: u32, ) -> Weight {
(Weight::from_ref_time(694_175_000))
// Standard Error: 0
.saturating_add((Weight::from_ref_time(405_000)).saturating_mul(z as u64))
}
// Storage: Multisig Multisigs (r:1 w:1)
// Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0)
fn as_multi_create(s: u32, z: u32, ) -> Weight {
(Weight::from_ref_time(1_258_408_000))
// Standard Error: 752_000
.saturating_add((Weight::from_ref_time(34_672_000)).saturating_mul(s as u64))
// Standard Error: 0
.saturating_add((Weight::from_ref_time(249_000)).saturating_mul(z as u64))
.saturating_add(T::DbWeight::get().reads(2))
.saturating_add(T::DbWeight::get().writes(1))
}
// Storage: Multisig Multisigs (r:1 w:1)
fn as_multi_approve(s: u32, z: u32, ) -> Weight {
(Weight::from_ref_time(865_034_000))
// Standard Error: 878_000
.saturating_add((Weight::from_ref_time(36_962_000)).saturating_mul(s as u64))
// Standard Error: 0
.saturating_add((Weight::from_ref_time(250_000)).saturating_mul(z as u64))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
// Storage: Multisig Multisigs (r:1 w:1)
// Storage: Multisig Calls (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn as_multi_complete(s: u32, z: u32, ) -> Weight {
(Weight::from_ref_time(1_884_292_000))
// Standard Error: 1_339_000
.saturating_add((Weight::from_ref_time(80_505_000)).saturating_mul(s as u64))
// Standard Error: 0
.saturating_add((Weight::from_ref_time(980_000)).saturating_mul(z as u64))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(3))
}
// Storage: Multisig Multisigs (r:1 w:1)
// Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0)
fn approve_as_multi_create(s: u32, ) -> Weight {
(Weight::from_ref_time(1_267_276_000))
// Standard Error: 243_000
.saturating_add((Weight::from_ref_time(33_108_000)).saturating_mul(s as u64))
.saturating_add(T::DbWeight::get().reads(2))
.saturating_add(T::DbWeight::get().writes(1))
}
// Storage: Multisig Multisigs (r:1 w:1)
// Storage: Multisig Calls (r:1 w:0)
fn approve_as_multi_approve(s: u32, ) -> Weight {
(Weight::from_ref_time(865_683_000))
// Standard Error: 403_000
.saturating_add((Weight::from_ref_time(35_735_000)).saturating_mul(s as u64))
.saturating_add(T::DbWeight::get().reads(2))
.saturating_add(T::DbWeight::get().writes(1))
}
// Storage: Multisig Multisigs (r:1 w:1)
// Storage: Multisig Calls (r:1 w:1)
fn cancel_as_multi(s: u32, ) -> Weight {
(Weight::from_ref_time(6_654_037_000))
// Standard Error: 300_000
.saturating_add((Weight::from_ref_time(33_665_000)).saturating_mul(s as u64))
.saturating_add(T::DbWeight::get().reads(2))
.saturating_add(T::DbWeight::get().writes(2))
}
}
// Copyright 2021-2022 Axiom-Team
//
// This file is part of Duniter-v2S.
//
// Duniter-v2S is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Duniter-v2S is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
//! Autogenerated weights for `pallet_proxy`
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2022-06-13, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Interpreted, CHAIN: Some("dev"), DB CACHE: 1024
// Executed Command:
// ./duniter
// benchmark
// --chain=dev
// --steps=50
// --repeat=20
// --pallet=pallet_proxy
// --extrinsic=*
// --execution=wasm
// --wasm-execution=interpreted-i-know-what-i-do
// --heap-pages=4096
// --header=./file_header.txt
// --output=.
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(clippy::unnecessary_cast)]
use frame_support::{traits::Get, weights::Weight};
use sp_std::marker::PhantomData;
/// Weight functions for `pallet_proxy`.
pub struct WeightInfo<T>(PhantomData<T>);
impl<T: frame_system::Config> pallet_proxy::WeightInfo for WeightInfo<T> {
// dummy
fn create_pure(_s:u32)->Weight {Weight::zero()}
// dummy
fn kill_pure(_s:u32)->Weight {Weight::zero()}
// Storage: Proxy Proxies (r:1 w:0)
fn proxy(p: u32, ) -> Weight {
(Weight::from_ref_time(580_976_000))
// Standard Error: 66_000
.saturating_add((Weight::from_ref_time(43_246_000)).saturating_mul(p as u64))
.saturating_add(T::DbWeight::get().reads(1))
}
// Storage: Proxy Proxies (r:1 w:0)
// Storage: Proxy Announcements (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn proxy_announced(a: u32, p: u32, ) -> Weight {
(Weight::from_ref_time(1_543_060_000))
// Standard Error: 372_000
.saturating_add((Weight::from_ref_time(106_336_000)).saturating_mul(a as u64))
// Standard Error: 387_000
.saturating_add((Weight::from_ref_time(37_661_000)).saturating_mul(p as u64))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(2))
}
// Storage: Proxy Announcements (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn remove_announcement(a: u32, _p: u32, ) -> Weight {
(Weight::from_ref_time(1_028_018_000))
// Standard Error: 359_000
.saturating_add((Weight::from_ref_time(105_964_000)).saturating_mul(a as u64))
.saturating_add(T::DbWeight::get().reads(2))
.saturating_add(T::DbWeight::get().writes(2))
}
// Storage: Proxy Announcements (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn reject_announcement(a: u32, _p: u32, ) -> Weight {
(Weight::from_ref_time(1_044_098_000))
// Standard Error: 349_000
.saturating_add((Weight::from_ref_time(106_076_000)).saturating_mul(a as u64))
.saturating_add(T::DbWeight::get().reads(2))
.saturating_add(T::DbWeight::get().writes(2))
}
// Storage: Proxy Proxies (r:1 w:0)
// Storage: Proxy Announcements (r:1 w:1)
// Storage: System Account (r:1 w:1)
fn announce(a: u32, p: u32, ) -> Weight {
(Weight::from_ref_time(1_262_407_000))
// Standard Error: 350_000
.saturating_add((Weight::from_ref_time(104_255_000)).saturating_mul(a as u64))
// Standard Error: 364_000
.saturating_add((Weight::from_ref_time(38_980_000)).saturating_mul(p as u64))
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(2))
}
// Storage: Proxy Proxies (r:1 w:1)
fn add_proxy(p: u32, ) -> Weight {
(Weight::from_ref_time(964_226_000))
// Standard Error: 288_000
.saturating_add((Weight::from_ref_time(55_018_000)).saturating_mul(p as u64))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
// Storage: Proxy Proxies (r:1 w:1)
fn remove_proxy(p: u32, ) -> Weight {
(Weight::from_ref_time(761_347_000))
// Standard Error: 240_000
.saturating_add((Weight::from_ref_time(58_595_000)).saturating_mul(p as u64))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
// Storage: Proxy Proxies (r:1 w:1)
fn remove_proxies(p: u32, ) -> Weight {
(Weight::from_ref_time(706_599_000))
// Standard Error: 55_000
.saturating_add((Weight::from_ref_time(41_943_000)).saturating_mul(p as u64))
.saturating_add(T::DbWeight::get().reads(1))
.saturating_add(T::DbWeight::get().writes(1))
}
}
// Copyright 2021 Axiom-Team
//
// This file is part of Duniter-v2S.
//
// Duniter-v2S is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Duniter-v2S is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2022-11-18 (Y/M/D)
//! HOSTNAME: `raspberrypi`, CPU: `ARMv7 Processor rev 3 (v7l)`
//!
//! DATABASE: `ParityDb`, RUNTIME: `Ğdev`
//! BLOCK-NUM: `BlockId::Number(85630)`
//! SKIP-WRITE: `false`, SKIP-READ: `false`, WARMUPS: `1`
//! STATE-VERSION: `V1`, STATE-CACHE-SIZE: `0`
//! WEIGHT-PATH: `.`
//! METRIC: `Average`, WEIGHT-MUL: `2`, WEIGHT-ADD: `0`
// Executed Command:
// ./duniter
// benchmark
// storage
// -d=/mnt/ssd1/duniter-v2s/t1
// --chain=gdev
// --mul=2
// --weight-path=.
// --state-version=1
/// Storage DB weights for the `Ğdev` runtime and `ParityDb`.
pub mod constants {
use frame_support::{
parameter_types,
weights::{constants, RuntimeDbWeight},
};
parameter_types! {
/// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights
/// are available for brave runtime engineers who may want to try this out as default.
pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight {
/// Time to read one storage item.
/// Calculated by multiplying the *Average* of all values with `2` and adding `0`.
///
/// Stats nanoseconds:
/// Min, Max: 62_017, 5_238_182
/// Average: 125_949
/// Median: 124_943
/// Std-Dev: 19659.02
///
/// Percentiles nanoseconds:
/// 99th: 151_424
/// 95th: 143_017
/// 75th: 133_498
read: 250_000 * constants::WEIGHT_PER_NANOS.ref_time(),
/// Time to write one storage item.
/// Calculated by multiplying the *Average* of all values with `2` and adding `0`.
///
/// Stats nanoseconds:
/// Min, Max: 88_054, 107_065_367
/// Average: 419_064
/// Median: 424_994
/// Std-Dev: 423253.1
///
/// Percentiles nanoseconds:
/// 99th: 611_825
/// 95th: 512_789
/// 75th: 457_938
write: 840_000 * constants::WEIGHT_PER_NANOS.ref_time(),
};
}
#[cfg(test)]
mod test_db_weights {
use super::constants::ParityDbWeight as W;
use frame_support::weights::constants;
/// Checks that all weights exist and have sane values.
// NOTE: If this test fails but you are sure that the generated values are fine,
// you can delete it.
#[test]
fn bound() {
// At least 1 µs.
assert!(
W::get().reads(1).ref_time() >= constants::WEIGHT_PER_MICROS.ref_time(),
"Read weight should be at least 1 µs."
);
assert!(
W::get().writes(1).ref_time() >= constants::WEIGHT_PER_MICROS.ref_time(),
"Write weight should be at least 1 µs."
);
// At most 1 ms.
assert!(
W::get().reads(1).ref_time() <= constants::WEIGHT_PER_MILLIS.ref_time(),
"Read weight should be at most 1 ms."
);
assert!(
W::get().writes(1).ref_time() <= constants::WEIGHT_PER_MILLIS.ref_time(),
"Write weight should be at most 1 ms."
);
}
}
}