diff --git a/.github/workflows/build-and-push-docker-image.yml b/.github/workflows/build-and-push-docker-image.yml index 7891195d90e2a..64bd2d2a98a64 100644 --- a/.github/workflows/build-and-push-docker-image.yml +++ b/.github/workflows/build-and-push-docker-image.yml @@ -36,9 +36,9 @@ jobs: - name: Copy wasm artifact from the image run: | container_id=$(docker create ${{ env.IMAGE_ID }}) - artifact_name=node_runtime.compact.${GITHUB_SHA:0:7}.wasm + artifact_name=node_runtime.compact.compressed.${GITHUB_SHA:0:7}.wasm echo ARTIFACT_NAME=$artifact_name >> $GITHUB_ENV - docker cp $container_id:/home/cere/node-runtime-artifacts/node_runtime.compact.wasm ./$artifact_name + docker cp $container_id:/home/cere/node-runtime-artifacts/node_runtime.compact.compressed.wasm ./$artifact_name - name: Upload wasm artifact uses: actions/upload-artifact@v3 with: diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index b68dd303841d8..f6f714ea52b10 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -209,18 +209,6 @@ default: AWS_SECRET_ACCESS_KEY: vault: cicd/gitlab/$CI_PROJECT_PATH/AWS_SECRET_ACCESS_KEY@kv file: false - AWX_TOKEN: - vault: cicd/gitlab/$CI_PROJECT_PATH/AWX_TOKEN@kv - file: false - CRATES_TOKEN: - vault: cicd/gitlab/$CI_PROJECT_PATH/CRATES_TOKEN@kv - file: false - DOCKER_CHAOS_TOKEN: - vault: cicd/gitlab/$CI_PROJECT_PATH/DOCKER_CHAOS_TOKEN@kv - file: false - DOCKER_CHAOS_USER: - vault: cicd/gitlab/$CI_PROJECT_PATH/DOCKER_CHAOS_USER@kv - file: false GITHUB_EMAIL: vault: cicd/gitlab/$CI_PROJECT_PATH/GITHUB_EMAIL@kv file: false @@ -239,22 +227,13 @@ default: MATRIX_ROOM_ID: vault: cicd/gitlab/$CI_PROJECT_PATH/MATRIX_ROOM_ID@kv file: false - PIPELINE_TOKEN: - vault: cicd/gitlab/$CI_PROJECT_PATH/PIPELINE_TOKEN@kv - file: false - VALIDATOR_KEYS: - vault: cicd/gitlab/$CI_PROJECT_PATH/VALIDATOR_KEYS@kv - file: false - VALIDATOR_KEYS_CHAOS: - vault: cicd/gitlab/$CI_PROJECT_PATH/VALIDATOR_KEYS_CHAOS@kv - file: false + #### stage: .pre skip-if-draft: image: paritytech/tools:latest <<: *kubernetes-env - <<: *vault-secrets stage: .pre rules: - if: $CI_COMMIT_REF_NAME =~ /^[0-9]+$/ # PRs @@ -270,7 +249,6 @@ check-runtime: stage: check image: paritytech/tools:latest <<: *kubernetes-env - <<: *vault-secrets rules: - if: $CI_COMMIT_REF_NAME =~ /^[0-9]+$/ # PRs variables: @@ -285,7 +263,6 @@ check-signed-tag: stage: check image: paritytech/tools:latest <<: *kubernetes-env - <<: *vault-secrets rules: - if: $CI_COMMIT_REF_NAME =~ /^ci-release-.*$/ - if: $CI_COMMIT_REF_NAME =~ /^v[0-9]+\.[0-9]+.*$/ # i.e. v1.0, v2.1rc1 @@ -548,7 +525,6 @@ cargo-check-macos: stage: build <<: *docker-env <<: *test-refs-no-trigger-prs-only - <<: *vault-secrets script: - git clone --depth=1 @@ -747,13 +723,7 @@ publish-rustdoc: image: node:16 variables: GIT_DEPTH: 100 - # --- Following variables are for rustdocs deployment --- - # Space separated values of branches and tags to generate rustdocs - RUSTDOCS_DEPLOY_REFS: "master monthly-2021-09+1 monthly-2021-08 v3.0.0" - # Location of the docs index template - INDEX_TPL: ".maintain/docs-index-tpl.ejs" - # Where the `/latest` symbolic link links to. One of the $RUSTDOCS_DEPLOY_REFS value. - LATEST: "monthly-2021-09+1" + RUSTDOCS_DEPLOY_REFS: "master" rules: - if: $CI_PIPELINE_SOURCE == "pipeline" when: never @@ -783,34 +753,18 @@ publish-rustdoc: - git config remote.origin.url "git@github.com:/paritytech/${CI_PROJECT_NAME}.git" - git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*" - git fetch origin gh-pages - # Install `ejs` and generate index.html based on RUSTDOCS_DEPLOY_REFS - - yarn global add ejs - - 'ejs ${INDEX_TPL} -i "{\"deploy_refs\":\"${RUSTDOCS_DEPLOY_REFS}\",\"repo_name\":\"${CI_PROJECT_NAME}\",\"latest\":\"${LATEST}\"}" > /tmp/index.html' # Save README and docs - cp -r ./crate-docs/ /tmp/doc/ - cp README.md /tmp/doc/ - git checkout gh-pages - # Remove directories no longer necessary, as specified in $RUSTDOCS_DEPLOY_REFS. - # Also ensure $RUSTDOCS_DEPLOY_REFS is not just empty spaces. - # Even though this block spans multiple lines, they are concatenated to run as a single line - # command, so note for the semi-colons in the inner-most code block. - - if [[ ! -z ${RUSTDOCS_DEPLOY_REFS// } ]]; then - for FILE in *; do - if [[ ! " $RUSTDOCS_DEPLOY_REFS " =~ " $FILE " ]]; then - echo "Removing ${FILE}..."; - rm -rf $FILE; - fi - done - fi - # Move the index page & built back - - mv -f /tmp/index.html . + # Install `index-tpl-crud` and generate index.html based on RUSTDOCS_DEPLOY_REFS + - which index-tpl-crud &> /dev/null || yarn global add @substrate/index-tpl-crud + - index-tpl-crud upsert ./index.html ${CI_COMMIT_REF_NAME} # Ensure the destination dir doesn't exist. - rm -rf ${CI_COMMIT_REF_NAME} - mv -f /tmp/doc ${CI_COMMIT_REF_NAME} - # Add the symlink - - '[[ -e "$LATEST" ]] && ln -sf "${LATEST}" latest' # Upload files - - git add --all --force + - git add --all # `git commit` has an exit code of > 0 if there is nothing to commit. # This causes GitLab to exit immediately and marks this job failed. # We don't want to mark the entire job failed if there's nothing to diff --git a/.maintain/monitoring/alerting-rules/alerting-rule-tests.yaml b/.maintain/monitoring/alerting-rules/alerting-rule-tests.yaml index 7ad916f022154..df5e020d067ea 100644 --- a/.maintain/monitoring/alerting-rules/alerting-rule-tests.yaml +++ b/.maintain/monitoring/alerting-rules/alerting-rule-tests.yaml @@ -6,39 +6,39 @@ evaluation_interval: 1m tests: - interval: 1m input_series: - - series: 'polkadot_sub_libp2p_peers_count{ - job="polkadot", - pod="polkadot-abcdef01234-abcdef", - instance="polkadot-abcdef01234-abcdef", + - series: 'substrate_sub_libp2p_peers_count{ + job="substrate", + pod="substrate-abcdef01234-abcdef", + instance="substrate-abcdef01234-abcdef", }' values: '3 2+0x4 1+0x9' # 3 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 - - series: 'polkadot_sub_txpool_validations_scheduled{ - job="polkadot", - pod="polkadot-abcdef01234-abcdef", - instance="polkadot-abcdef01234-abcdef", + - series: 'substrate_sub_txpool_validations_scheduled{ + job="substrate", + pod="substrate-abcdef01234-abcdef", + instance="substrate-abcdef01234-abcdef", }' values: '11+1x10 22+2x30 10043x5' - - series: 'polkadot_sub_txpool_validations_finished{ - job="polkadot", - pod="polkadot-abcdef01234-abcdef", - instance="polkadot-abcdef01234-abcdef", + - series: 'substrate_sub_txpool_validations_finished{ + job="substrate", + pod="substrate-abcdef01234-abcdef", + instance="substrate-abcdef01234-abcdef", }' values: '0+1x42 42x5' - - series: 'polkadot_block_height{ - status="best", job="polkadot", - pod="polkadot-abcdef01234-abcdef", - instance="polkadot-abcdef01234-abcdef", + - series: 'substrate_block_height{ + status="best", job="substrate", + pod="substrate-abcdef01234-abcdef", + instance="substrate-abcdef01234-abcdef", }' values: '1+1x3 4+0x13' # 1 2 3 4 4 4 4 4 4 4 4 4 ... - - series: 'polkadot_block_height{ + - series: 'substrate_block_height{ status="finalized", - job="polkadot", - pod="polkadot-abcdef01234-abcdef", - instance="polkadot-abcdef01234-abcdef", + job="substrate", + pod="substrate-abcdef01234-abcdef", + instance="substrate-abcdef01234-abcdef", }' values: '1+1x3 4+0x13' # 1 2 3 4 4 4 4 4 4 4 4 4 ... @@ -56,13 +56,13 @@ tests: exp_alerts: - exp_labels: severity: warning - pod: polkadot-abcdef01234-abcdef - instance: polkadot-abcdef01234-abcdef - job: polkadot + pod: substrate-abcdef01234-abcdef + instance: substrate-abcdef01234-abcdef + job: substrate status: best exp_annotations: message: "Best block on instance - polkadot-abcdef01234-abcdef increases by less than 1 per + substrate-abcdef01234-abcdef increases by less than 1 per minute for more than 3 minutes." - eval_time: 14m @@ -70,23 +70,23 @@ tests: exp_alerts: - exp_labels: severity: warning - pod: polkadot-abcdef01234-abcdef - instance: polkadot-abcdef01234-abcdef - job: polkadot + pod: substrate-abcdef01234-abcdef + instance: substrate-abcdef01234-abcdef + job: substrate status: best exp_annotations: message: "Best block on instance - polkadot-abcdef01234-abcdef increases by less than 1 per + substrate-abcdef01234-abcdef increases by less than 1 per minute for more than 3 minutes." - exp_labels: severity: critical - pod: polkadot-abcdef01234-abcdef - instance: polkadot-abcdef01234-abcdef - job: polkadot + pod: substrate-abcdef01234-abcdef + instance: substrate-abcdef01234-abcdef + job: substrate status: best exp_annotations: message: "Best block on instance - polkadot-abcdef01234-abcdef increases by less than 1 per + substrate-abcdef01234-abcdef increases by less than 1 per minute for more than 10 minutes." ###################################################################### @@ -101,13 +101,13 @@ tests: exp_alerts: - exp_labels: severity: warning - pod: polkadot-abcdef01234-abcdef - instance: polkadot-abcdef01234-abcdef - job: polkadot + pod: substrate-abcdef01234-abcdef + instance: substrate-abcdef01234-abcdef + job: substrate status: finalized exp_annotations: message: "Finalized block on instance - polkadot-abcdef01234-abcdef increases by less than 1 per + substrate-abcdef01234-abcdef increases by less than 1 per minute for more than 3 minutes." - eval_time: 14m @@ -115,23 +115,23 @@ tests: exp_alerts: - exp_labels: severity: warning - pod: polkadot-abcdef01234-abcdef - instance: polkadot-abcdef01234-abcdef - job: polkadot + pod: substrate-abcdef01234-abcdef + instance: substrate-abcdef01234-abcdef + job: substrate status: finalized exp_annotations: message: "Finalized block on instance - polkadot-abcdef01234-abcdef increases by less than 1 per + substrate-abcdef01234-abcdef increases by less than 1 per minute for more than 3 minutes." - exp_labels: severity: critical - pod: polkadot-abcdef01234-abcdef - instance: polkadot-abcdef01234-abcdef - job: polkadot + pod: substrate-abcdef01234-abcdef + instance: substrate-abcdef01234-abcdef + job: substrate status: finalized exp_annotations: message: "Finalized block on instance - polkadot-abcdef01234-abcdef increases by less than 1 per + substrate-abcdef01234-abcdef increases by less than 1 per minute for more than 10 minutes." ###################################################################### @@ -152,12 +152,12 @@ tests: exp_alerts: - exp_labels: severity: warning - pod: polkadot-abcdef01234-abcdef - instance: polkadot-abcdef01234-abcdef - job: polkadot + pod: substrate-abcdef01234-abcdef + instance: substrate-abcdef01234-abcdef + job: substrate exp_annotations: message: "The transaction pool size on node - polkadot-abcdef01234-abcdef has been monotonically + substrate-abcdef01234-abcdef has been monotonically increasing for more than 10 minutes." - eval_time: 43m alertname: TransactionQueueSizeIncreasing @@ -167,21 +167,21 @@ tests: exp_alerts: - exp_labels: severity: warning - pod: polkadot-abcdef01234-abcdef - instance: polkadot-abcdef01234-abcdef - job: polkadot + pod: substrate-abcdef01234-abcdef + instance: substrate-abcdef01234-abcdef + job: substrate exp_annotations: message: "The transaction pool size on node - polkadot-abcdef01234-abcdef has been monotonically + substrate-abcdef01234-abcdef has been monotonically increasing for more than 10 minutes." - exp_labels: severity: warning - pod: polkadot-abcdef01234-abcdef - instance: polkadot-abcdef01234-abcdef - job: polkadot + pod: substrate-abcdef01234-abcdef + instance: substrate-abcdef01234-abcdef + job: substrate exp_annotations: message: "The transaction pool size on node - polkadot-abcdef01234-abcdef has been monotonically + substrate-abcdef01234-abcdef has been monotonically increasing for more than 30 minutes." - eval_time: 49m alertname: TransactionQueueSizeHigh @@ -191,12 +191,12 @@ tests: exp_alerts: - exp_labels: severity: warning - pod: polkadot-abcdef01234-abcdef - instance: polkadot-abcdef01234-abcdef - job: polkadot + pod: substrate-abcdef01234-abcdef + instance: substrate-abcdef01234-abcdef + job: substrate exp_annotations: message: "The transaction pool size on node - polkadot-abcdef01234-abcdef has been above 10_000 for more + substrate-abcdef01234-abcdef has been above 10_000 for more than 5 minutes." ###################################################################### @@ -211,11 +211,11 @@ tests: exp_alerts: - exp_labels: severity: warning - pod: polkadot-abcdef01234-abcdef - instance: polkadot-abcdef01234-abcdef - job: polkadot + pod: substrate-abcdef01234-abcdef + instance: substrate-abcdef01234-abcdef + job: substrate exp_annotations: - message: "The node polkadot-abcdef01234-abcdef has less + message: "The node substrate-abcdef01234-abcdef has less than 3 peers for more than 3 minutes" - eval_time: 16m # Values: 3 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 @@ -223,17 +223,17 @@ tests: exp_alerts: - exp_labels: severity: warning - pod: polkadot-abcdef01234-abcdef - instance: polkadot-abcdef01234-abcdef - job: polkadot + pod: substrate-abcdef01234-abcdef + instance: substrate-abcdef01234-abcdef + job: substrate exp_annotations: - message: "The node polkadot-abcdef01234-abcdef has less + message: "The node substrate-abcdef01234-abcdef has less than 3 peers for more than 3 minutes" - exp_labels: severity: critical - pod: polkadot-abcdef01234-abcdef - instance: polkadot-abcdef01234-abcdef - job: polkadot + pod: substrate-abcdef01234-abcdef + instance: substrate-abcdef01234-abcdef + job: substrate exp_annotations: - message: "The node polkadot-abcdef01234-abcdef has less + message: "The node substrate-abcdef01234-abcdef has less than 3 peers for more than 15 minutes" diff --git a/.maintain/monitoring/alerting-rules/alerting-rules.yaml b/.maintain/monitoring/alerting-rules/alerting-rules.yaml index 2711610024330..4171f92f68fef 100644 --- a/.maintain/monitoring/alerting-rules/alerting-rules.yaml +++ b/.maintain/monitoring/alerting-rules/alerting-rules.yaml @@ -1,5 +1,5 @@ groups: -- name: polkadot.rules +- name: substrate.rules rules: ############################################################################## @@ -10,7 +10,7 @@ groups: annotations: message: 'Best block on instance {{ $labels.instance }} increases by less than 1 per minute for more than 3 minutes.' - expr: increase(polkadot_block_height{status="best"}[1m]) < 1 + expr: increase(substrate_block_height{status="best"}[1m]) < 1 for: 3m labels: severity: warning @@ -18,7 +18,7 @@ groups: annotations: message: 'Best block on instance {{ $labels.instance }} increases by less than 1 per minute for more than 10 minutes.' - expr: increase(polkadot_block_height{status="best"}[1m]) < 1 + expr: increase(substrate_block_height{status="best"}[1m]) < 1 for: 10m labels: severity: critical @@ -28,7 +28,7 @@ groups: ############################################################################## - alert: BlockFinalizationSlow - expr: increase(polkadot_block_height{status="finalized"}[1m]) < 1 + expr: increase(substrate_block_height{status="finalized"}[1m]) < 1 for: 3m labels: severity: warning @@ -36,7 +36,7 @@ groups: message: 'Finalized block on instance {{ $labels.instance }} increases by less than 1 per minute for more than 3 minutes.' - alert: BlockFinalizationSlow - expr: increase(polkadot_block_height{status="finalized"}[1m]) < 1 + expr: increase(substrate_block_height{status="finalized"}[1m]) < 1 for: 10m labels: severity: critical @@ -47,8 +47,8 @@ groups: # Under the assumption of an average block production of 6 seconds, # "best" and "finalized" being more than 10 blocks apart would imply # more than a 1 minute delay between block production and finalization. - expr: '(polkadot_block_height{status="best"} - ignoring(status) - polkadot_block_height{status="finalized"}) > 10' + expr: '(substrate_block_height{status="best"} - ignoring(status) + substrate_block_height{status="finalized"}) > 10' for: 8m labels: severity: critical @@ -61,8 +61,8 @@ groups: ############################################################################## - alert: TransactionQueueSizeIncreasing - expr: 'increase(polkadot_sub_txpool_validations_scheduled[5m]) - - increase(polkadot_sub_txpool_validations_finished[5m]) > 0' + expr: 'increase(substrate_sub_txpool_validations_scheduled[5m]) - + increase(substrate_sub_txpool_validations_finished[5m]) > 0' for: 10m labels: severity: warning @@ -70,8 +70,8 @@ groups: message: 'The transaction pool size on node {{ $labels.instance }} has been monotonically increasing for more than 10 minutes.' - alert: TransactionQueueSizeIncreasing - expr: 'increase(polkadot_sub_txpool_validations_scheduled[5m]) - - increase(polkadot_sub_txpool_validations_finished[5m]) > 0' + expr: 'increase(substrate_sub_txpool_validations_scheduled[5m]) - + increase(substrate_sub_txpool_validations_finished[5m]) > 0' for: 30m labels: severity: warning @@ -79,8 +79,8 @@ groups: message: 'The transaction pool size on node {{ $labels.instance }} has been monotonically increasing for more than 30 minutes.' - alert: TransactionQueueSizeHigh - expr: 'polkadot_sub_txpool_validations_scheduled - - polkadot_sub_txpool_validations_finished > 10000' + expr: 'substrate_sub_txpool_validations_scheduled - + substrate_sub_txpool_validations_finished > 10000' for: 5m labels: severity: warning @@ -93,7 +93,7 @@ groups: ############################################################################## - alert: NumberOfPeersLow - expr: polkadot_sub_libp2p_peers_count < 3 + expr: substrate_sub_libp2p_peers_count < 3 for: 3m labels: severity: warning @@ -101,7 +101,7 @@ groups: message: 'The node {{ $labels.instance }} has less than 3 peers for more than 3 minutes' - alert: NumberOfPeersLow - expr: polkadot_sub_libp2p_peers_count < 3 + expr: substrate_sub_libp2p_peers_count < 3 for: 15m labels: severity: critical @@ -109,7 +109,7 @@ groups: message: 'The node {{ $labels.instance }} has less than 3 peers for more than 15 minutes' - alert: NoIncomingConnection - expr: increase(polkadot_sub_libp2p_incoming_connections_total[20m]) == 0 + expr: increase(substrate_sub_libp2p_incoming_connections_total[20m]) == 0 labels: severity: warning annotations: @@ -121,7 +121,7 @@ groups: ############################################################################## - alert: NumberOfFileDescriptorsHigh - expr: 'node_filefd_allocated{domain=~"kusama|polkadot"} > 10000' + expr: 'node_filefd_allocated{chain!=""} > 10000' for: 3m labels: severity: warning @@ -134,9 +134,9 @@ groups: ############################################################################## - alert: AuthorityDiscoveryDiscoveryFailureHigh - expr: 'polkadot_authority_discovery_handle_value_found_event_failure / + expr: 'substrate_authority_discovery_handle_value_found_event_failure / ignoring(name) - polkadot_authority_discovery_dht_event_received{name="value_found"} > 0.5' + substrate_authority_discovery_dht_event_received{name="value_found"} > 0.5' for: 2h labels: severity: warning @@ -147,9 +147,9 @@ groups: - alert: UnboundedChannelPersistentlyLarge expr: '( - (polkadot_unbounded_channel_len{action = "send"} - - ignoring(action) polkadot_unbounded_channel_len{action = "received"}) - or on(instance) polkadot_unbounded_channel_len{action = "send"} + (substrate_unbounded_channel_len{action = "send"} - + ignoring(action) substrate_unbounded_channel_len{action = "received"}) + or on(instance) substrate_unbounded_channel_len{action = "send"} ) >= 200' for: 5m labels: @@ -160,9 +160,9 @@ groups: - alert: UnboundedChannelVeryLarge expr: '( - (polkadot_unbounded_channel_len{action = "send"} - - ignoring(action) polkadot_unbounded_channel_len{action = "received"}) - or on(instance) polkadot_unbounded_channel_len{action = "send"} + (substrate_unbounded_channel_len{action = "send"} - + ignoring(action) substrate_unbounded_channel_len{action = "received"}) + or on(instance) substrate_unbounded_channel_len{action = "send"} ) > 15000' labels: severity: warning diff --git a/.maintain/monitoring/grafana-dashboards/substrate-networking.json b/.maintain/monitoring/grafana-dashboards/substrate-networking.json index 46942cf582fc6..abd675ed13ec3 100644 --- a/.maintain/monitoring/grafana-dashboards/substrate-networking.json +++ b/.maintain/monitoring/grafana-dashboards/substrate-networking.json @@ -4,7 +4,7 @@ "name": "VAR_METRIC_NAMESPACE", "type": "constant", "label": "Prefix of the metrics", - "value": "polkadot", + "value": "substrate", "description": "" } ], diff --git a/.maintain/monitoring/grafana-dashboards/substrate-service-tasks.json b/.maintain/monitoring/grafana-dashboards/substrate-service-tasks.json index 2f08ac7bb34c5..ce7e9f78cd8ae 100644 --- a/.maintain/monitoring/grafana-dashboards/substrate-service-tasks.json +++ b/.maintain/monitoring/grafana-dashboards/substrate-service-tasks.json @@ -4,7 +4,7 @@ "name": "VAR_METRIC_NAMESPACE", "type": "constant", "label": "Prefix of the metrics", - "value": "polkadot", + "value": "substrate", "description": "" } ], diff --git a/.maintain/node-template-release/Cargo.toml b/.maintain/node-template-release/Cargo.toml index 26256e8363301..667281f6dcad7 100644 --- a/.maintain/node-template-release/Cargo.toml +++ b/.maintain/node-template-release/Cargo.toml @@ -9,7 +9,7 @@ license = "GPL-3.0" toml = "0.4" tar = "0.4" glob = "0.2" -structopt = "0.3" +clap = { version = "3.0", features = ["derive"] } tempfile = "3" fs_extra = "1" git2 = "0.8" diff --git a/.maintain/node-template-release/src/main.rs b/.maintain/node-template-release/src/main.rs index 7dcb1f0f4d816..62e9b66715768 100644 --- a/.maintain/node-template-release/src/main.rs +++ b/.maintain/node-template-release/src/main.rs @@ -1,4 +1,4 @@ -use structopt::StructOpt; +use clap::Parser; use std::{ collections::HashMap, @@ -26,13 +26,13 @@ const SUBSTRATE_GIT_URL: &str = "https://github.com/paritytech/substrate.git"; type CargoToml = HashMap; -#[derive(StructOpt)] +#[derive(Parser)] struct Options { /// The path to the `node-template` source. - #[structopt(parse(from_os_str))] + #[clap(parse(from_os_str))] node_template: PathBuf, /// The path where to output the generated `tar.gz` file. - #[structopt(parse(from_os_str))] + #[clap(parse(from_os_str))] output: PathBuf, } @@ -209,7 +209,7 @@ fn build_and_test(path: &Path, cargo_tomls: &[PathBuf]) { } fn main() { - let options = Options::from_args(); + let options = Options::parse(); let build_dir = tempfile::tempdir().expect("Creates temp build dir"); @@ -261,8 +261,7 @@ fn main() { // adding root rustfmt to node template build path let node_template_rustfmt_toml_path = node_template_path.join("rustfmt.toml"); - let root_rustfmt_toml = - &options.node_template.join("../../rustfmt.toml"); + let root_rustfmt_toml = &options.node_template.join("../../rustfmt.toml"); if root_rustfmt_toml.exists() { fs::copy(&root_rustfmt_toml, &node_template_rustfmt_toml_path) .expect("Copying rustfmt.toml."); diff --git a/.maintain/rustdocs-release.sh b/.maintain/rustdocs-release.sh new file mode 100755 index 0000000000000..2a1e141e63ad2 --- /dev/null +++ b/.maintain/rustdocs-release.sh @@ -0,0 +1,244 @@ +#!/usr/bin/env bash +# set -x + +# This script manages the deployment of Substrate rustdocs to https://paritytech.github.io/substrate/. +# - With `deploy` sub-command, it will checkout the passed-in branch/tag ref, build the rustdocs +# locally (this takes some time), update the `index.html` index page, and push it to remote +# `gh-pages` branch. So users running this command need to have write access to the remote +# `gh-pages` branch. This sub-command depends on [@substrate/index-tpl-crud](https://www.npmjs.com/package/@substrate/index-tpl-crud) +# to update the DOM of index.html page. +# - With `remove` sub-command, it will remove the deployed rustdocs from `gh-pages`, and update the +# index.html page as necessary. It may remove the `latest` symbolic link. +# +# Examples: +# # Showing help text +# rustdocs-release.sh -h +# +# # Deploy rustdocs of `monthly-2021-10` tag +# rustdocs-release.sh deploy monthly-2021-10 +# +# # In addition to the above, the `latest` symlink will point to this version of rustdocs +# rustdocs-release.sh deploy -l monthly-2021-10 +# +# # Remove the rustdocs of `monthly-2021-10` from `gh-pages`. +# rustdocs-release.sh remove monthly-2021-10 +# +# Dependencies: +# - @substrate/index-tpl-crud - https://www.npmjs.com/package/@substrate/index-tpl-crud +# + +# Script setting +# The git repo http URL +REMOTE_REPO="https://github.com/paritytech/substrate.git" +TMP_PREFIX="/tmp" # tmp location that the built doc is copied to. +DOC_INDEX_PAGE="sc_service/index.html" + +# Set to `true` if using cargo `nightly` toolchain to build the doc. +# Set to `false` to use the default cargo toolchain. This is preferred if you want to build +# the rustdocs with a pinned nightly version set to your default toolchain. +CARGO_NIGHTLY=false + +# Set the git remote name. Most of the time the default is `origin`. +GIT_REMOTE="origin" +LATEST=false + +# Setting the help text +declare -A HELP_TXT +HELP_TXT["deploy"]=$(cat <<-EOH +Build and deploy the rustdocs of the specified branch/tag to \`gh-pages\` branch. + + usage: $0 deploy [-l] + example: $0 deploy -l monthly-2021-10 + + options: + -l The \`latest\` path will be sym'linked to this rustdocs version +EOH +) + +HELP_TXT["remove"]=$(cat <<-EOH +Remove the rustdocs of the specified version from \`gh-pages\` branch. + + usage: $0 remove + example: $0 remove monthly-2021-10 +EOH +) + +set_and_check_rustdoc_ref() { + [[ -z "$1" ]] && { + echo -e "git branch_ref is not specified.\n" + echo "${HELP_TXT[$2]}" + exit 1 + } + BUILD_RUSTDOC_REF=$1 +} + +check_local_change() { + # Check there is no local changes before proceeding + [[ -n $(git status --porcelain) ]] \ + && echo "Local changes exist, please either discard or commit them as this command will change the current checkout branch." \ + && exit 1 +} + +build_rustdocs() { + # Build the docs + time cargo $($CARGO_NIGHTLY && echo "+nightly") doc --workspace --all-features --verbose \ + || { echo "Generate $1 rustdocs failed" && exit 1; } + rm -f target/doc/.lock + + # Moving the built doc to the tmp location + mv target/doc "${2}" + [[ -n "${DOC_INDEX_PAGE}" ]] \ + && echo "" > "${2}/index.html" +} + +upsert_index_page() { + # Check if `index-tpl-crud` exists + which index-tpl-crud &> /dev/null || yarn global add @substrate/index-tpl-crud + index-tpl-crud upsert $($1 && echo "-l") ./index.html "$2" +} + +rm_index_page() { + which index-tpl-crud &> /dev/null || yarn global add @substrate/index-tpl-crud + index-tpl-crud rm ./index.html "$1" +} + +git_add_commit_push() { + git add --all + git commit -m "$1" || echo "Nothing to commit" + git push "${GIT_REMOTE}" gh-pages --force +} + +import_gh_key() { + [[ -n $GITHUB_SSH_PRIV_KEY ]] && { + eval $(ssh-agent) + ssh-add - <<< $GITHUB_SSH_PRIV_KEY + } + + # Adding github.com as known_hosts + ssh-keygen -F github.com &>/dev/null || { + [[ -e ~/.ssh ]] || mkdir ~/.ssh + [[ -e ~/.ssh/known_hosts ]] || touch ~/.ssh/known_hosts + ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts + } +} + +deploy_main() { + check_local_change + import_gh_key + + CURRENT_GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) + TMP_PROJECT_PATH="${TMP_PREFIX}/${PROJECT_NAME}" + DOC_PATH="${TMP_PROJECT_PATH}/${BUILD_RUSTDOC_REF}" + + # Build the tmp project path + rm -rf "${TMP_PROJECT_PATH}" && mkdir "${TMP_PROJECT_PATH}" + + # Copy .gitignore file to tmp + [[ -e "${PROJECT_PATH}/.gitignore" ]] && cp "${PROJECT_PATH}/.gitignore" "${TMP_PROJECT_PATH}" + + git fetch --all + git checkout -f ${BUILD_RUSTDOC_REF} || { echo "Checkout \`${BUILD_RUSTDOC_REF}\` error." && exit 1; } + build_rustdocs "${BUILD_RUSTDOC_REF}" "${DOC_PATH}" + + # git checkout `gh-pages` branch + git fetch "${GIT_REMOTE}" gh-pages + git checkout gh-pages + # Move the built back + [[ -e "${TMP_PROJECT_PATH}/.gitignore" ]] && cp -f "${TMP_PROJECT_PATH}/.gitignore" . + # Ensure the destination dir doesn't exist under current path. + rm -rf "${BUILD_RUSTDOC_REF}" + mv -f "${DOC_PATH}" "${BUILD_RUSTDOC_REF}" + + upsert_index_page $LATEST "${BUILD_RUSTDOC_REF}" + # Add the latest symlink + $LATEST && rm -rf latest && ln -sf "${BUILD_RUSTDOC_REF}" latest + + git_add_commit_push "___Deployed rustdocs of ${BUILD_RUSTDOC_REF}___" + # Clean up + # Remove the tmp asset created + rm -rf "${TMP_PROJECT_PATH}" + # Resume back previous checkout branch. + git checkout -f "$CURRENT_GIT_BRANCH" +} + +remove_main() { + check_local_change + import_gh_key + + CURRENT_GIT_BRANCH=$(git rev-parse --abbrev-ref HEAD) + + # git checkout `gh-pages` branch + git fetch "${GIT_REMOTE}" gh-pages + git checkout gh-pages + + rm -rf "${BUILD_RUSTDOC_REF}" + rm_index_page "${BUILD_RUSTDOC_REF}" + # check if the destination of `latest` exists and rmove if not. + [[ -e "latest" ]] || rm latest + + git_add_commit_push "___Removed rustdocs of ${BUILD_RUSTDOC_REF}___" + + # Resume back previous checkout branch. + git checkout -f "$CURRENT_GIT_BRANCH" +} + +# ---- The script execution entry point starts here ---- + +# Arguments handling +SUBCMD=$1 +[[ $SUBCMD == "deploy" || $SUBCMD == "remove" ]] \ + || { echo "Please specify a subcommand of \`deploy\` or \`remove\`" && exit 1 ;} +shift + +# After removing the subcommand, there could only be 1 or 2 parameters afterward +[[ $# -lt 1 || $# -gt 2 ]] && { + echo "${HELP_TXT[${SUBCMD}]}" + exit 1 +} + +# Parsing options and argument for `deploy` subcommand +[[ $SUBCMD == "deploy" ]] && { + while getopts :lh opt; do + case $opt in + l) + LATEST=true + ;; + h) + echo "${HELP_TXT[$SUBCMD]}" + exit 0 + ;; + \?) + echo "Invalid option: -$OPTARG" >&2 + exit 1 + ;; + esac + done +} +# Parsing options and argument for `remove` subcommand +[[ $SUBCMD == "remove" ]] && { + while getopts :h opt; do + case $opt in + h) + echo "${HELP_TXT[$SUBCMD]}" + exit 0 + ;; + \?) + echo "Invalid option: -$OPTARG" >&2 + exit 1 + ;; + esac + done +} + +shift $(($OPTIND - 1)) +set_and_check_rustdoc_ref ${1:-''} $SUBCMD + +SCRIPT=$(realpath $0) +SCRIPT_PATH=$(dirname $SCRIPT) +PROJECT_PATH=$(dirname ${SCRIPT_PATH}) +PROJECT_NAME=$(basename "$PROJECT_PATH") + +pushd "${PROJECT_PATH}" &>/dev/null +[[ $SUBCMD == "deploy" ]] && deploy_main +[[ $SUBCMD == "remove" ]] && remove_main +popd &>/dev/null diff --git a/Cargo.lock b/Cargo.lock index 580da5ad074c3..feb721e6092cf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -520,7 +520,6 @@ version = "4.0.0-dev" dependencies = [ "beefy-gadget", "beefy-primitives", - "derive_more", "futures 0.3.16", "jsonrpc-core", "jsonrpc-core-client", @@ -928,13 +927,13 @@ name = "chain-spec-builder" version = "2.0.0" dependencies = [ "ansi_term", + "clap 3.0.7", "node-cli", - "rand 0.7.3", + "rand 0.8.4", "sc-chain-spec", "sc-keystore", "sp-core", "sp-keystore", - "structopt", ] [[package]] @@ -996,13 +995,48 @@ version = "2.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" dependencies = [ - "ansi_term", - "atty", "bitflags", - "strsim 0.8.0", - "textwrap", + "textwrap 0.11.0", "unicode-width", - "vec_map", +] + +[[package]] +name = "clap" +version = "3.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12e8611f9ae4e068fa3e56931fded356ff745e70987ff76924a6e0ab1c8ef2e3" +dependencies = [ + "atty", + "bitflags", + "clap_derive", + "indexmap", + "lazy_static", + "os_str_bytes", + "strsim", + "termcolor", + "textwrap 0.14.2", +] + +[[package]] +name = "clap_complete" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a394f7ec0715b42a4e52b294984c27c9a61f77c8d82f7774c5198350be143f19" +dependencies = [ + "clap 3.0.7", +] + +[[package]] +name = "clap_derive" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a0645a430ec9136d2d701e54a95d557de12649a9dd7109ced3187e648ac824" +dependencies = [ + "heck 0.4.0", + "proc-macro-error", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -1256,7 +1290,7 @@ checksum = "1604dafd25fba2fe2d5895a9da139f8dc9b319a5fe5354ca137cbbce4e178d10" dependencies = [ "atty", "cast", - "clap", + "clap 2.34.0", "criterion-plot", "csv", "futures 0.3.16", @@ -1404,7 +1438,7 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1a816186fa68d9e426e3cb4ae4dff1fcd8e4a2c34b781bf7a822574a0d0aac8" dependencies = [ - "sct", + "sct 0.6.0", ] [[package]] @@ -1483,7 +1517,7 @@ dependencies = [ "ident_case", "proc-macro2", "quote", - "strsim 0.10.0", + "strsim", "syn", ] @@ -1741,7 +1775,7 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c5f0096a91d210159eceb2ff5e1c4da18388a170e1e3ce948aac9c8fdbbf595" dependencies = [ - "heck", + "heck 0.3.2", "proc-macro2", "quote", "syn", @@ -2004,6 +2038,7 @@ dependencies = [ "parity-scale-codec", "paste 1.0.6", "scale-info", + "serde", "sp-api", "sp-application-crypto", "sp-io", @@ -2020,6 +2055,7 @@ version = "4.0.0-dev" dependencies = [ "Inflector", "chrono", + "clap 3.0.7", "frame-benchmarking", "frame-support", "handlebars", @@ -2031,12 +2067,12 @@ dependencies = [ "sc-executor", "sc-service", "serde", + "serde_json", "sp-core", "sp-externalities", "sp-keystore", "sp-runtime", "sp-state-machine", - "structopt", ] [[package]] @@ -2391,8 +2427,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a1387e07917c711fb4ee4f48ea0adb04a3c9739e53ef85bf43ae1edc2937a8b" dependencies = [ "futures-io", - "rustls", - "webpki", + "rustls 0.19.1", + "webpki 0.21.4", ] [[package]] @@ -2450,7 +2486,6 @@ dependencies = [ "num-format", "pallet-staking", "sp-io", - "structopt", ] [[package]] @@ -2653,6 +2688,12 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "heck" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" + [[package]] name = "hermit-abi" version = "0.1.18" @@ -2835,11 +2876,11 @@ dependencies = [ "futures-util", "hyper 0.14.16", "log 0.4.14", - "rustls", - "rustls-native-certs", + "rustls 0.19.1", + "rustls-native-certs 0.5.0", "tokio", - "tokio-rustls", - "webpki", + "tokio-rustls 0.22.0", + "webpki 0.21.4", ] [[package]] @@ -3201,19 +3242,73 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6373a33d987866ccfe1af4bc11b089dce941764313f9fd8b7cf13fcb51b72dc5" dependencies = [ - "jsonrpsee-proc-macros", - "jsonrpsee-types", + "jsonrpsee-types 0.4.1", "jsonrpsee-utils", - "jsonrpsee-ws-client", + "jsonrpsee-ws-client 0.4.1", +] + +[[package]] +name = "jsonrpsee" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05fd8cd6c6b1bbd06881d2cf88f1fc83cc36c98f2219090f839115fb4a956cb9" +dependencies = [ + "jsonrpsee-core", + "jsonrpsee-proc-macros", + "jsonrpsee-types 0.8.0", + "jsonrpsee-ws-client 0.8.0", +] + +[[package]] +name = "jsonrpsee-client-transport" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3303cdf246e6ab76e2866fb3d9acb6c76a068b1b28bd923a1b7a8122257ad7b5" +dependencies = [ + "futures 0.3.16", + "http", + "jsonrpsee-core", + "jsonrpsee-types 0.8.0", + "pin-project 1.0.10", + "rustls-native-certs 0.6.1", + "soketto 0.7.1", + "thiserror", + "tokio", + "tokio-rustls 0.23.2", + "tokio-util", + "tracing", + "webpki-roots 0.22.2", +] + +[[package]] +name = "jsonrpsee-core" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f220b5a238dc7992b90f1144fbf6eaa585872c9376afe6fe6863ffead6191bf3" +dependencies = [ + "anyhow", + "arrayvec 0.7.1", + "async-trait", + "beef", + "futures-channel", + "futures-util", + "hyper 0.14.16", + "jsonrpsee-types 0.8.0", + "rustc-hash", + "serde", + "serde_json", + "soketto 0.7.1", + "thiserror", + "tokio", + "tracing", ] [[package]] name = "jsonrpsee-proc-macros" -version = "0.4.1" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d802063f7a3c867456955f9d2f15eb3ee0edb5ec9ec2b5526324756759221c0f" +checksum = "4299ebf790ea9de1cb72e73ff2ae44c723ef264299e5e2d5ef46a371eb3ac3d8" dependencies = [ - "log 0.4.14", "proc-macro-crate 1.1.0", "proc-macro2", "quote", @@ -3235,10 +3330,24 @@ dependencies = [ "log 0.4.14", "serde", "serde_json", - "soketto 0.7.0", + "soketto 0.7.1", "thiserror", ] +[[package]] +name = "jsonrpsee-types" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1b3f601bbbe45cd63f5407b6f7d7950e08a7d4f82aa699ff41a4a5e9e54df58" +dependencies = [ + "anyhow", + "beef", + "serde", + "serde_json", + "thiserror", + "tracing", +] + [[package]] name = "jsonrpsee-utils" version = "0.4.1" @@ -3247,7 +3356,7 @@ checksum = "0109c4f972058f3b1925b73a17210aff7b63b65967264d0045d15ee88fe84f0c" dependencies = [ "arrayvec 0.7.1", "beef", - "jsonrpsee-types", + "jsonrpsee-types 0.4.1", ] [[package]] @@ -3261,19 +3370,30 @@ dependencies = [ "fnv", "futures 0.3.16", "http", - "jsonrpsee-types", + "jsonrpsee-types 0.4.1", "log 0.4.14", "pin-project 1.0.10", - "rustls-native-certs", + "rustls-native-certs 0.5.0", "serde", "serde_json", - "soketto 0.7.0", + "soketto 0.7.1", "thiserror", "tokio", - "tokio-rustls", + "tokio-rustls 0.22.0", "tokio-util", ] +[[package]] +name = "jsonrpsee-ws-client" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aff425cee7c779e33920913bc695447416078ee6d119f443f3060feffa4e86b5" +dependencies = [ + "jsonrpsee-client-transport", + "jsonrpsee-core", + "jsonrpsee-types 0.8.0", +] + [[package]] name = "keccak" version = "0.1.0" @@ -3881,9 +4001,9 @@ dependencies = [ "log 0.4.14", "quicksink", "rw-stream-sink", - "soketto 0.7.0", + "soketto 0.7.1", "url 2.2.1", - "webpki-roots", + "webpki-roots 0.21.0", ] [[package]] @@ -4516,6 +4636,7 @@ dependencies = [ name = "node-bench" version = "0.9.0-dev" dependencies = [ + "clap 3.0.7", "derive_more", "fs_extra", "futures 0.3.16", @@ -4545,7 +4666,6 @@ dependencies = [ "sp-timestamp", "sp-tracing", "sp-trie", - "structopt", "tempfile", ] @@ -4555,13 +4675,15 @@ version = "3.0.0-dev" dependencies = [ "assert_cmd", "async-std", + "clap 3.0.7", + "clap_complete", "criterion", "frame-benchmarking-cli", "frame-system", "frame-system-rpc-runtime-api", "futures 0.3.16", "hex-literal", - "jsonrpsee-ws-client", + "jsonrpsee-ws-client 0.4.1", "log 0.4.14", "nix", "node-executor", @@ -4576,7 +4698,7 @@ dependencies = [ "pallet-transaction-payment", "parity-scale-codec", "platforms", - "rand 0.7.3", + "rand 0.8.4", "regex", "remote-externalities", "sc-authority-discovery", @@ -4622,7 +4744,6 @@ dependencies = [ "sp-transaction-pool", "sp-transaction-storage-proof", "sp-trie", - "structopt", "substrate-build-script-utils", "substrate-frame-cli", "tempfile", @@ -4668,7 +4789,7 @@ dependencies = [ name = "node-inspect" version = "0.9.0-dev" dependencies = [ - "derive_more", + "clap 3.0.7", "parity-scale-codec", "sc-cli", "sc-client-api", @@ -4677,7 +4798,7 @@ dependencies = [ "sp-blockchain", "sp-core", "sp-runtime", - "structopt", + "thiserror", ] [[package]] @@ -4750,6 +4871,7 @@ dependencies = [ "pallet-contracts", "pallet-contracts-primitives", "pallet-contracts-rpc-runtime-api", + "pallet-conviction-voting", "pallet-democracy", "pallet-election-provider-multi-phase", "pallet-elections-phragmen", @@ -4768,6 +4890,7 @@ dependencies = [ "pallet-proxy", "pallet-randomness-collective-flip", "pallet-recovery", + "pallet-referenda", "pallet-scheduler", "pallet-session", "pallet-session-benchmarking", @@ -4811,15 +4934,16 @@ dependencies = [ name = "node-runtime-generate-bags" version = "3.0.0" dependencies = [ + "clap 3.0.7", "generate-bags", "node-runtime", - "structopt", ] [[package]] name = "node-template" -version = "3.0.0" +version = "4.0.0-dev" dependencies = [ + "clap 3.0.7", "frame-benchmarking", "frame-benchmarking-cli", "jsonrpc-core", @@ -4848,14 +4972,13 @@ dependencies = [ "sp-finality-grandpa", "sp-runtime", "sp-timestamp", - "structopt", "substrate-build-script-utils", "substrate-frame-rpc-system", ] [[package]] name = "node-template-runtime" -version = "3.0.0" +version = "4.0.0-dev" dependencies = [ "frame-benchmarking", "frame-executive", @@ -5140,6 +5263,15 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "os_str_bytes" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64" +dependencies = [ + "memchr", +] + [[package]] name = "output_vt100" version = "0.1.2" @@ -5323,7 +5455,6 @@ dependencies = [ name = "pallet-bags-list-remote-tests" version = "4.0.0-dev" dependencies = [ - "clap", "frame-election-provider-support", "frame-support", "frame-system", @@ -5336,7 +5467,6 @@ dependencies = [ "sp-std", "sp-storage", "sp-tracing", - "structopt", "tokio", ] @@ -5492,7 +5622,7 @@ dependencies = [ [[package]] name = "pallet-contracts-primitives" -version = "4.0.0-dev" +version = "5.0.0" dependencies = [ "bitflags", "parity-scale-codec", @@ -5544,6 +5674,25 @@ dependencies = [ "sp-std", ] +[[package]] +name = "pallet-conviction-voting" +version = "4.0.0-dev" +dependencies = [ + "assert_matches", + "frame-benchmarking", + "frame-support", + "frame-system", + "pallet-balances", + "pallet-scheduler", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", +] + [[package]] name = "pallet-democracy" version = "4.0.0-dev" @@ -5585,7 +5734,6 @@ dependencies = [ "sp-tracing", "static_assertions", "strum", - "strum_macros 0.23.1", ] [[package]] @@ -5995,6 +6143,26 @@ dependencies = [ "sp-std", ] +[[package]] +name = "pallet-referenda" +version = "4.0.0-dev" +dependencies = [ + "assert_matches", + "frame-benchmarking", + "frame-support", + "frame-system", + "pallet-balances", + "pallet-preimage", + "pallet-scheduler", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", +] + [[package]] name = "pallet-scheduler" version = "4.0.0-dev" @@ -6153,7 +6321,7 @@ dependencies = [ [[package]] name = "pallet-template" -version = "3.0.0" +version = "4.0.0-dev" dependencies = [ "frame-benchmarking", "frame-support", @@ -6912,7 +7080,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "62941722fb675d463659e49c4f3fe1fe792ff24fe5bbaa9c08cd3b98a1c354f5" dependencies = [ "bytes 1.1.0", - "heck", + "heck 0.3.2", "itertools", "lazy_static", "log 0.4.14", @@ -7380,7 +7548,7 @@ version = "0.10.0-dev" dependencies = [ "env_logger 0.9.0", "frame-support", - "jsonrpsee", + "jsonrpsee 0.8.0", "log 0.4.14", "pallet-elections-phragmen", "parity-scale-codec", @@ -7512,8 +7680,20 @@ dependencies = [ "base64 0.13.0", "log 0.4.14", "ring", - "sct", - "webpki", + "sct 0.6.0", + "webpki 0.21.4", +] + +[[package]] +name = "rustls" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d37e5e2290f3e040b594b1a9e04377c2c671f1a1cfd9bfdef82106ac1c113f84" +dependencies = [ + "log 0.4.14", + "ring", + "sct 0.7.0", + "webpki 0.22.0", ] [[package]] @@ -7523,11 +7703,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a07b7c1885bd8ed3831c289b7870b13ef46fe0e856d288c30d9cc17d75a2092" dependencies = [ "openssl-probe", - "rustls", + "rustls 0.19.1", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-native-certs" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca9ebdfa27d3fc180e42879037b5338ab1c040c06affd00d8338598e7800943" +dependencies = [ + "openssl-probe", + "rustls-pemfile", "schannel", "security-framework", ] +[[package]] +name = "rustls-pemfile" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eebeaeb360c87bfb72e84abdb3447159c0eaececf1bef2aecd65a8be949d1c9" +dependencies = [ + "base64 0.13.0", +] + [[package]] name = "rustversion" version = "1.0.6" @@ -7599,7 +7800,6 @@ name = "sc-authority-discovery" version = "0.10.0-dev" dependencies = [ "async-trait", - "derive_more", "futures 0.3.16", "futures-timer", "ip_network", @@ -7621,6 +7821,7 @@ dependencies = [ "sp-tracing", "substrate-prometheus-endpoint", "substrate-test-runtime-client", + "thiserror", ] [[package]] @@ -7695,6 +7896,7 @@ name = "sc-cli" version = "0.10.0-dev" dependencies = [ "chrono", + "clap 3.0.7", "fdlimit", "futures 0.3.16", "hex", @@ -7721,7 +7923,6 @@ dependencies = [ "sp-panic-handler", "sp-runtime", "sp-version", - "structopt", "tempfile", "thiserror", "tiny-bip39", @@ -7815,7 +8016,6 @@ name = "sc-consensus-aura" version = "0.10.0-dev" dependencies = [ "async-trait", - "derive_more", "futures 0.3.16", "getrandom 0.2.3", "log 0.4.14", @@ -7846,6 +8046,7 @@ dependencies = [ "substrate-prometheus-endpoint", "substrate-test-runtime-client", "tempfile", + "thiserror", ] [[package]] @@ -7853,7 +8054,6 @@ name = "sc-consensus-babe" version = "0.10.0-dev" dependencies = [ "async-trait", - "derive_more", "fork-tree", "futures 0.3.16", "log 0.4.14", @@ -7896,13 +8096,13 @@ dependencies = [ "substrate-prometheus-endpoint", "substrate-test-runtime-client", "tempfile", + "thiserror", ] [[package]] name = "sc-consensus-babe-rpc" version = "0.10.0-dev" dependencies = [ - "derive_more", "futures 0.3.16", "jsonrpc-core", "jsonrpc-core-client", @@ -7925,6 +8125,7 @@ dependencies = [ "sp-runtime", "substrate-test-runtime-client", "tempfile", + "thiserror", ] [[package]] @@ -7945,7 +8146,6 @@ version = "0.10.0-dev" dependencies = [ "assert_matches", "async-trait", - "derive_more", "futures 0.3.16", "jsonrpc-core", "jsonrpc-core-client", @@ -7975,6 +8175,7 @@ dependencies = [ "substrate-prometheus-endpoint", "substrate-test-runtime-client", "substrate-test-runtime-transaction-pool", + "thiserror", "tokio", ] @@ -7983,7 +8184,6 @@ name = "sc-consensus-pow" version = "0.10.0-dev" dependencies = [ "async-trait", - "derive_more", "futures 0.3.16", "futures-timer", "log 0.4.14", @@ -8000,6 +8200,7 @@ dependencies = [ "sp-inherents", "sp-runtime", "substrate-prometheus-endpoint", + "thiserror", ] [[package]] @@ -8080,7 +8281,6 @@ dependencies = [ name = "sc-executor-common" version = "0.10.0-dev" dependencies = [ - "derive_more", "environmental", "parity-scale-codec", "sc-allocator", @@ -8136,7 +8336,6 @@ version = "0.10.0-dev" dependencies = [ "assert_matches", "async-trait", - "derive_more", "dyn-clone", "finality-grandpa", "fork-tree", @@ -8171,6 +8370,7 @@ dependencies = [ "substrate-prometheus-endpoint", "substrate-test-runtime-client", "tempfile", + "thiserror", "tokio", ] @@ -8178,7 +8378,6 @@ dependencies = [ name = "sc-finality-grandpa-rpc" version = "0.10.0-dev" dependencies = [ - "derive_more", "finality-grandpa", "futures 0.3.16", "jsonrpc-core", @@ -8199,6 +8398,7 @@ dependencies = [ "sp-keyring", "sp-runtime", "substrate-test-runtime-client", + "thiserror", ] [[package]] @@ -8222,7 +8422,6 @@ name = "sc-keystore" version = "4.0.0-dev" dependencies = [ "async-trait", - "derive_more", "hex", "parking_lot 0.11.2", "serde_json", @@ -8230,6 +8429,7 @@ dependencies = [ "sp-core", "sp-keystore", "tempfile", + "thiserror", ] [[package]] @@ -8243,7 +8443,6 @@ dependencies = [ "bitflags", "bytes 1.1.0", "cid", - "derive_more", "either", "fnv", "fork-tree", @@ -8714,7 +8913,6 @@ dependencies = [ name = "sc-transaction-pool-api" version = "4.0.0-dev" dependencies = [ - "derive_more", "futures 0.3.16", "log 0.4.14", "serde", @@ -8811,6 +9009,16 @@ dependencies = [ "untrusted", ] +[[package]] +name = "sct" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" +dependencies = [ + "ring", + "untrusted", +] + [[package]] name = "secrecy" version = "0.8.0" @@ -8896,9 +9104,9 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.132" +version = "1.0.136" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b9875c23cf305cd1fd7eb77234cbb705f21ea6a72c637a5c6db5fe4b8e7f008" +checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789" dependencies = [ "serde_derive", ] @@ -8924,9 +9132,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.132" +version = "1.0.136" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc0db5cb2556c0e558887d9bbdcf6ac4471e83ff66cf696e5419024d1606276" +checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9" dependencies = [ "proc-macro2", "quote", @@ -9158,9 +9366,9 @@ dependencies = [ [[package]] name = "soketto" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "083624472e8817d44d02c0e55df043737ff11f279af924abdf93845717c2b75c" +checksum = "41d1c5305e39e09653383c2c7244f2f78b3bcae37cf50c64cb4789c9f5096ec2" dependencies = [ "base64 0.13.0", "bytes 1.1.0", @@ -9223,7 +9431,7 @@ dependencies = [ [[package]] name = "sp-application-crypto" -version = "4.0.0" +version = "5.0.0" dependencies = [ "parity-scale-codec", "scale-info", @@ -9416,7 +9624,7 @@ dependencies = [ [[package]] name = "sp-core" -version = "4.1.0-dev" +version = "5.0.0" dependencies = [ "base58", "bitflags", @@ -9507,7 +9715,7 @@ dependencies = [ [[package]] name = "sp-externalities" -version = "0.10.0" +version = "0.11.0" dependencies = [ "environmental", "parity-scale-codec", @@ -9548,7 +9756,7 @@ dependencies = [ [[package]] name = "sp-io" -version = "4.0.0" +version = "5.0.0" dependencies = [ "futures 0.3.16", "hash-db", @@ -9571,7 +9779,7 @@ dependencies = [ [[package]] name = "sp-keyring" -version = "4.1.0-dev" +version = "5.0.0" dependencies = [ "lazy_static", "sp-core", @@ -9581,10 +9789,9 @@ dependencies = [ [[package]] name = "sp-keystore" -version = "0.10.0" +version = "0.11.0" dependencies = [ "async-trait", - "derive_more", "futures 0.3.16", "merlin", "parity-scale-codec", @@ -9595,12 +9802,14 @@ dependencies = [ "serde", "sp-core", "sp-externalities", + "thiserror", ] [[package]] name = "sp-maybe-compressed-blob" version = "4.1.0-dev" dependencies = [ + "thiserror", "zstd", ] @@ -9624,13 +9833,13 @@ dependencies = [ name = "sp-npos-elections-fuzzer" version = "2.0.0-alpha.5" dependencies = [ + "clap 3.0.7", "honggfuzz", "parity-scale-codec", - "rand 0.7.3", + "rand 0.8.4", "scale-info", "sp-npos-elections", "sp-runtime", - "structopt", ] [[package]] @@ -9668,7 +9877,7 @@ dependencies = [ [[package]] name = "sp-rpc" -version = "4.0.0-dev" +version = "5.0.0" dependencies = [ "rustc-hash", "serde", @@ -9678,7 +9887,7 @@ dependencies = [ [[package]] name = "sp-runtime" -version = "4.1.0-dev" +version = "5.0.0" dependencies = [ "either", "hash256-std-hasher", @@ -9705,7 +9914,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface" -version = "4.1.0-dev" +version = "5.0.0" dependencies = [ "impl-trait-for-tuples", "parity-scale-codec", @@ -9822,7 +10031,7 @@ dependencies = [ [[package]] name = "sp-state-machine" -version = "0.10.0" +version = "0.11.0" dependencies = [ "hash-db", "hex-literal", @@ -9851,7 +10060,7 @@ version = "4.0.0" [[package]] name = "sp-storage" -version = "4.0.0" +version = "5.0.0" dependencies = [ "impl-serde", "parity-scale-codec", @@ -9937,7 +10146,7 @@ dependencies = [ [[package]] name = "sp-trie" -version = "4.0.0" +version = "5.0.0" dependencies = [ "criterion", "hash-db", @@ -9983,7 +10192,7 @@ dependencies = [ [[package]] name = "sp-wasm-interface" -version = "4.1.0-dev" +version = "5.0.0" dependencies = [ "impl-trait-for-tuples", "log 0.4.14", @@ -10001,9 +10210,9 @@ checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" [[package]] name = "ss58-registry" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c83f0afe7e571565ef9aae7b0e4fb30fcaec4ebb9aea2f00489b772782aa03a4" +checksum = "1230685dc82f8699110640244d361a7099c602f08bddc5c90765a5153b4881dc" dependencies = [ "Inflector", "proc-macro2", @@ -10038,61 +10247,19 @@ dependencies = [ "rand 0.8.4", ] -[[package]] -name = "strsim" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" - [[package]] name = "strsim" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" -[[package]] -name = "structopt" -version = "0.3.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40b9788f4202aa75c240ecc9c15c65185e6a39ccdeb0fd5d008b98825464c87c" -dependencies = [ - "clap", - "lazy_static", - "structopt-derive", -] - -[[package]] -name = "structopt-derive" -version = "0.4.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcb5ae327f9cc13b68763b5749770cb9e048a99bd9dfdfa58d0cf05d5f64afe0" -dependencies = [ - "heck", - "proc-macro-error", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "strum" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7ac893c7d471c8a21f31cfe213ec4f6d9afeed25537c772e08ef3f005f8729e" -dependencies = [ - "strum_macros 0.22.0", -] - -[[package]] -name = "strum_macros" -version = "0.22.0" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "339f799d8b549e3744c7ac7feb216383e4005d94bdb22561b3ab8f3b808ae9fb" +checksum = "cae14b91c7d11c9a851d3fbc80a963198998c2a64eec840477fa92d8ce9b70bb" dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn", + "strum_macros", ] [[package]] @@ -10101,7 +10268,7 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5bb0dc7ee9c15cea6199cde9a127fa16a4c5819af85395457ad72d68edc85a38" dependencies = [ - "heck", + "heck 0.3.2", "proc-macro2", "quote", "rustversion", @@ -10112,8 +10279,8 @@ dependencies = [ name = "subkey" version = "2.0.1" dependencies = [ + "clap 3.0.7", "sc-cli", - "structopt", ] [[package]] @@ -10140,12 +10307,12 @@ dependencies = [ name = "substrate-frame-cli" version = "4.0.0-dev" dependencies = [ + "clap 3.0.7", "frame-support", "frame-system", "sc-cli", "sp-core", "sp-runtime", - "structopt", ] [[package]] @@ -10193,11 +10360,11 @@ name = "substrate-prometheus-endpoint" version = "0.10.0-dev" dependencies = [ "async-std", - "derive_more", "futures-util", "hyper 0.14.16", "log 0.4.14", "prometheus", + "thiserror", "tokio", ] @@ -10294,7 +10461,6 @@ dependencies = [ name = "substrate-test-runtime-transaction-pool" version = "2.0.0" dependencies = [ - "derive_more", "futures 0.3.16", "parity-scale-codec", "parking_lot 0.11.2", @@ -10303,6 +10469,7 @@ dependencies = [ "sp-blockchain", "sp-runtime", "substrate-test-runtime-client", + "thiserror", ] [[package]] @@ -10343,6 +10510,7 @@ dependencies = [ "build-helper", "cargo_metadata", "sp-maybe-compressed-blob", + "strum", "tempfile", "toml", "walkdir", @@ -10428,6 +10596,12 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "textwrap" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0066c8d12af8b5acd21e00547c3797fde4e8677254a7ee429176ccebbe93dd80" + [[package]] name = "thiserror" version = "1.0.30" @@ -10627,9 +10801,20 @@ version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc6844de72e57df1980054b38be3a9f4702aba4858be64dd700181a8a6d0e1b6" dependencies = [ - "rustls", + "rustls 0.19.1", "tokio", - "webpki", + "webpki 0.21.4", +] + +[[package]] +name = "tokio-rustls" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a27d5f2b839802bd8267fa19b0530f5a08b9c08cd417976be2a65d130fe1c11b" +dependencies = [ + "rustls 0.20.2", + "tokio", + "webpki 0.22.0", ] [[package]] @@ -10920,7 +11105,8 @@ checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" name = "try-runtime-cli" version = "0.10.0-dev" dependencies = [ - "jsonrpsee", + "clap 3.0.7", + "jsonrpsee 0.4.1", "log 0.4.14", "parity-scale-codec", "remote-externalities", @@ -10936,7 +11122,6 @@ dependencies = [ "sp-runtime", "sp-state-machine", "sp-version", - "structopt", "zstd", ] @@ -11146,12 +11331,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eafc1b9b2dfc6f5529177b62cf806484db55b32dc7c9658a118e11bbeb33061d" -[[package]] -name = "vec_map" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" - [[package]] name = "version_check" version = "0.1.5" @@ -11297,9 +11476,9 @@ dependencies = [ [[package]] name = "wasm-instrument" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e67369bb53d409b67e57ef31797b1b2d628955fc82f86f2ea78bb403acc7c73" +checksum = "962e5b0401bbb6c887f54e69b8c496ea36f704df65db73e81fd5ff8dc3e63a9f" dependencies = [ "parity-wasm 0.42.2", ] @@ -11741,13 +11920,32 @@ dependencies = [ "untrusted", ] +[[package]] +name = "webpki" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd" +dependencies = [ + "ring", + "untrusted", +] + [[package]] name = "webpki-roots" version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "82015b7e0b8bad8185994674a13a93306bea76cf5a16c5a181382fd3a5ec2376" dependencies = [ - "webpki", + "webpki 0.21.4", +] + +[[package]] +name = "webpki-roots" +version = "0.22.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "552ceb903e957524388c4d3475725ff2c8b7960922063af6ce53c9a43da07449" +dependencies = [ + "webpki 0.22.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index b7051bdd44ef4..a31d8011a9f44 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,6 +67,9 @@ members = [ "frame/authority-discovery", "frame/authorship", "frame/babe", + "frame/bags-list", + "frame/bags-list/fuzzer", + "frame/bags-list/remote-tests", "frame/balances", "frame/beefy", "frame/beefy-mmr", @@ -78,6 +81,7 @@ members = [ "frame/contracts", "frame/contracts/rpc", "frame/contracts/rpc/runtime-api", + "frame/conviction-voting", "frame/democracy", "frame/try-runtime", "frame/election-provider-multi-phase", @@ -104,6 +108,7 @@ members = [ "frame/proxy", "frame/randomness-collective-flip", "frame/recovery", + "frame/referenda", "frame/scheduler", "frame/scored-pool", "frame/session", @@ -133,9 +138,6 @@ members = [ "frame/uniques", "frame/utility", "frame/vesting", - "frame/bags-list", - "frame/bags-list/remote-tests", - "frame/bags-list/fuzzer", "primitives/api", "primitives/api/proc-macro", "primitives/api/test", @@ -272,6 +274,17 @@ wasmi = { opt-level = 3 } x25519-dalek = { opt-level = 3 } yamux = { opt-level = 3 } zeroize = { opt-level = 3 } + [profile.release] # Substrate runtime requires unwinding. panic = "unwind" + +[profile.production] +inherits = "release" + +# Sacrifice compile speed for execution speed by using optimization flags: + +# https://doc.rust-lang.org/rustc/linker-plugin-lto.html +lto = "fat" +# https://doc.rust-lang.org/rustc/codegen-options/index.html#codegen-units +codegen-units = 1 diff --git a/bin/node-template/README.md b/bin/node-template/README.md index bb4df52f41a8f..52b117b8a7826 100644 --- a/bin/node-template/README.md +++ b/bin/node-template/README.md @@ -26,7 +26,7 @@ First, complete the [basic Rust setup instructions](./docs/rust-setup.md). Use Rust's native `cargo` command to build and launch the template node: ```sh -cargo run --release -- --dev --tmp +cargo run --release -- --dev ``` ### Build @@ -72,20 +72,20 @@ Start the development chain with detailed logging: ```bash RUST_BACKTRACE=1 ./target/release/node-template -ldebug --dev ``` + > Development chain means that the state of our chain will be in a tmp folder while the nodes are -> running. Also, **alice** account will be authority and sudo account as declared in the [genesis -> state](https://github.com/substrate-developer-hub/substrate-node-template/blob/main/node/src/chain_spec.rs#L49). -> At the same time the following accounts will be prefunded: +> running. Also, **alice** account will be authority and sudo account as declared in the +> [genesis state](https://github.com/substrate-developer-hub/substrate-node-template/blob/main/node/src/chain_spec.rs#L49). +> At the same time the following accounts will be pre-funded: > - Alice -> - Bob +> - Bob > - Alice//stash > - Bob//stash -In case of being interested in maintaining the chain' state futher in time a base path other than -a temporary directory must be added so the db can be stored in the provided folder. We could use -this folder to store different chain databases, as a different folder will be created per different - chain that is ran. The following commands shows how to use a newly created folder as our db base - path. +In case of being interested in maintaining the chain' state between runs a base path must be added +so the db can be stored in the provided folder instead of a temporal one. We could use this folder +to store different chain databases, as a different folder will be created per different chain that +is ran. The following commands shows how to use a newly created folder as our db base path. ```bash // Create a folder to use as the db base path @@ -103,6 +103,7 @@ $ ls ./my-chain-state/chains/dev db keystore network ``` + ### Connect with Polkadot-JS Apps Front-end Once the node template is running locally, you can connect it with **Polkadot-JS Apps** front-end diff --git a/bin/node-template/docs/rust-setup.md b/bin/node-template/docs/rust-setup.md index 4b96da1146b8e..ea133ca847af7 100644 --- a/bin/node-template/docs/rust-setup.md +++ b/bin/node-template/docs/rust-setup.md @@ -2,32 +2,21 @@ title: Installation --- -This page will guide you through the steps needed to prepare a computer for development with the -Substrate Node Template. Since Substrate is built with -[the Rust programming language](https://www.rust-lang.org/), the first thing you will need to do is -prepare the computer for Rust development - these steps will vary based on the computer's operating -system. Once Rust is configured, you will use its toolchains to interact with Rust projects; the -commands for Rust's toolchains will be the same for all supported, Unix-based operating systems. +This guide is for reference only, please check the latest information on getting starting with Substrate +[here](https://docs.substrate.io/v3/getting-started/installation/). -## Unix-Based Operating Systems +This page will guide you through the **2 steps** needed to prepare a computer for **Substrate** development. +Since Substrate is built with [the Rust programming language](https://www.rust-lang.org/), the first +thing you will need to do is prepare the computer for Rust development - these steps will vary based +on the computer's operating system. Once Rust is configured, you will use its toolchains to interact +with Rust projects; the commands for Rust's toolchains will be the same for all supported, +Unix-based operating systems. -Substrate development is easiest on Unix-based operating systems like macOS or Linux. The examples -in the Substrate [Tutorials](https://docs.substrate.io/tutorials/v3) and -[How-to Guides](https://docs.substrate.io/how-to-guides/v3) use Unix-style terminals to demonstrate -how to interact with Substrate from the command line. - -### macOS +## Build dependencies -Open the Terminal application and execute the following commands: - -```bash -# Install Homebrew if necessary https://brew.sh/ -/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" - -# Make sure Homebrew is up-to-date, install openssl and cmake -brew update -brew install openssl cmake -``` +Substrate development is easiest on Unix-based operating systems like macOS or Linux. The examples +in the [Substrate Docs](https://docs.substrate.io) use Unix-style terminals to demonstrate how to +interact with Substrate from the command line. ### Ubuntu/Debian @@ -36,7 +25,7 @@ Use a terminal shell to execute the following commands: ```bash sudo apt update # May prompt for location information -sudo apt install -y cmake pkg-config libssl-dev git build-essential clang libclang-dev curl +sudo apt install -y git clang curl libssl-dev llvm libudev-dev ``` ### Arch Linux @@ -44,39 +33,193 @@ sudo apt install -y cmake pkg-config libssl-dev git build-essential clang libcla Run these commands from a terminal: ```bash -pacman -Syu --needed --noconfirm cmake gcc openssl-1.0 pkgconf git clang -export OPENSSL_LIB_DIR="/usr/lib/openssl-1.0" -export OPENSSL_INCLUDE_DIR="/usr/include/openssl-1.0" +pacman -Syu --needed --noconfirm curl git clang ``` -### Fedora/RHEL/CentOS +### Fedora -Use a terminal to run the following commands: +Run these commands from a terminal: ```bash -# Update sudo dnf update -# Install packages -sudo dnf install cmake pkgconfig rocksdb rocksdb-devel llvm git libcurl libcurl-devel curl-devel clang +sudo dnf install clang curl git openssl-devel +``` + +### OpenSUSE + +Run these commands from a terminal: + +```bash +sudo zypper install clang curl git openssl-devel llvm-devel libudev-devel +``` + +### macOS + +> **Apple M1 ARM** +> If you have an Apple M1 ARM system on a chip, make sure that you have Apple Rosetta 2 +> installed through `softwareupdate --install-rosetta`. This is only needed to run the +> `protoc` tool during the build. The build itself and the target binaries would remain native. + +Open the Terminal application and execute the following commands: + +```bash +# Install Homebrew if necessary https://brew.sh/ +/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" + +# Make sure Homebrew is up-to-date, install openssl +brew update +brew install openssl ``` -## Rust Developer Environment +### Windows + +**_PLEASE NOTE:_** Native development of Substrate is _not_ very well supported! It is _highly_ +recommend to use [Windows Subsystem Linux](https://docs.microsoft.com/en-us/windows/wsl/install-win10) +(WSL) and follow the instructions for [Ubuntu/Debian](#ubuntudebian). +Please refer to the separate +[guide for native Windows development](https://docs.substrate.io/v3/getting-started/windows-users/). -This project uses [`rustup`](https://rustup.rs/) to help manage the Rust toolchain. First install -and configure `rustup`: +## Rust developer environment + +This guide uses installer and the `rustup` tool to manage the Rust toolchain. +First install and configure `rustup`: ```bash # Install -curl https://sh.rustup.rs -sSf | sh +curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Configure source ~/.cargo/env ``` -Finally, configure the Rust toolchain: +Configure the Rust toolchain to default to the latest stable version, add nightly and the nightly wasm target: ```bash rustup default stable +rustup update +rustup update nightly +rustup target add wasm32-unknown-unknown --toolchain nightly +``` + +## Test your set-up + +Now the best way to ensure that you have successfully prepared a computer for Substrate +development is to follow the steps in [our first Substrate tutorial](https://docs.substrate.io/tutorials/v3/create-your-first-substrate-chain/). + +## Troubleshooting Substrate builds + +Sometimes you can't get the Substrate node template +to compile out of the box. Here are some tips to help you work through that. + +### Rust configuration check + +To see what Rust toolchain you are presently using, run: + +```bash +rustup show +``` + +This will show something like this (Ubuntu example) output: + +```text +Default host: x86_64-unknown-linux-gnu +rustup home: /home/user/.rustup + +installed toolchains +-------------------- + +stable-x86_64-unknown-linux-gnu (default) +nightly-2020-10-06-x86_64-unknown-linux-gnu +nightly-x86_64-unknown-linux-gnu + +installed targets for active toolchain +-------------------------------------- + +wasm32-unknown-unknown +x86_64-unknown-linux-gnu + +active toolchain +---------------- + +stable-x86_64-unknown-linux-gnu (default) +rustc 1.50.0 (cb75ad5db 2021-02-10) +``` + +As you can see above, the default toolchain is stable, and the +`nightly-x86_64-unknown-linux-gnu` toolchain as well as its `wasm32-unknown-unknown` target is installed. +You also see that `nightly-2020-10-06-x86_64-unknown-linux-gnu` is installed, but is not used unless explicitly defined as illustrated in the [specify your nightly version](#specifying-nightly-version) +section. + +### WebAssembly compilation + +Substrate uses [WebAssembly](https://webassembly.org) (Wasm) to produce portable blockchain +runtimes. You will need to configure your Rust compiler to use +[`nightly` builds](https://doc.rust-lang.org/book/appendix-07-nightly-rust.html) to allow you to +compile Substrate runtime code to the Wasm target. + +> There are upstream issues in Rust that need to be resolved before all of Substrate can use the stable Rust toolchain. +> [This is our tracking issue](https://github.com/paritytech/substrate/issues/1252) if you're curious as to why and how this will be resolved. + +#### Latest nightly for Substrate `master` + +Developers who are building Substrate _itself_ should always use the latest bug-free versions of +Rust stable and nightly. This is because the Substrate codebase follows the tip of Rust nightly, +which means that changes in Substrate often depend on upstream changes in the Rust nightly compiler. +To ensure your Rust compiler is always up to date, you should run: + +```bash +rustup update rustup update nightly -rustup update stable rustup target add wasm32-unknown-unknown --toolchain nightly ``` + +> NOTE: It may be necessary to occasionally rerun `rustup update` if a change in the upstream Substrate +> codebase depends on a new feature of the Rust compiler. When you do this, both your nightly +> and stable toolchains will be pulled to the most recent release, and for nightly, it is +> generally _not_ expected to compile WASM without error (although it very often does). +> Be sure to [specify your nightly version](#specifying-nightly-version) if you get WASM build errors +> from `rustup` and [downgrade nightly as needed](#downgrading-rust-nightly). + +#### Rust nightly toolchain + +If you want to guarantee that your build works on your computer as you update Rust and other +dependencies, you should use a specific Rust nightly version that is known to be +compatible with the version of Substrate they are using; this version will vary from project to +project and different projects may use different mechanisms to communicate this version to +developers. For instance, the Polkadot client specifies this information in its +[release notes](https://github.com/paritytech/polkadot/releases). + +```bash +# Specify the specific nightly toolchain in the date below: +rustup install nightly- +``` + +#### Wasm toolchain + +Now, configure the nightly version to work with the Wasm compilation target: + +```bash +rustup target add wasm32-unknown-unknown --toolchain nightly- +``` + +### Specifying nightly version + +Use the `WASM_BUILD_TOOLCHAIN` environment variable to specify the Rust nightly version a Substrate +project should use for Wasm compilation: + +```bash +WASM_BUILD_TOOLCHAIN=nightly- cargo build --release +``` + +> Note that this only builds _the runtime_ with the specified nightly. The rest of project will be +> compiled with **your default toolchain**, i.e. the latest installed stable toolchain. + +### Downgrading Rust nightly + +If your computer is configured to use the latest Rust nightly and you would like to downgrade to a +specific nightly version, follow these steps: + +```bash +rustup uninstall nightly +rustup install nightly- +rustup target add wasm32-unknown-unknown --toolchain nightly- +``` diff --git a/bin/node-template/node/Cargo.toml b/bin/node-template/node/Cargo.toml index 2b280e1bf00de..1f8ff0ae1e0d4 100644 --- a/bin/node-template/node/Cargo.toml +++ b/bin/node-template/node/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "node-template" -version = "3.0.0" +version = "4.0.0-dev" description = "A fresh FRAME-based Substrate node, ready for hacking." authors = ["Substrate DevHub "] homepage = "https://substrate.io/" @@ -17,10 +17,10 @@ targets = ["x86_64-unknown-linux-gnu"] name = "node-template" [dependencies] -structopt = "0.3.25" +clap = { version = "3.0", features = ["derive"] } sc-cli = { version = "0.10.0-dev", path = "../../../client/cli", features = ["wasmtime"] } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } sc-executor = { version = "0.10.0-dev", path = "../../../client/executor", features = ["wasmtime"] } sc-service = { version = "0.10.0-dev", path = "../../../client/service", features = ["wasmtime"] } sc-telemetry = { version = "4.0.0-dev", path = "../../../client/telemetry" } @@ -34,7 +34,7 @@ sc-consensus = { version = "0.10.0-dev", path = "../../../client/consensus/commo sc-finality-grandpa = { version = "0.10.0-dev", path = "../../../client/finality-grandpa" } sp-finality-grandpa = { version = "4.0.0-dev", path = "../../../primitives/finality-grandpa" } sc-client-api = { version = "4.0.0-dev", path = "../../../client/api" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } sp-timestamp = { version = "4.0.0-dev", path = "../../../primitives/timestamp" } # These dependencies are used for the node template's RPCs @@ -52,13 +52,12 @@ pallet-transaction-payment-rpc = { version = "4.0.0-dev", path = "../../../frame frame-benchmarking = { version = "4.0.0-dev", path = "../../../frame/benchmarking" } frame-benchmarking-cli = { version = "4.0.0-dev", path = "../../../utils/frame/benchmarking-cli" } -node-template-runtime = { version = "3.0.0", path = "../runtime" } +# Local Dependencies +node-template-runtime = { version = "4.0.0-dev", path = "../runtime" } [build-dependencies] substrate-build-script-utils = { version = "3.0.0", path = "../../../utils/build-script-utils" } [features] default = [] -runtime-benchmarks = [ - "node-template-runtime/runtime-benchmarks", -] +runtime-benchmarks = ["node-template-runtime/runtime-benchmarks"] diff --git a/bin/node-template/node/src/cli.rs b/bin/node-template/node/src/cli.rs index 8ed1d35ba5f92..d787f57f071a6 100644 --- a/bin/node-template/node/src/cli.rs +++ b/bin/node-template/node/src/cli.rs @@ -1,19 +1,20 @@ use sc_cli::RunCmd; -use structopt::StructOpt; -#[derive(Debug, StructOpt)] +#[derive(Debug, clap::Parser)] pub struct Cli { - #[structopt(subcommand)] + #[clap(subcommand)] pub subcommand: Option, - #[structopt(flatten)] + #[clap(flatten)] pub run: RunCmd, } -#[derive(Debug, StructOpt)] +#[derive(Debug, clap::Subcommand)] pub enum Subcommand { /// Key management cli utilities + #[clap(subcommand)] Key(sc_cli::KeySubcommand), + /// Build a chain specification. BuildSpec(sc_cli::BuildSpecCmd), @@ -36,6 +37,6 @@ pub enum Subcommand { Revert(sc_cli::RevertCmd), /// The custom benchmark subcommand benchmarking runtime pallets. - #[structopt(name = "benchmark", about = "Benchmark runtime pallets.")] + #[clap(name = "benchmark", about = "Benchmark runtime pallets.")] Benchmark(frame_benchmarking_cli::BenchmarkCmd), } diff --git a/bin/node-template/pallets/template/Cargo.toml b/bin/node-template/pallets/template/Cargo.toml index 9702501a3e0ea..0a9d0eb27a2ca 100644 --- a/bin/node-template/pallets/template/Cargo.toml +++ b/bin/node-template/pallets/template/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-template" -version = "3.0.0" +version = "4.0.0-dev" description = "FRAME pallet template for defining custom runtime logic." authors = ["Substrate DevHub "] homepage = "https://substrate.io/" @@ -22,9 +22,9 @@ frame-system = { default-features = false, version = "4.0.0-dev", path = "../../ frame-benchmarking = { default-features = false, version = "4.0.0-dev", path = "../../../../frame/benchmarking", optional = true } [dev-dependencies] -sp-core = { default-features = false, version = "4.1.0-dev", path = "../../../../primitives/core" } -sp-io = { default-features = false, version = "4.0.0-dev", path = "../../../../primitives/io" } -sp-runtime = { default-features = false, version = "4.1.0-dev", path = "../../../../primitives/runtime" } +sp-core = { default-features = false, version = "5.0.0", path = "../../../../primitives/core" } +sp-io = { default-features = false, version = "5.0.0", path = "../../../../primitives/io" } +sp-runtime = { default-features = false, version = "5.0.0", path = "../../../../primitives/runtime" } [features] default = ["std"] diff --git a/bin/node-template/runtime/Cargo.toml b/bin/node-template/runtime/Cargo.toml index b757029f2581d..98da28c4476d9 100644 --- a/bin/node-template/runtime/Cargo.toml +++ b/bin/node-template/runtime/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "node-template-runtime" -version = "3.0.0" -description = "A fresh FRAME-based Substrate runtime, ready for hacking." +version = "4.0.0-dev" +description = "A fresh FRAME-based Substrate node, ready for hacking." authors = ["Substrate DevHub "] homepage = "https://substrate.io/" edition = "2021" @@ -27,12 +27,12 @@ pallet-timestamp = { version = "4.0.0-dev", default-features = false, path = ".. pallet-transaction-payment = { version = "4.0.0-dev", default-features = false, path = "../../../frame/transaction-payment" } frame-executive = { version = "4.0.0-dev", default-features = false, path = "../../../frame/executive" } sp-api = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/api" } -sp-block-builder = { path = "../../../primitives/block-builder", default-features = false, version = "4.0.0-dev"} +sp-block-builder = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/block-builder"} sp-consensus-aura = { version = "0.10.0-dev", default-features = false, path = "../../../primitives/consensus/aura" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/core" } -sp-inherents = { path = "../../../primitives/inherents", default-features = false, version = "4.0.0-dev"} +sp-core = { version = "5.0.0", default-features = false, path = "../../../primitives/core" } +sp-inherents = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/inherents"} sp-offchain = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/offchain" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } sp-session = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/session" } sp-std = { version = "4.0.0", default-features = false, path = "../../../primitives/std" } sp-transaction-pool = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/transaction-pool" } @@ -47,7 +47,8 @@ frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = " frame-system-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../../../frame/system/benchmarking", optional = true } hex-literal = { version = "0.3.4", optional = true } -pallet-template = { version = "3.0.0", default-features = false, path = "../pallets/template" } +# Local Dependencies +pallet-template = { version = "4.0.0-dev", default-features = false, path = "../pallets/template" } [build-dependencies] substrate-wasm-builder = { version = "5.0.0-dev", path = "../../../utils/wasm-builder" } diff --git a/bin/node-template/runtime/src/lib.rs b/bin/node-template/runtime/src/lib.rs index 2aa6bf1f1ae71..0b39d76fe495e 100644 --- a/bin/node-template/runtime/src/lib.rs +++ b/bin/node-template/runtime/src/lib.rs @@ -299,6 +299,7 @@ pub type Header = generic::Header; pub type Block = generic::Block; /// The SignedExtension to the basic transaction logic. pub type SignedExtra = ( + frame_system::CheckNonZeroSender, frame_system::CheckSpecVersion, frame_system::CheckTxVersion, frame_system::CheckGenesis, diff --git a/bin/node/bench/Cargo.toml b/bin/node/bench/Cargo.toml index 670f6c4d3ed84..18951179235c1 100644 --- a/bin/node/bench/Cargo.toml +++ b/bin/node/bench/Cargo.toml @@ -9,21 +9,21 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +clap = { version = "3.0", features = ["derive"] } log = "0.4.8" node-primitives = { version = "2.0.0", path = "../primitives" } node-testing = { version = "3.0.0-dev", path = "../testing" } node-runtime = { version = "3.0.0-dev", path = "../runtime" } sc-client-api = { version = "4.0.0-dev", path = "../../../client/api/" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } -sp-state-machine = { version = "0.10.0", path = "../../../primitives/state-machine" } -serde = "1.0.132" +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } +sp-state-machine = { version = "0.11.0", path = "../../../primitives/state-machine" } +serde = "1.0.136" serde_json = "1.0.74" -structopt = "0.3" derive_more = "0.99.16" kvdb = "0.10.0" kvdb-rocksdb = "0.14.0" -sp-trie = { version = "4.0.0", path = "../../../primitives/trie" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } +sp-trie = { version = "5.0.0", path = "../../../primitives/trie" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } sp-consensus = { version = "0.10.0-dev", path = "../../../primitives/consensus/common" } sc-basic-authorship = { version = "0.10.0-dev", path = "../../../client/basic-authorship" } sp-inherents = { version = "4.0.0-dev", path = "../../../primitives/inherents" } @@ -35,9 +35,7 @@ fs_extra = "1" hex = "0.4.0" rand = { version = "0.7.2", features = ["small_rng"] } lazy_static = "1.4.0" -parity-util-mem = { version = "0.10.2", default-features = false, features = [ - "primitive-types", -] } +parity-util-mem = { version = "0.10.2", default-features = false, features = ["primitive-types"] } parity-db = { version = "0.3" } sc-transaction-pool = { version = "4.0.0-dev", path = "../../../client/transaction-pool" } sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../../client/transaction-pool/api" } diff --git a/bin/node/bench/src/main.rs b/bin/node/bench/src/main.rs index f1800214e3e81..0e50447d464fb 100644 --- a/bin/node/bench/src/main.rs +++ b/bin/node/bench/src/main.rs @@ -28,7 +28,7 @@ mod tempdb; mod trie; mod txpool; -use structopt::StructOpt; +use clap::Parser; use node_testing::bench::{BlockType, DatabaseType as BenchDataBaseType, KeyTypes, Profile}; @@ -42,19 +42,19 @@ use crate::{ txpool::PoolBenchmarkDescription, }; -#[derive(Debug, StructOpt)] -#[structopt(name = "node-bench", about = "Node integration benchmarks")] +#[derive(Debug, Parser)] +#[clap(name = "node-bench", about = "Node integration benchmarks")] struct Opt { /// Show list of all available benchmarks. /// /// Will output ("name", "path"). Benchmarks can then be filtered by path. - #[structopt(short, long)] + #[clap(short, long)] list: bool, /// Machine readable json output. /// /// This also suppresses all regular output (except to stderr) - #[structopt(short, long)] + #[clap(short, long)] json: bool, /// Filter benchmarks. @@ -63,7 +63,7 @@ struct Opt { filter: Option, /// Number of transactions for block import with `custom` size. - #[structopt(long)] + #[clap(long)] transactions: Option, /// Mode @@ -72,12 +72,12 @@ struct Opt { /// /// "profile" mode adds pauses between measurable runs, /// so that actual interval can be selected in the profiler of choice. - #[structopt(short, long, default_value = "regular")] + #[clap(short, long, default_value = "regular")] mode: BenchmarkMode, } fn main() { - let opt = Opt::from_args(); + let opt = Opt::parse(); if !opt.json { sp_tracing::try_init_simple(); diff --git a/bin/node/cli/Cargo.toml b/bin/node/cli/Cargo.toml index 8d9bf7d7af5b6..78c279add2778 100644 --- a/bin/node/cli/Cargo.toml +++ b/bin/node/cli/Cargo.toml @@ -34,26 +34,26 @@ crate-type = ["cdylib", "rlib"] [dependencies] # third-party dependencies +clap = { version = "3.0", features = ["derive"], optional = true } codec = { package = "parity-scale-codec", version = "2.0.0" } -serde = { version = "1.0.132", features = ["derive"] } +serde = { version = "1.0.136", features = ["derive"] } futures = "0.3.16" hex-literal = "0.3.4" log = "0.4.8" -rand = "0.7.2" -structopt = { version = "0.3.25", optional = true } +rand = "0.8" # primitives sp-authority-discovery = { version = "4.0.0-dev", path = "../../../primitives/authority-discovery" } sp-consensus-babe = { version = "0.10.0-dev", path = "../../../primitives/consensus/babe" } grandpa-primitives = { version = "4.0.0-dev", package = "sp-finality-grandpa", path = "../../../primitives/finality-grandpa" } sp-api = { version = "4.0.0-dev", path = "../../../primitives/api" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } sp-timestamp = { version = "4.0.0-dev", path = "../../../primitives/timestamp" } sp-authorship = { version = "4.0.0-dev", path = "../../../primitives/authorship" } sp-inherents = { version = "4.0.0-dev", path = "../../../primitives/inherents" } -sp-keyring = { version = "4.1.0-dev", path = "../../../primitives/keyring" } -sp-keystore = { version = "0.10.0", path = "../../../primitives/keystore" } +sp-keyring = { version = "5.0.0", path = "../../../primitives/keyring" } +sp-keystore = { version = "0.11.0", path = "../../../primitives/keystore" } sp-consensus = { version = "0.10.0-dev", path = "../../../primitives/consensus/common" } sp-transaction-pool = { version = "4.0.0-dev", path = "../../../primitives/transaction-pool" } sp-transaction-storage-proof = { version = "4.0.0-dev", path = "../../../primitives/transaction-storage-proof" } @@ -97,16 +97,12 @@ node-inspect = { version = "0.9.0-dev", optional = true, path = "../inspect" } try-runtime-cli = { version = "0.10.0-dev", optional = true, path = "../../../utils/frame/try-runtime/cli" } [target.'cfg(any(target_arch="x86_64", target_arch="aarch64"))'.dependencies] -node-executor = { version = "3.0.0-dev", path = "../executor", features = [ - "wasmtime", -] } -sc-cli = { version = "0.10.0-dev", optional = true, path = "../../../client/cli", features = [ - "wasmtime", -] } +node-executor = { version = "3.0.0-dev", path = "../executor", features = ["wasmtime"] } +sc-cli = { version = "0.10.0-dev", optional = true, path = "../../../client/cli", features = ["wasmtime"] } sc-service = { version = "0.10.0-dev", default-features = false, path = "../../../client/service", features = [ "wasmtime", ] } -sp-trie = { version = "4.0.0", default-features = false, path = "../../../primitives/trie", features = [ +sp-trie = { version = "5.0.0", default-features = false, path = "../../../primitives/trie", features = [ "memory-tracker", ] } @@ -129,7 +125,7 @@ regex = "1" platforms = "2.0" async-std = { version = "1.10.0", features = ["attributes"] } soketto = "0.4.2" -criterion = { version = "0.3.5", features = [ "async_tokio" ] } +criterion = { version = "0.3.5", features = ["async_tokio"] } tokio = { version = "1.15", features = ["macros", "time"] } jsonrpsee-ws-client = "0.4.1" wait-timeout = "0.2" @@ -137,7 +133,8 @@ remote-externalities = { path = "../../../utils/frame/remote-externalities" } pallet-timestamp = { version = "4.0.0-dev", path = "../../../frame/timestamp" } [build-dependencies] -structopt = { version = "0.3.25", optional = true } +clap = { version = "3.0", optional = true } +clap_complete = { version = "3.0", optional = true } node-inspect = { version = "0.9.0-dev", optional = true, path = "../inspect" } frame-benchmarking-cli = { version = "4.0.0-dev", optional = true, path = "../../../utils/frame/benchmarking-cli" } substrate-build-script-utils = { version = "3.0.0", optional = true, path = "../../../utils/build-script-utils" } @@ -155,14 +152,12 @@ cli = [ "frame-benchmarking-cli", "substrate-frame-cli", "sc-service/db", - "structopt", + "clap", + "clap_complete", "substrate-build-script-utils", "try-runtime-cli", ] -runtime-benchmarks = [ - "node-runtime/runtime-benchmarks", - "frame-benchmarking-cli", -] +runtime-benchmarks = ["node-runtime/runtime-benchmarks", "frame-benchmarking-cli"] # Enable features that allow the runtime to be tried and debugged. Name might be subject to change # in the near future. try-runtime = ["node-runtime/try-runtime", "try-runtime-cli"] diff --git a/bin/node/cli/build.rs b/bin/node/cli/build.rs index e0d5dcea62eda..6a010d8858fe5 100644 --- a/bin/node/cli/build.rs +++ b/bin/node/cli/build.rs @@ -25,7 +25,8 @@ fn main() { mod cli { include!("src/cli.rs"); - use sc_cli::structopt::clap::Shell; + use clap::{ArgEnum, IntoApp}; + use clap_complete::{generate_to, Shell}; use std::{env, fs, path::Path}; use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; @@ -37,9 +38,8 @@ mod cli { } /// Build shell completion scripts for all known shells - /// Full list in https://github.com/kbknapp/clap-rs/blob/e9d0562a1dc5dfe731ed7c767e6cee0af08f0cf9/src/app/parser.rs#L123 fn build_shell_completion() { - for shell in &[Shell::Bash, Shell::Fish, Shell::Zsh, Shell::Elvish, Shell::PowerShell] { + for shell in Shell::value_variants() { build_completion(shell); } } @@ -61,6 +61,6 @@ mod cli { fs::create_dir(&path).ok(); - Cli::clap().gen_completions("substrate-node", *shell, &path); + let _ = generate_to(*shell, &mut Cli::into_app(), "substrate-node", &path); } } diff --git a/bin/node/cli/src/chain_spec.rs b/bin/node/cli/src/chain_spec.rs index 448cbb260d84f..11516f964903a 100644 --- a/bin/node/cli/src/chain_spec.rs +++ b/bin/node/cli/src/chain_spec.rs @@ -23,8 +23,8 @@ use hex_literal::hex; use node_runtime::{ constants::currency::*, wasm_binary_unwrap, AuthorityDiscoveryConfig, BabeConfig, BalancesConfig, Block, CouncilConfig, DemocracyConfig, ElectionsConfig, GrandpaConfig, - ImOnlineConfig, IndicesConfig, SessionConfig, SessionKeys, SocietyConfig, StakerStatus, - StakingConfig, SudoConfig, SystemConfig, TechnicalCommitteeConfig, MAX_NOMINATIONS, + ImOnlineConfig, IndicesConfig, MaxNominations, SessionConfig, SessionKeys, SocietyConfig, + StakerStatus, StakingConfig, SudoConfig, SystemConfig, TechnicalCommitteeConfig, }; use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use sc_chain_spec::ChainSpecExtension; @@ -278,7 +278,7 @@ pub fn testnet_genesis( .map(|x| (x.0.clone(), x.1.clone(), STASH, StakerStatus::Validator)) .chain(initial_nominators.iter().map(|x| { use rand::{seq::SliceRandom, Rng}; - let limit = (MAX_NOMINATIONS as usize).min(initial_authorities.len()); + let limit = (MaxNominations::get() as usize).min(initial_authorities.len()); let count = rng.gen::() % limit; let nominations = initial_authorities .as_slice() diff --git a/bin/node/cli/src/cli.rs b/bin/node/cli/src/cli.rs index 59d219a01090e..00393c52f8b68 100644 --- a/bin/node/cli/src/cli.rs +++ b/bin/node/cli/src/cli.rs @@ -16,35 +16,30 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use sc_cli::{KeySubcommand, RunCmd, SignCmd, VanityCmd, VerifyCmd}; -use structopt::StructOpt; - /// An overarching CLI command definition. -#[derive(Debug, StructOpt)] +#[derive(Debug, clap::Parser)] pub struct Cli { /// Possible subcommand with parameters. - #[structopt(subcommand)] + #[clap(subcommand)] pub subcommand: Option, + #[allow(missing_docs)] - #[structopt(flatten)] - pub run: RunCmd, + #[clap(flatten)] + pub run: sc_cli::RunCmd, } /// Possible subcommands of the main binary. -#[derive(Debug, StructOpt)] +#[derive(Debug, clap::Subcommand)] pub enum Subcommand { - /// Key management cli utilities - Key(KeySubcommand), - /// The custom inspect subcommmand for decoding blocks and extrinsics. - #[structopt( + #[clap( name = "inspect", about = "Decode given block or extrinsic using current native runtime." )] Inspect(node_inspect::cli::InspectCmd), /// The custom benchmark subcommmand benchmarking runtime pallets. - #[structopt(name = "benchmark", about = "Benchmark runtime pallets.")] + #[clap(name = "benchmark", about = "Benchmark runtime pallets.")] Benchmark(frame_benchmarking_cli::BenchmarkCmd), /// Try some command against runtime state. @@ -55,14 +50,18 @@ pub enum Subcommand { #[cfg(not(feature = "try-runtime"))] TryRuntime, + /// Key management cli utilities + #[clap(subcommand)] + Key(sc_cli::KeySubcommand), + /// Verify a signature for a message, provided on STDIN, with a given (public or secret) key. - Verify(VerifyCmd), + Verify(sc_cli::VerifyCmd), /// Generate a seed that provides a vanity address. - Vanity(VanityCmd), + Vanity(sc_cli::VanityCmd), /// Sign a message, with a given (secret) key. - Sign(SignCmd), + Sign(sc_cli::SignCmd), /// Build a chain specification. BuildSpec(sc_cli::BuildSpecCmd), diff --git a/bin/node/executor/Cargo.toml b/bin/node/executor/Cargo.toml index e23152e00e5e8..531fffe35529f 100644 --- a/bin/node/executor/Cargo.toml +++ b/bin/node/executor/Cargo.toml @@ -17,11 +17,11 @@ scale-info = { version = "1.0", features = ["derive"] } node-primitives = { version = "2.0.0", path = "../primitives" } node-runtime = { version = "3.0.0-dev", path = "../runtime" } sc-executor = { version = "0.10.0-dev", path = "../../../client/executor" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } -sp-keystore = { version = "0.10.0", path = "../../../primitives/keystore" } -sp-state-machine = { version = "0.10.0", path = "../../../primitives/state-machine" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } +sp-keystore = { version = "0.11.0", path = "../../../primitives/keystore" } +sp-state-machine = { version = "0.11.0", path = "../../../primitives/state-machine" } sp-tracing = { version = "4.0.0", path = "../../../primitives/tracing" } -sp-trie = { version = "4.0.0", path = "../../../primitives/trie" } +sp-trie = { version = "5.0.0", path = "../../../primitives/trie" } frame-benchmarking = { version = "4.0.0-dev", path = "../../../frame/benchmarking" } [dev-dependencies] @@ -34,11 +34,11 @@ pallet-contracts = { version = "4.0.0-dev", path = "../../../frame/contracts" } pallet-im-online = { version = "4.0.0-dev", path = "../../../frame/im-online" } pallet-timestamp = { version = "4.0.0-dev", path = "../../../frame/timestamp" } pallet-treasury = { version = "4.0.0-dev", path = "../../../frame/treasury" } -sp-application-crypto = { version = "4.0.0", path = "../../../primitives/application-crypto" } +sp-application-crypto = { version = "5.0.0", path = "../../../primitives/application-crypto" } sp-consensus-babe = { version = "0.10.0-dev", path = "../../../primitives/consensus/babe" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } -sp-externalities = { version = "0.10.0", path = "../../../primitives/externalities" } -sp-keyring = { version = "4.1.0-dev", path = "../../../primitives/keyring" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } +sp-externalities = { version = "0.11.0", path = "../../../primitives/externalities" } +sp-keyring = { version = "5.0.0", path = "../../../primitives/keyring" } wat = "1.0" futures = "0.3.9" diff --git a/bin/node/inspect/Cargo.toml b/bin/node/inspect/Cargo.toml index d72c6f43d005d..e5b4c41c91b71 100644 --- a/bin/node/inspect/Cargo.toml +++ b/bin/node/inspect/Cargo.toml @@ -11,13 +11,13 @@ repository = "https://github.com/paritytech/substrate/" targets = ["x86_64-unknown-linux-gnu"] [dependencies] +clap = { version = "3.0", features = ["derive"] } codec = { package = "parity-scale-codec", version = "2.0.0" } -derive_more = "0.99" +thiserror = "1.0" sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" } sc-client-api = { version = "4.0.0-dev", path = "../../../client/api" } sc-executor = { version = "0.10.0-dev", path = "../../../client/executor" } sc-service = { version = "0.10.0-dev", default-features = false, path = "../../../client/service" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } -structopt = "0.3.8" +sp-core = { version = "5.0.0", path = "../../../primitives/core" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } diff --git a/bin/node/inspect/src/cli.rs b/bin/node/inspect/src/cli.rs index 6e019ca5b2084..cc1f232e1fe0f 100644 --- a/bin/node/inspect/src/cli.rs +++ b/bin/node/inspect/src/cli.rs @@ -19,27 +19,25 @@ //! Structs to easily compose inspect sub-command for CLI. use sc_cli::{ImportParams, SharedParams}; -use std::fmt::Debug; -use structopt::StructOpt; /// The `inspect` command used to print decoded chain data. -#[derive(Debug, StructOpt)] +#[derive(Debug, clap::Parser)] pub struct InspectCmd { #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(subcommand)] pub command: InspectSubCmd, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub shared_params: SharedParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub import_params: ImportParams, } /// A possible inspect sub-commands. -#[derive(Debug, StructOpt)] +#[derive(Debug, clap::Subcommand)] pub enum InspectSubCmd { /// Decode block with native version of runtime and print out the details. Block { @@ -48,7 +46,7 @@ pub enum InspectSubCmd { /// Can be either a block hash (no 0x prefix) or a number to retrieve existing block, /// or a 0x-prefixed bytes hex string, representing SCALE encoding of /// a block. - #[structopt(value_name = "HASH or NUMBER or BYTES")] + #[clap(value_name = "HASH or NUMBER or BYTES")] input: String, }, /// Decode extrinsic with native version of runtime and print out the details. @@ -58,7 +56,7 @@ pub enum InspectSubCmd { /// Can be either a block hash (no 0x prefix) or number and the index, in the form /// of `{block}:{index}` or a 0x-prefixed bytes hex string, /// representing SCALE encoding of an extrinsic. - #[structopt(value_name = "BLOCK:INDEX or BYTES")] + #[clap(value_name = "BLOCK:INDEX or BYTES")] input: String, }, } diff --git a/bin/node/inspect/src/lib.rs b/bin/node/inspect/src/lib.rs index ff1eecd219a97..b37c5aa7ca2e8 100644 --- a/bin/node/inspect/src/lib.rs +++ b/bin/node/inspect/src/lib.rs @@ -78,26 +78,19 @@ impl PrettyPrinter for DebugPrinter { } /// Aggregated error for `Inspector` operations. -#[derive(Debug, derive_more::From, derive_more::Display)] +#[derive(Debug, thiserror::Error)] pub enum Error { /// Could not decode Block or Extrinsic. - Codec(codec::Error), + #[error(transparent)] + Codec(#[from] codec::Error), /// Error accessing blockchain DB. - Blockchain(sp_blockchain::Error), + #[error(transparent)] + Blockchain(#[from] sp_blockchain::Error), /// Given block has not been found. + #[error("{0}")] NotFound(String), } -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match *self { - Self::Codec(ref e) => Some(e), - Self::Blockchain(ref e) => Some(e), - Self::NotFound(_) => None, - } - } -} - /// A helper trait to access block headers and bodies. pub trait ChainAccess: HeaderBackend + BlockBackend {} diff --git a/bin/node/primitives/Cargo.toml b/bin/node/primitives/Cargo.toml index e00f46720c947..5664318513a09 100644 --- a/bin/node/primitives/Cargo.toml +++ b/bin/node/primitives/Cargo.toml @@ -16,9 +16,9 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = ] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } frame-system = { version = "4.0.0-dev", default-features = false, path = "../../../frame/system" } -sp-application-crypto = { version = "4.0.0", default-features = false, path = "../../../primitives/application-crypto" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } +sp-application-crypto = { version = "5.0.0", default-features = false, path = "../../../primitives/application-crypto" } +sp-core = { version = "5.0.0", default-features = false, path = "../../../primitives/core" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } [features] default = ["std"] diff --git a/bin/node/rpc/Cargo.toml b/bin/node/rpc/Cargo.toml index 36d313ebc30ae..c6ba0c9f992d8 100644 --- a/bin/node/rpc/Cargo.toml +++ b/bin/node/rpc/Cargo.toml @@ -29,9 +29,9 @@ sc-sync-state-rpc = { version = "0.10.0-dev", path = "../../../client/sync-state sp-api = { version = "4.0.0-dev", path = "../../../primitives/api" } sp-block-builder = { version = "4.0.0-dev", path = "../../../primitives/block-builder" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } -sp-keystore = { version = "0.10.0", path = "../../../primitives/keystore" } +sp-keystore = { version = "0.11.0", path = "../../../primitives/keystore" } sp-consensus = { version = "0.10.0-dev", path = "../../../primitives/consensus/common" } sp-consensus-babe = { version = "0.10.0-dev", path = "../../../primitives/consensus/babe" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../../client/transaction-pool/api" } substrate-frame-rpc-system = { version = "4.0.0-dev", path = "../../../utils/frame/rpc/system" } diff --git a/bin/node/runtime/Cargo.toml b/bin/node/runtime/Cargo.toml index ef1b73aed854b..1a21b3230a3cf 100644 --- a/bin/node/runtime/Cargo.toml +++ b/bin/node/runtime/Cargo.toml @@ -30,17 +30,17 @@ sp-block-builder = { path = "../../../primitives/block-builder", default-feature sp-inherents = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/inherents" } node-primitives = { version = "2.0.0", default-features = false, path = "../primitives" } sp-offchain = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/offchain" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/core" } +sp-core = { version = "5.0.0", default-features = false, path = "../../../primitives/core" } sp-std = { version = "4.0.0", default-features = false, path = "../../../primitives/std" } sp-api = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/api" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } sp-staking = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/staking" } -sp-keyring = { version = "4.1.0-dev", optional = true, path = "../../../primitives/keyring" } +sp-keyring = { version = "5.0.0", optional = true, path = "../../../primitives/keyring" } sp-session = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/session" } sp-transaction-pool = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/transaction-pool" } sp-version = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/version" } sp-npos-elections = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/npos-elections" } -sp-io = { version = "4.0.0", default-features = false, path = "../../../primitives/io" } +sp-io = { version = "5.0.0", default-features = false, path = "../../../primitives/io" } sp-sandbox = { version = "0.10.0-dev", default-features = false, path = "../../../primitives/sandbox" } # frame dependencies @@ -62,7 +62,7 @@ pallet-bounties = { version = "4.0.0-dev", default-features = false, path = "../ pallet-child-bounties = { version = "4.0.0-dev", default-features = false, path = "../../../frame/child-bounties" } pallet-collective = { version = "4.0.0-dev", default-features = false, path = "../../../frame/collective" } pallet-contracts = { version = "4.0.0-dev", default-features = false, path = "../../../frame/contracts" } -pallet-contracts-primitives = { version = "4.0.0-dev", default-features = false, path = "../../../frame/contracts/common/" } +pallet-contracts-primitives = { version = "5.0.0", default-features = false, path = "../../../frame/contracts/common/" } pallet-contracts-rpc-runtime-api = { version = "4.0.0-dev", default-features = false, path = "../../../frame/contracts/rpc/runtime-api/" } pallet-democracy = { version = "4.0.0-dev", default-features = false, path = "../../../frame/democracy" } pallet-election-provider-multi-phase = { version = "4.0.0-dev", default-features = false, path = "../../../frame/election-provider-multi-phase" } @@ -82,9 +82,7 @@ pallet-preimage = { version = "4.0.0-dev", default-features = false, path = "../ pallet-proxy = { version = "4.0.0-dev", default-features = false, path = "../../../frame/proxy" } pallet-randomness-collective-flip = { version = "4.0.0-dev", default-features = false, path = "../../../frame/randomness-collective-flip" } pallet-recovery = { version = "4.0.0-dev", default-features = false, path = "../../../frame/recovery" } -pallet-session = { version = "4.0.0-dev", features = [ - "historical", -], path = "../../../frame/session", default-features = false } +pallet-session = { version = "4.0.0-dev", features = [ "historical" ], path = "../../../frame/session", default-features = false } pallet-session-benchmarking = { version = "4.0.0-dev", path = "../../../frame/session/benchmarking", default-features = false, optional = true } pallet-staking = { version = "4.0.0-dev", default-features = false, path = "../../../frame/staking" } pallet-staking-reward-curve = { version = "4.0.0-dev", default-features = false, path = "../../../frame/staking/reward-curve" } @@ -183,7 +181,6 @@ runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", - "pallet-election-provider-multi-phase/runtime-benchmarks", "sp-runtime/runtime-benchmarks", "pallet-assets/runtime-benchmarks", "pallet-babe/runtime-benchmarks", @@ -194,6 +191,7 @@ runtime-benchmarks = [ "pallet-collective/runtime-benchmarks", "pallet-contracts/runtime-benchmarks", "pallet-democracy/runtime-benchmarks", + "pallet-election-provider-multi-phase/runtime-benchmarks", "pallet-elections-phragmen/runtime-benchmarks", "pallet-gilt/runtime-benchmarks", "pallet-grandpa/runtime-benchmarks", @@ -204,9 +202,11 @@ runtime-benchmarks = [ "pallet-membership/runtime-benchmarks", "pallet-mmr/runtime-benchmarks", "pallet-multisig/runtime-benchmarks", + "pallet-offences-benchmarking", "pallet-preimage/runtime-benchmarks", "pallet-proxy/runtime-benchmarks", "pallet-scheduler/runtime-benchmarks", + "pallet-session-benchmarking", "pallet-society/runtime-benchmarks", "pallet-staking/runtime-benchmarks", "pallet-timestamp/runtime-benchmarks", @@ -216,8 +216,6 @@ runtime-benchmarks = [ "pallet-utility/runtime-benchmarks", "pallet-uniques/runtime-benchmarks", "pallet-vesting/runtime-benchmarks", - "pallet-offences-benchmarking", - "pallet-session-benchmarking", "frame-system-benchmarking", "hex-literal", ] @@ -235,34 +233,34 @@ try-runtime = [ "pallet-collective/try-runtime", "pallet-contracts/try-runtime", "pallet-democracy/try-runtime", + "pallet-election-provider-multi-phase/try-runtime", "pallet-elections-phragmen/try-runtime", + "pallet-gilt/try-runtime", "pallet-grandpa/try-runtime", + "pallet-identity/try-runtime", "pallet-im-online/try-runtime", "pallet-indices/try-runtime", "pallet-lottery/try-runtime", "pallet-membership/try-runtime", "pallet-mmr/try-runtime", "pallet-multisig/try-runtime", - "pallet-identity/try-runtime", - "pallet-scheduler/try-runtime", "pallet-offences/try-runtime", "pallet-preimage/try-runtime", "pallet-proxy/try-runtime", "pallet-randomness-collective-flip/try-runtime", + "pallet-recovery/try-runtime", + "pallet-scheduler/try-runtime", "pallet-session/try-runtime", + "pallet-society/try-runtime", "pallet-staking/try-runtime", "pallet-sudo/try-runtime", - "pallet-election-provider-multi-phase/try-runtime", "pallet-timestamp/try-runtime", "pallet-tips/try-runtime", "pallet-transaction-payment/try-runtime", "pallet-treasury/try-runtime", - "pallet-utility/try-runtime", - "pallet-society/try-runtime", - "pallet-recovery/try-runtime", "pallet-uniques/try-runtime", + "pallet-utility/try-runtime", "pallet-vesting/try-runtime", - "pallet-gilt/try-runtime", ] # Make contract callable functions marked as __unstable__ available. Do not enable # on live chains as those are subject to change. diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index adfc253eaa6f9..e962a9883cb9f 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -23,6 +23,7 @@ #![recursion_limit = "256"] use codec::{Decode, Encode, MaxEncodedLen}; +use frame_election_provider_support::onchain; use frame_support::{ construct_runtime, parameter_types, traits::{ @@ -122,7 +123,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // and set impl_version to 0. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. - spec_version: 299, + spec_version: 300, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, @@ -528,12 +529,6 @@ parameter_types! { pub OffchainRepeat: BlockNumber = 5; } -use frame_election_provider_support::onchain; -impl onchain::Config for Runtime { - type Accuracy = Perbill; - type DataProvider = Staking; -} - pub struct StakingBenchmarkingConfig; impl pallet_staking::BenchmarkingConfig for StakingBenchmarkingConfig { type MaxNominators = ConstU32<1000>; @@ -541,7 +536,7 @@ impl pallet_staking::BenchmarkingConfig for StakingBenchmarkingConfig { } impl pallet_staking::Config for Runtime { - const MAX_NOMINATIONS: u32 = MAX_NOMINATIONS; + type MaxNominations = MaxNominations; type Currency = Balances; type UnixTime = Timestamp; type CurrencyToVote = U128CurrencyToVote; @@ -605,7 +600,9 @@ sp_npos_elections::generate_solution_type!( >(16) ); -pub const MAX_NOMINATIONS: u32 = ::LIMIT as u32; +parameter_types! { + pub MaxNominations: u32 = ::LIMIT as u32; +} /// The numbers configured here could always be more than the the maximum limits of staking pallet /// to ensure election snapshot will not run out of memory. For now, we set them to smaller values @@ -647,6 +644,11 @@ impl frame_support::pallet_prelude::Get::DataProvider; +} + impl pallet_election_provider_multi_phase::Config for Runtime { type Event = Event; type Currency = Balances; @@ -669,6 +671,8 @@ impl pallet_election_provider_multi_phase::Config for Runtime { type DataProvider = Staking; type Solution = NposSolution16; type Fallback = pallet_election_provider_multi_phase::NoFallback; + type GovernanceFallback = + frame_election_provider_support::onchain::OnChainSequentialPhragmen; type Solver = frame_election_provider_support::SequentialPhragmen< AccountId, pallet_election_provider_multi_phase::SolutionAccuracyOf, @@ -1792,7 +1796,7 @@ mod tests { #[test] fn perbill_as_onchain_accuracy() { type OnChainAccuracy = ::Accuracy; - let maximum_chain_accuracy: Vec> = (0..MAX_NOMINATIONS) + let maximum_chain_accuracy: Vec> = (0..MaxNominations::get()) .map(|_| >::from(OnChainAccuracy::one().deconstruct())) .collect(); let _: UpperOf = diff --git a/bin/node/testing/Cargo.toml b/bin/node/testing/Cargo.toml index 29efc0028c159..3275aac0ef1de 100644 --- a/bin/node/testing/Cargo.toml +++ b/bin/node/testing/Cargo.toml @@ -24,13 +24,13 @@ sc-client-db = { version = "0.10.0-dev", path = "../../../client/db/", features sc-client-api = { version = "4.0.0-dev", path = "../../../client/api/" } sc-consensus = { version = "0.10.0-dev", path = "../../../client/consensus/common" } codec = { package = "parity-scale-codec", version = "2.0.0" } -sp-keyring = { version = "4.1.0-dev", path = "../../../primitives/keyring" } +sp-keyring = { version = "5.0.0", path = "../../../primitives/keyring" } node-executor = { version = "3.0.0-dev", path = "../executor" } node-primitives = { version = "2.0.0", path = "../primitives" } node-runtime = { version = "3.0.0-dev", path = "../runtime" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } -sp-io = { version = "4.0.0-dev", path = "../../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../../primitives/io" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } sc-executor = { version = "0.10.0-dev", path = "../../../client/executor", features = [ "wasmtime", ] } diff --git a/bin/utils/chain-spec-builder/Cargo.toml b/bin/utils/chain-spec-builder/Cargo.toml index f9bb4f94491a8..f6af82ba42eb0 100644 --- a/bin/utils/chain-spec-builder/Cargo.toml +++ b/bin/utils/chain-spec-builder/Cargo.toml @@ -15,10 +15,11 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] ansi_term = "0.12.1" +clap = { version = "3.0", features = ["derive"] } +rand = "0.8" + sc-keystore = { version = "4.0.0-dev", path = "../../../client/keystore" } sc-chain-spec = { version = "4.0.0-dev", path = "../../../client/chain-spec" } node-cli = { version = "3.0.0-dev", path = "../../node/cli" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } -sp-keystore = { version = "0.10.0", path = "../../../primitives/keystore" } -rand = "0.7.2" -structopt = "0.3.25" +sp-core = { version = "5.0.0", path = "../../../primitives/core" } +sp-keystore = { version = "0.11.0", path = "../../../primitives/keystore" } diff --git a/bin/utils/chain-spec-builder/src/main.rs b/bin/utils/chain-spec-builder/src/main.rs index 013fbeccfe0d7..3e8b1f4ea7523 100644 --- a/bin/utils/chain-spec-builder/src/main.rs +++ b/bin/utils/chain-spec-builder/src/main.rs @@ -23,8 +23,8 @@ use std::{ }; use ansi_term::Style; +use clap::Parser; use rand::{distributions::Alphanumeric, rngs::OsRng, Rng}; -use structopt::StructOpt; use node_cli::chain_spec::{self, AccountId}; use sc_keystore::LocalKeystore; @@ -36,52 +36,52 @@ use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; /// A utility to easily create a testnet chain spec definition with a given set /// of authorities and endowed accounts and/or generate random accounts. -#[derive(StructOpt)] -#[structopt(rename_all = "kebab-case")] +#[derive(Parser)] +#[clap(rename_all = "kebab-case")] enum ChainSpecBuilder { /// Create a new chain spec with the given authorities, endowed and sudo /// accounts. New { /// Authority key seed. - #[structopt(long, short, required = true)] + #[clap(long, short, required = true)] authority_seeds: Vec, /// Active nominators (SS58 format), each backing a random subset of the aforementioned /// authorities. - #[structopt(long, short, default_value = "0")] + #[clap(long, short, default_value = "0")] nominator_accounts: Vec, /// Endowed account address (SS58 format). - #[structopt(long, short)] + #[clap(long, short)] endowed_accounts: Vec, /// Sudo account address (SS58 format). - #[structopt(long, short)] + #[clap(long, short)] sudo_account: String, /// The path where the chain spec should be saved. - #[structopt(long, short, default_value = "./chain_spec.json")] + #[clap(long, short, default_value = "./chain_spec.json")] chain_spec_path: PathBuf, }, /// Create a new chain spec with the given number of authorities and endowed /// accounts. Random keys will be generated as required. Generate { /// The number of authorities. - #[structopt(long, short)] + #[clap(long, short)] authorities: usize, /// The number of nominators backing the aforementioned authorities. /// /// Will nominate a random subset of `authorities`. - #[structopt(long, short, default_value = "0")] + #[clap(long, short, default_value = "0")] nominators: usize, /// The number of endowed accounts. - #[structopt(long, short, default_value = "0")] + #[clap(long, short, default_value = "0")] endowed: usize, /// The path where the chain spec should be saved. - #[structopt(long, short, default_value = "./chain_spec.json")] + #[clap(long, short, default_value = "./chain_spec.json")] chain_spec_path: PathBuf, /// Path to use when saving generated keystores for each authority. /// /// At this path, a new folder will be created for each authority's /// keystore named `auth-$i` where `i` is the authority index, i.e. /// `auth-0`, `auth-1`, etc. - #[structopt(long, short)] + #[clap(long, short)] keystore_path: Option, }, } @@ -236,13 +236,15 @@ fn main() -> Result<(), String> { the chain spec builder binary in `--release` mode.\n", ); - let builder = ChainSpecBuilder::from_args(); + let builder = ChainSpecBuilder::parse(); let chain_spec_path = builder.chain_spec_path().to_path_buf(); let (authority_seeds, nominator_accounts, endowed_accounts, sudo_account) = match builder { ChainSpecBuilder::Generate { authorities, nominators, endowed, keystore_path, .. } => { let authorities = authorities.max(1); - let rand_str = || -> String { OsRng.sample_iter(&Alphanumeric).take(32).collect() }; + let rand_str = || -> String { + OsRng.sample_iter(&Alphanumeric).take(32).map(char::from).collect() + }; let authority_seeds = (0..authorities).map(|_| rand_str()).collect::>(); let nominator_seeds = (0..nominators).map(|_| rand_str()).collect::>(); diff --git a/bin/utils/subkey/Cargo.toml b/bin/utils/subkey/Cargo.toml index d3c38edb5771d..85f864cfbfc13 100644 --- a/bin/utils/subkey/Cargo.toml +++ b/bin/utils/subkey/Cargo.toml @@ -17,5 +17,5 @@ path = "src/main.rs" name = "subkey" [dependencies] +clap = { version = "3.0", features = ["derive"] } sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" } -structopt = "0.3.25" diff --git a/bin/utils/subkey/src/lib.rs b/bin/utils/subkey/src/lib.rs index 9a33ef2d2d6dd..73698db0b7ea0 100644 --- a/bin/utils/subkey/src/lib.rs +++ b/bin/utils/subkey/src/lib.rs @@ -16,14 +16,14 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use clap::Parser; use sc_cli::{ Error, GenerateCmd, GenerateNodeKeyCmd, InspectKeyCmd, InspectNodeKeyCmd, SignCmd, VanityCmd, VerifyCmd, }; -use structopt::StructOpt; -#[derive(Debug, StructOpt)] -#[structopt( +#[derive(Debug, Parser)] +#[clap( name = "subkey", author = "Parity Team ", about = "Utility for generating and restoring with Substrate keys" @@ -54,7 +54,7 @@ pub enum Subkey { /// Run the subkey command, given the appropriate runtime. pub fn run() -> Result<(), Error> { - match Subkey::from_args() { + match Subkey::parse() { Subkey::GenerateNodeKey(cmd) => cmd.run(), Subkey::Generate(cmd) => cmd.run(), Subkey::Inspect(cmd) => cmd.run(), diff --git a/client/allocator/Cargo.toml b/client/allocator/Cargo.toml index eb8d298e1ec25..6f20449b38bc7 100644 --- a/client/allocator/Cargo.toml +++ b/client/allocator/Cargo.toml @@ -14,7 +14,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-wasm-interface = { version = "4.1.0-dev", path = "../../primitives/wasm-interface" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-wasm-interface = { version = "5.0.0", path = "../../primitives/wasm-interface" } log = "0.4.11" thiserror = "1.0.30" diff --git a/client/api/Cargo.toml b/client/api/Cargo.toml index c18b920cace81..ab6ad96e286f9 100644 --- a/client/api/Cargo.toml +++ b/client/api/Cargo.toml @@ -19,7 +19,7 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = ] } sp-consensus = { version = "0.10.0-dev", path = "../../primitives/consensus/common" } sc-executor = { version = "0.10.0-dev", path = "../executor" } -sp-externalities = { version = "0.10.0", path = "../../primitives/externalities" } +sp-externalities = { version = "0.11.0", path = "../../primitives/externalities" } fnv = "1.0.6" futures = "0.3.1" hash-db = { version = "0.15.2", default-features = false } @@ -27,14 +27,14 @@ sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } log = "0.4.8" parking_lot = "0.11.2" sp-database = { version = "4.0.0-dev", path = "../../primitives/database" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } -sp-keystore = { version = "0.10.0", default-features = false, path = "../../primitives/keystore" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } +sp-keystore = { version = "0.11.0", default-features = false, path = "../../primitives/keystore" } sp-api = { version = "4.0.0-dev", path = "../../primitives/api" } sc-utils = { version = "4.0.0-dev", path = "../utils" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } -sp-state-machine = { version = "0.10.0", path = "../../primitives/state-machine" } -sp-trie = { version = "4.0.0", path = "../../primitives/trie" } -sp-storage = { version = "4.0.0", path = "../../primitives/storage" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } +sp-state-machine = { version = "0.11.0", path = "../../primitives/state-machine" } +sp-trie = { version = "5.0.0", path = "../../primitives/trie" } +sp-storage = { version = "5.0.0", path = "../../primitives/storage" } sc-transaction-pool-api = { version = "4.0.0-dev", path = "../transaction-pool/api" } prometheus-endpoint = { package = "substrate-prometheus-endpoint", version = "0.10.0-dev", path = "../../utils/prometheus" } diff --git a/client/api/src/backend.rs b/client/api/src/backend.rs index 004c0574fcbe8..bb2579e4a420e 100644 --- a/client/api/src/backend.rs +++ b/client/api/src/backend.rs @@ -70,14 +70,26 @@ pub struct ImportSummary { pub tree_route: Option>, } -/// Import operation wrapper +/// Finalization operation summary. +/// +/// Contains information about the block that just got finalized, +/// including tree heads that became stale at the moment of finalization. +pub struct FinalizeSummary { + /// Blocks that were finalized. + /// The last entry is the one that has been explicitly finalized. + pub finalized: Vec, + /// Heads that became stale during this finalization operation. + pub stale_heads: Vec, +} + +/// Import operation wrapper. pub struct ClientImportOperation> { /// DB Operation. pub op: B::BlockImportOperation, /// Summary of imported block. pub notify_imported: Option>, - /// A list of hashes of blocks that got finalized. - pub notify_finalized: Vec, + /// Summary of finalized block. + pub notify_finalized: Option>, } /// Helper function to apply auxiliary data insertion into an operation. diff --git a/client/api/src/client.rs b/client/api/src/client.rs index b6a5fbfad47a5..9bb212099565b 100644 --- a/client/api/src/client.rs +++ b/client/api/src/client.rs @@ -273,10 +273,14 @@ pub struct BlockImportNotification { /// Summary of a finalized block. #[derive(Clone, Debug)] pub struct FinalityNotification { - /// Imported block header hash. + /// Finalized block header hash. pub hash: Block::Hash, - /// Imported block header. + /// Finalized block header. pub header: Block::Header, + /// Path from the old finalized to new finalized parent (implicitly finalized blocks). + pub tree_route: Arc>, + /// Stale branches heads. + pub stale_heads: Arc>, } impl TryFrom> for ChainEvent { @@ -293,6 +297,6 @@ impl TryFrom> for ChainEvent { impl From> for ChainEvent { fn from(n: FinalityNotification) -> Self { - Self::Finalized { hash: n.hash } + Self::Finalized { hash: n.hash, tree_route: n.tree_route } } } diff --git a/client/authority-discovery/Cargo.toml b/client/authority-discovery/Cargo.toml index c6c523fa5eec7..e3a3ef2a3591b 100644 --- a/client/authority-discovery/Cargo.toml +++ b/client/authority-discovery/Cargo.toml @@ -19,7 +19,7 @@ prost-build = "0.9" [dependencies] async-trait = "0.1" codec = { package = "parity-scale-codec", default-features = false, version = "2.0.0" } -derive_more = "0.99.16" +thiserror = "1.0" futures = "0.3.9" futures-timer = "3.0.1" ip_network = "0.4.1" @@ -32,9 +32,9 @@ sc-client-api = { version = "4.0.0-dev", path = "../api" } sc-network = { version = "0.10.0-dev", path = "../network" } sp-authority-discovery = { version = "4.0.0-dev", path = "../../primitives/authority-discovery" } sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-keystore = { version = "0.10.0", path = "../../primitives/keystore" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-keystore = { version = "0.11.0", path = "../../primitives/keystore" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } sp-api = { version = "4.0.0-dev", path = "../../primitives/api" } [dev-dependencies] diff --git a/client/authority-discovery/src/error.rs b/client/authority-discovery/src/error.rs index 26ee02ef85321..bce39069ef7c7 100644 --- a/client/authority-discovery/src/error.rs +++ b/client/authority-discovery/src/error.rs @@ -24,40 +24,56 @@ use sp_core::crypto::CryptoTypePublicPair; pub type Result = std::result::Result; /// Error type for the authority discovery module. -#[derive(Debug, derive_more::Display, derive_more::From)] +#[derive(Debug, thiserror::Error)] pub enum Error { - /// Received dht value found event with records with different keys. + #[error("Received dht value found event with records with different keys.")] ReceivingDhtValueFoundEventWithDifferentKeys, - /// Received dht value found event with no records. + + #[error("Received dht value found event with no records.")] ReceivingDhtValueFoundEventWithNoRecords, - /// Failed to verify a dht payload with the given signature. + + #[error("Failed to verify a dht payload with the given signature.")] VerifyingDhtPayload, - /// Failed to hash the authority id to be used as a dht key. - HashingAuthorityId(libp2p::core::multiaddr::multihash::Error), - /// Failed calling into the Substrate runtime. - CallingRuntime(sp_blockchain::Error), - /// Received a dht record with a key that does not match any in-flight awaited keys. + + #[error("Failed to hash the authority id to be used as a dht key.")] + HashingAuthorityId(#[from] libp2p::core::multiaddr::multihash::Error), + + #[error("Failed calling into the Substrate runtime: {0}")] + CallingRuntime(#[from] sp_blockchain::Error), + + #[error("Received a dht record with a key that does not match any in-flight awaited keys.")] ReceivingUnexpectedRecord, - /// Failed to encode a protobuf payload. - EncodingProto(prost::EncodeError), - /// Failed to decode a protobuf payload. - DecodingProto(prost::DecodeError), - /// Failed to encode or decode scale payload. - EncodingDecodingScale(codec::Error), - /// Failed to parse a libp2p multi address. - ParsingMultiaddress(libp2p::core::multiaddr::Error), - /// Failed to parse a libp2p key. - ParsingLibp2pIdentity(sc_network::DecodingError), - /// Failed to sign using a specific public key. + + #[error("Failed to encode a protobuf payload.")] + EncodingProto(#[from] prost::EncodeError), + + #[error("Failed to decode a protobuf payload.")] + DecodingProto(#[from] prost::DecodeError), + + #[error("Failed to encode or decode scale payload.")] + EncodingDecodingScale(#[from] codec::Error), + + #[error("Failed to parse a libp2p multi address.")] + ParsingMultiaddress(#[from] libp2p::core::multiaddr::Error), + + #[error("Failed to parse a libp2p key.")] + ParsingLibp2pIdentity(#[from] sc_network::DecodingError), + + #[error("Failed to sign using a specific public key.")] MissingSignature(CryptoTypePublicPair), - /// Failed to sign using all public keys. + + #[error("Failed to sign using all public keys.")] Signing, - /// Failed to register Prometheus metric. - Prometheus(prometheus_endpoint::PrometheusError), - /// Received authority record that contains addresses with multiple peer ids + + #[error("Failed to register Prometheus metric.")] + Prometheus(#[from] prometheus_endpoint::PrometheusError), + + #[error("Received authority record that contains addresses with multiple peer ids")] ReceivingDhtValueFoundEventWithDifferentPeerIds, - /// Received authority record without any addresses having a peer id + + #[error("Received authority record without any addresses having a peer id")] ReceivingDhtValueFoundEventWithNoPeerIds, - /// Received authority record without a valid signature for the remote peer id. + + #[error("Received authority record without a valid signature for the remote peer id.")] MissingPeerIdSignature, } diff --git a/client/authority-discovery/src/worker.rs b/client/authority-discovery/src/worker.rs index ee5a15b9533b7..019abaac3cfcb 100644 --- a/client/authority-discovery/src/worker.rs +++ b/client/authority-discovery/src/worker.rs @@ -187,7 +187,7 @@ where Some(registry) => match Metrics::register(®istry) { Ok(metrics) => Some(metrics), Err(e) => { - error!(target: LOG_TARGET, "Failed to register metrics: {:?}", e); + error!(target: LOG_TARGET, "Failed to register metrics: {}", e); None }, }, @@ -242,7 +242,7 @@ where if let Err(e) = self.publish_ext_addresses(only_if_changed).await { error!( target: LOG_TARGET, - "Failed to publish external addresses: {:?}", e, + "Failed to publish external addresses: {}", e, ); } }, @@ -251,7 +251,7 @@ where if let Err(e) = self.refill_pending_lookups_queue().await { error!( target: LOG_TARGET, - "Failed to request addresses of authorities: {:?}", e, + "Failed to request addresses of authorities: {}", e, ); } }, @@ -426,7 +426,7 @@ where metrics.handle_value_found_event_failure.inc(); } - debug!(target: LOG_TARGET, "Failed to handle Dht value found event: {:?}", e); + debug!(target: LOG_TARGET, "Failed to handle Dht value found event: {}", e); } }, DhtEvent::ValueNotFound(hash) => { diff --git a/client/basic-authorship/Cargo.toml b/client/basic-authorship/Cargo.toml index e1083b15a9700..85592c7c549c0 100644 --- a/client/basic-authorship/Cargo.toml +++ b/client/basic-authorship/Cargo.toml @@ -19,8 +19,8 @@ futures-timer = "3.0.1" log = "0.4.8" prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus", version = "0.10.0-dev"} sp-api = { version = "4.0.0-dev", path = "../../primitives/api" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } sc-client-api = { version = "4.0.0-dev", path = "../api" } sp-consensus = { version = "0.10.0-dev", path = "../../primitives/consensus/common" } diff --git a/client/basic-authorship/src/basic_authorship.rs b/client/basic-authorship/src/basic_authorship.rs index 5ab207e39e583..23725e5138697 100644 --- a/client/basic-authorship/src/basic_authorship.rs +++ b/client/basic-authorship/src/basic_authorship.rs @@ -47,7 +47,7 @@ use sp_runtime::{ use std::{marker::PhantomData, pin::Pin, sync::Arc, time}; use prometheus_endpoint::Registry as PrometheusRegistry; -use sc_proposer_metrics::MetricsLink as PrometheusMetrics; +use sc_proposer_metrics::{EndProposingReason, MetricsLink as PrometheusMetrics}; /// Default block size limit in bytes used by [`Proposer`]. /// @@ -412,16 +412,21 @@ where debug!("Attempting to push transactions from the pool."); debug!("Pool status: {:?}", self.transaction_pool.status()); let mut transaction_pushed = false; - let mut hit_block_size_limit = false; - while let Some(pending_tx) = pending_iterator.next() { + let end_reason = loop { + let pending_tx = if let Some(pending_tx) = pending_iterator.next() { + pending_tx + } else { + break EndProposingReason::NoMoreTransactions + }; + let now = (self.now)(); if now > deadline { debug!( "Consensus deadline reached when pushing block transactions, \ proceeding with proposing." ); - break + break EndProposingReason::HitDeadline } let pending_tx_data = pending_tx.data().clone(); @@ -448,8 +453,7 @@ where continue } else { debug!("Reached block size limit, proceeding with proposing."); - hit_block_size_limit = true; - break + break EndProposingReason::HitBlockSizeLimit } } @@ -473,8 +477,8 @@ where so we will try a bit more before quitting." ); } else { - debug!("Block is full, proceed with proposing."); - break + debug!("Reached block weight limit, proceeding with proposing."); + break EndProposingReason::HitBlockWeightLimit } }, Err(e) if skipped > 0 => { @@ -491,9 +495,9 @@ where unqueue_invalid.push(pending_tx_hash); }, } - } + }; - if hit_block_size_limit && !transaction_pushed { + if matches!(end_reason, EndProposingReason::HitBlockSizeLimit) && !transaction_pushed { warn!( "Hit block size limit of `{}` without including any transaction!", block_size_limit, @@ -507,6 +511,8 @@ where self.metrics.report(|metrics| { metrics.number_of_transactions.set(block.extrinsics().len() as u64); metrics.block_constructed.observe(block_timer.elapsed().as_secs_f64()); + + metrics.report_end_proposing_reason(end_reason); }); info!( @@ -518,7 +524,7 @@ where block.extrinsics().len(), block.extrinsics() .iter() - .map(|xt| format!("{}", BlakeTwo256::hash_of(xt))) + .map(|xt| BlakeTwo256::hash_of(xt).to_string()) .collect::>() .join(", ") ); diff --git a/client/beefy/Cargo.toml b/client/beefy/Cargo.toml index 9761f18d78450..3ce556e85239b 100644 --- a/client/beefy/Cargo.toml +++ b/client/beefy/Cargo.toml @@ -19,12 +19,12 @@ codec = { version = "2.2.0", package = "parity-scale-codec", features = ["derive prometheus = { version = "0.10.0-dev", package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" } sp-api = { version = "4.0.0-dev", path = "../../primitives/api" } -sp-application-crypto = { version = "4.0.0", path = "../../primitives/application-crypto" } +sp-application-crypto = { version = "5.0.0", path = "../../primitives/application-crypto" } sp-arithmetic = { version = "4.0.0", path = "../../primitives/arithmetic" } sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-keystore = { version = "0.10.0", path = "../../primitives/keystore" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-keystore = { version = "0.11.0", path = "../../primitives/keystore" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } sc-chain-spec = { version = "4.0.0-dev", path = "../../client/chain-spec" } sc-utils = { version = "4.0.0-dev", path = "../utils" } @@ -39,4 +39,4 @@ beefy-primitives = { version = "4.0.0-dev", path = "../../primitives/beefy" } sp-tracing = { version = "4.0.0", path = "../../primitives/tracing" } sc-network-test = { version = "0.8.0", path = "../network/test" } -strum = { version = "0.22", features = ["derive"] } +strum = { version = "0.23", features = ["derive"] } diff --git a/client/beefy/rpc/Cargo.toml b/client/beefy/rpc/Cargo.toml index a72af62fdeeac..44837fb0e41f5 100644 --- a/client/beefy/rpc/Cargo.toml +++ b/client/beefy/rpc/Cargo.toml @@ -8,12 +8,11 @@ repository = "https://github.com/paritytech/substrate" description = "RPC for the BEEFY Client gadget for substrate" [dependencies] -derive_more = "0.99" futures = "0.3.16" log = "0.4" parking_lot = "0.11" thiserror = "1.0" -serde = { version = "1.0.132", features = ["derive"] } +serde = { version = "1.0.136", features = ["derive"] } jsonrpc-core = "18.0.0" jsonrpc-core-client = "18.0.0" @@ -25,8 +24,8 @@ codec = { version = "2.2.0", package = "parity-scale-codec", features = ["derive sc-rpc = { version = "4.0.0-dev", path = "../../rpc" } sc-utils = { version = "4.0.0-dev", path = "../../utils" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } beefy-gadget = { version = "4.0.0-dev", path = "../." } beefy-primitives = { version = "4.0.0-dev", path = "../../../primitives/beefy" } diff --git a/client/beefy/rpc/src/lib.rs b/client/beefy/rpc/src/lib.rs index dc9ee8b94701b..4c1bc03e222e7 100644 --- a/client/beefy/rpc/src/lib.rs +++ b/client/beefy/rpc/src/lib.rs @@ -36,15 +36,15 @@ mod notification; type FutureResult = jsonrpc_core::BoxFuture>; -#[derive(Debug, derive_more::Display, derive_more::From, thiserror::Error)] +#[derive(Debug, thiserror::Error)] /// Top-level error type for the RPC handler pub enum Error { /// The BEEFY RPC endpoint is not ready. - #[display(fmt = "BEEFY RPC endpoint not ready")] + #[error("BEEFY RPC endpoint not ready")] EndpointNotReady, /// The BEEFY RPC background task failed to spawn. - #[display(fmt = "BEEFY RPC background task failed to spawn")] - RpcTaskFailure(SpawnError), + #[error("BEEFY RPC background task failed to spawn")] + RpcTaskFailure(#[from] SpawnError), } /// The error codes returned by jsonrpc. diff --git a/client/beefy/src/worker.rs b/client/beefy/src/worker.rs index 0c7d8d4ffdc9c..3f23638758eca 100644 --- a/client/beefy/src/worker.rs +++ b/client/beefy/src/worker.rs @@ -378,7 +378,7 @@ where .expect("forwards closure result; the closure always returns Ok; qed."); } }) { - error!(target: "beefy", "🥩 Failed to get hash for block number {}; err: {:?}", + error!(target: "beefy", "🥩 Failed to get hash for block number {}: {}", block_num, err); } diff --git a/client/block-builder/Cargo.toml b/client/block-builder/Cargo.toml index 19b8839c12280..e41ab0a5caf15 100644 --- a/client/block-builder/Cargo.toml +++ b/client/block-builder/Cargo.toml @@ -14,11 +14,11 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-state-machine = { version = "0.10.0", path = "../../primitives/state-machine" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-state-machine = { version = "0.11.0", path = "../../primitives/state-machine" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } sp-api = { version = "4.0.0-dev", path = "../../primitives/api" } sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } sp-block-builder = { version = "4.0.0-dev", path = "../../primitives/block-builder" } sp-inherents = { version = "4.0.0-dev", path = "../../primitives/inherents" } sc-client-api = { version = "4.0.0-dev", path = "../api" } diff --git a/client/chain-spec/Cargo.toml b/client/chain-spec/Cargo.toml index 0110e82532a5c..9b299f00a2147 100644 --- a/client/chain-spec/Cargo.toml +++ b/client/chain-spec/Cargo.toml @@ -16,10 +16,10 @@ targets = ["x86_64-unknown-linux-gnu"] sc-chain-spec-derive = { version = "4.0.0-dev", path = "./derive" } impl-trait-for-tuples = "0.2.1" sc-network = { version = "0.10.0-dev", path = "../network" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -serde = { version = "1.0.132", features = ["derive"] } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +serde = { version = "1.0.136", features = ["derive"] } serde_json = "1.0.74" -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } sc-telemetry = { version = "4.0.0-dev", path = "../telemetry" } codec = { package = "parity-scale-codec", version = "2.0.0" } memmap2 = "0.5.0" diff --git a/client/chain-spec/src/chain_spec.rs b/client/chain-spec/src/chain_spec.rs index a22a68d2944fa..2412a7cdf83f0 100644 --- a/client/chain-spec/src/chain_spec.rs +++ b/client/chain-spec/src/chain_spec.rs @@ -164,6 +164,10 @@ struct ClientSpec { boot_nodes: Vec, telemetry_endpoints: Option, protocol_id: Option, + /// Arbitrary string. Nodes will only synchronize with other nodes that have the same value + /// in their `fork_id`. This can be used in order to segregate nodes in cases when multiple + /// chains have the same genesis hash. + #[serde(default = "Default::default", skip_serializing_if = "Option::is_none")] fork_id: Option, properties: Option, #[serde(flatten)] diff --git a/client/cli/Cargo.toml b/client/cli/Cargo.toml index 01f5aab25d5fa..5375400056faf 100644 --- a/client/cli/Cargo.toml +++ b/client/cli/Cargo.toml @@ -13,42 +13,41 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -log = "0.4.11" -regex = "1.5.4" -tokio = { version = "1.15", features = [ "signal", "rt-multi-thread" ] } -futures = "0.3.9" +chrono = "0.4.10" +clap = { version = "3.0", features = ["derive"] } fdlimit = "0.2.1" -libp2p = "0.40.0" -parity-scale-codec = "2.3.1" +futures = "0.3.9" hex = "0.4.2" +libp2p = "0.40.0" +log = "0.4.11" +names = { version = "0.12.0", default-features = false } rand = "0.7.3" -tiny-bip39 = "0.8.2" +regex = "1.5.4" +rpassword = "5.0.0" +serde = "1.0.136" serde_json = "1.0.74" -sc-keystore = { version = "4.0.0-dev", path = "../keystore" } -sp-panic-handler = { version = "4.0.0", path = "../../primitives/panic-handler" } +thiserror = "1.0.30" +tiny-bip39 = "0.8.2" +tokio = { version = "1.15", features = ["signal", "rt-multi-thread"] } + +parity-scale-codec = "2.3.1" sc-client-api = { version = "4.0.0-dev", path = "../api" } -sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } +sc-keystore = { version = "4.0.0-dev", path = "../keystore" } sc-network = { version = "0.10.0-dev", path = "../network" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } -sc-utils = { version = "4.0.0-dev", path = "../utils" } -sp-version = { version = "4.0.0-dev", path = "../../primitives/version" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-keystore = { version = "0.10.0", path = "../../primitives/keystore" } sc-service = { version = "0.10.0-dev", default-features = false, path = "../service" } sc-telemetry = { version = "4.0.0-dev", path = "../telemetry" } -sp-keyring = { version = "4.1.0-dev", path = "../../primitives/keyring" } -names = { version = "0.12.0", default-features = false } -structopt = "0.3.25" sc-tracing = { version = "4.0.0-dev", path = "../tracing" } -chrono = "0.4.10" -serde = "1.0.132" -thiserror = "1.0.30" -rpassword = "5.0.0" +sc-utils = { version = "4.0.0-dev", path = "../utils" } +sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-keyring = { version = "5.0.0", path = "../../primitives/keyring" } +sp-keystore = { version = "0.11.0", path = "../../primitives/keystore" } +sp-panic-handler = { version = "4.0.0", path = "../../primitives/panic-handler" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } +sp-version = { version = "4.0.0-dev", path = "../../primitives/version" } [dev-dependencies] tempfile = "3.1.0" [features] -wasmtime = [ - "sc-service/wasmtime", -] +wasmtime = ["sc-service/wasmtime"] diff --git a/client/cli/src/arg_enums.rs b/client/cli/src/arg_enums.rs index c13361a9ac2ba..249e3c639e4ef 100644 --- a/client/cli/src/arg_enums.rs +++ b/client/cli/src/arg_enums.rs @@ -18,7 +18,7 @@ // NOTE: we allow missing docs here because arg_enum! creates the function variants without doc #![allow(missing_docs)] -use structopt::clap::arg_enum; +use clap::ArgEnum; /// How to execute Wasm runtime code. #[derive(Debug, Clone, Copy)] @@ -86,12 +86,11 @@ impl Into for WasmExecutionMethod { } } -arg_enum! { - #[allow(missing_docs)] - #[derive(Debug, Copy, Clone, PartialEq, Eq)] - pub enum TracingReceiver { - Log, - } +#[allow(missing_docs)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)] +#[clap(rename_all = "PascalCase")] +pub enum TracingReceiver { + Log, } impl Into for TracingReceiver { @@ -102,44 +101,40 @@ impl Into for TracingReceiver { } } -arg_enum! { - #[allow(missing_docs)] - #[derive(Debug, Copy, Clone, PartialEq, Eq)] - pub enum NodeKeyType { - Ed25519 - } +#[allow(missing_docs)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)] +#[clap(rename_all = "PascalCase")] +pub enum NodeKeyType { + Ed25519, } -arg_enum! { - #[derive(Debug, Copy, Clone, PartialEq, Eq)] - pub enum CryptoScheme { - Ed25519, - Sr25519, - Ecdsa, - } +#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)] +#[clap(rename_all = "PascalCase")] +pub enum CryptoScheme { + Ed25519, + Sr25519, + Ecdsa, } -arg_enum! { - #[derive(Debug, Copy, Clone, PartialEq, Eq)] - pub enum OutputType { - Json, - Text, - } +#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)] +#[clap(rename_all = "PascalCase")] +pub enum OutputType { + Json, + Text, } -arg_enum! { - /// How to execute blocks - #[derive(Debug, Clone, Copy, PartialEq, Eq)] - pub enum ExecutionStrategy { - // Execute with native build (if available, WebAssembly otherwise). - Native, - // Only execute with the WebAssembly build. - Wasm, - // Execute with both native (where available) and WebAssembly builds. - Both, - // Execute with the native build if possible; if it fails, then execute with WebAssembly. - NativeElseWasm, - } +/// How to execute blocks +#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)] +#[clap(rename_all = "PascalCase")] +pub enum ExecutionStrategy { + // Execute with native build (if available, WebAssembly otherwise). + Native, + // Only execute with the WebAssembly build. + Wasm, + // Execute with both native (where available) and WebAssembly builds. + Both, + // Execute with the native build if possible; if it fails, then execute with WebAssembly. + NativeElseWasm, } impl Into for ExecutionStrategy { @@ -165,19 +160,18 @@ impl ExecutionStrategy { } } -arg_enum! { - /// Available RPC methods. - #[allow(missing_docs)] - #[derive(Debug, Copy, Clone, PartialEq)] - pub enum RpcMethods { - // Expose every RPC method only when RPC is listening on `localhost`, - // otherwise serve only safe RPC methods. - Auto, - // Allow only a safe subset of RPC methods. - Safe, - // Expose every RPC method (even potentially unsafe ones). - Unsafe, - } +/// Available RPC methods. +#[allow(missing_docs)] +#[derive(Debug, Copy, Clone, PartialEq, ArgEnum)] +#[clap(rename_all = "PascalCase")] +pub enum RpcMethods { + // Expose every RPC method only when RPC is listening on `localhost`, + // otherwise serve only safe RPC methods. + Auto, + // Allow only a safe subset of RPC methods. + Safe, + // Expose every RPC method (even potentially unsafe ones). + Unsafe, } impl Into for RpcMethods { @@ -225,31 +219,28 @@ impl Database { } } -arg_enum! { - /// Whether off-chain workers are enabled. - #[allow(missing_docs)] - #[derive(Debug, Clone)] - pub enum OffchainWorkerEnabled { - Always, - Never, - WhenValidating, - } +/// Whether off-chain workers are enabled. +#[allow(missing_docs)] +#[derive(Debug, Clone, ArgEnum)] +#[clap(rename_all = "PascalCase")] +pub enum OffchainWorkerEnabled { + Always, + Never, + WhenValidating, } -arg_enum! { - /// Syncing mode. - #[allow(missing_docs)] - #[derive(Debug, Clone, Copy)] - pub enum SyncMode { - // Full sync. Donwnload end verify all blocks. - Full, - // Download blocks without executing them. Download latest state with proofs. - Fast, - // Download blocks without executing them. Download latest state without proofs. - FastUnsafe, - // Prove finality and download the latest state. - Warp, - } +/// Syncing mode. +#[derive(Debug, Clone, Copy, ArgEnum)] +#[clap(rename_all = "PascalCase")] +pub enum SyncMode { + // Full sync. Donwnload end verify all blocks. + Full, + // Download blocks without executing them. Download latest state with proofs. + Fast, + // Download blocks without executing them. Download latest state without proofs. + FastUnsafe, + // Prove finality and download the latest state. + Warp, } impl Into for SyncMode { diff --git a/client/cli/src/commands/build_spec_cmd.rs b/client/cli/src/commands/build_spec_cmd.rs index ad7cf455eb3b2..3196a3e7b915f 100644 --- a/client/cli/src/commands/build_spec_cmd.rs +++ b/client/cli/src/commands/build_spec_cmd.rs @@ -21,6 +21,7 @@ use crate::{ params::{NodeKeyParams, SharedParams}, CliConfiguration, }; +use clap::Parser; use log::info; use sc_network::config::build_multiaddr; use sc_service::{ @@ -28,28 +29,27 @@ use sc_service::{ ChainSpec, }; use std::io::Write; -use structopt::StructOpt; /// The `build-spec` command used to build a specification. -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Parser)] pub struct BuildSpecCmd { /// Force raw genesis storage output. - #[structopt(long = "raw")] + #[clap(long)] pub raw: bool, /// Disable adding the default bootnode to the specification. /// /// By default the `/ip4/127.0.0.1/tcp/30333/p2p/NODE_PEER_ID` bootnode is added to the /// specification when no bootnode exists. - #[structopt(long = "disable-default-bootnode")] + #[clap(long)] pub disable_default_bootnode: bool, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub shared_params: SharedParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub node_key_params: NodeKeyParams, } diff --git a/client/cli/src/commands/check_block_cmd.rs b/client/cli/src/commands/check_block_cmd.rs index b5642cf4b629b..b7e69b1360a0a 100644 --- a/client/cli/src/commands/check_block_cmd.rs +++ b/client/cli/src/commands/check_block_cmd.rs @@ -21,30 +21,30 @@ use crate::{ params::{BlockNumberOrHash, ImportParams, SharedParams}, CliConfiguration, }; +use clap::Parser; use sc_client_api::{BlockBackend, HeaderBackend}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use std::{fmt::Debug, str::FromStr, sync::Arc}; -use structopt::StructOpt; /// The `check-block` command used to validate blocks. -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Parser)] pub struct CheckBlockCmd { /// Block hash or number - #[structopt(value_name = "HASH or NUMBER")] + #[clap(value_name = "HASH or NUMBER")] pub input: BlockNumberOrHash, /// The default number of 64KB pages to ever allocate for Wasm execution. /// /// Don't alter this unless you know what you're doing. - #[structopt(long = "default-heap-pages", value_name = "COUNT")] + #[clap(long, value_name = "COUNT")] pub default_heap_pages: Option, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub shared_params: SharedParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub import_params: ImportParams, } diff --git a/client/cli/src/commands/export_blocks_cmd.rs b/client/cli/src/commands/export_blocks_cmd.rs index af7de3c12e77b..ff35b5a51fcad 100644 --- a/client/cli/src/commands/export_blocks_cmd.rs +++ b/client/cli/src/commands/export_blocks_cmd.rs @@ -21,46 +21,46 @@ use crate::{ params::{DatabaseParams, GenericNumber, PruningParams, SharedParams}, CliConfiguration, }; +use clap::Parser; use log::info; use sc_client_api::{BlockBackend, UsageProvider}; use sc_service::{chain_ops::export_blocks, config::DatabaseSource}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use std::{fmt::Debug, fs, io, path::PathBuf, str::FromStr, sync::Arc}; -use structopt::StructOpt; /// The `export-blocks` command used to export blocks. -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Parser)] pub struct ExportBlocksCmd { /// Output file name or stdout if unspecified. - #[structopt(parse(from_os_str))] + #[clap(parse(from_os_str))] pub output: Option, /// Specify starting block number. /// /// Default is 1. - #[structopt(long = "from", value_name = "BLOCK")] + #[clap(long, value_name = "BLOCK")] pub from: Option, /// Specify last block number. /// /// Default is best block. - #[structopt(long = "to", value_name = "BLOCK")] + #[clap(long, value_name = "BLOCK")] pub to: Option, /// Use binary output rather than JSON. - #[structopt(long)] + #[clap(long)] pub binary: bool, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub shared_params: SharedParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub pruning_params: PruningParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub database_params: DatabaseParams, } @@ -76,7 +76,7 @@ impl ExportBlocksCmd { C: BlockBackend + UsageProvider + 'static, <::Number as FromStr>::Err: Debug, { - if let DatabaseSource::RocksDb { ref path, .. } = database_config { + if let Some(path) = database_config.path() { info!("DB path: {}", path.display()); } diff --git a/client/cli/src/commands/export_state_cmd.rs b/client/cli/src/commands/export_state_cmd.rs index b322265aee2b5..b76724caf0fef 100644 --- a/client/cli/src/commands/export_state_cmd.rs +++ b/client/cli/src/commands/export_state_cmd.rs @@ -18,30 +18,34 @@ use crate::{ error, - params::{BlockNumberOrHash, PruningParams, SharedParams}, + params::{BlockNumberOrHash, DatabaseParams, PruningParams, SharedParams}, CliConfiguration, }; +use clap::Parser; use log::info; use sc_client_api::{StorageProvider, UsageProvider}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use std::{fmt::Debug, io::Write, str::FromStr, sync::Arc}; -use structopt::StructOpt; /// The `export-state` command used to export the state of a given block into /// a chain spec. -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Parser)] pub struct ExportStateCmd { /// Block hash or number. - #[structopt(value_name = "HASH or NUMBER")] + #[clap(value_name = "HASH or NUMBER")] pub input: Option, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub shared_params: SharedParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub pruning_params: PruningParams, + + #[allow(missing_docs)] + #[clap(flatten)] + pub database_params: DatabaseParams, } impl ExportStateCmd { @@ -81,4 +85,8 @@ impl CliConfiguration for ExportStateCmd { fn pruning_params(&self) -> Option<&PruningParams> { Some(&self.pruning_params) } + + fn database_params(&self) -> Option<&DatabaseParams> { + Some(&self.database_params) + } } diff --git a/client/cli/src/commands/generate.rs b/client/cli/src/commands/generate.rs index ce4c24fc7d8c9..9c1e5b689584b 100644 --- a/client/cli/src/commands/generate.rs +++ b/client/cli/src/commands/generate.rs @@ -21,30 +21,30 @@ use crate::{ NetworkSchemeFlag, OutputTypeFlag, }; use bip39::{Language, Mnemonic, MnemonicType}; -use structopt::StructOpt; +use clap::Parser; /// The `generate` command -#[derive(Debug, StructOpt, Clone)] -#[structopt(name = "generate", about = "Generate a random account")] +#[derive(Debug, Clone, Parser)] +#[clap(name = "generate", about = "Generate a random account")] pub struct GenerateCmd { /// The number of words in the phrase to generate. One of 12 (default), 15, 18, 21 and 24. - #[structopt(long, short = "w", value_name = "WORDS")] + #[clap(short = 'w', long, value_name = "WORDS")] words: Option, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub keystore_params: KeystoreParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub network_scheme: NetworkSchemeFlag, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub output_scheme: OutputTypeFlag, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub crypto_scheme: CryptoSchemeFlag, } @@ -78,12 +78,11 @@ impl GenerateCmd { #[cfg(test)] mod tests { - use super::GenerateCmd; - use structopt::StructOpt; + use super::*; #[test] fn generate() { - let generate = GenerateCmd::from_iter(&["generate", "--password", "12345"]); + let generate = GenerateCmd::parse_from(&["generate", "--password", "12345"]); assert!(generate.run().is_ok()) } } diff --git a/client/cli/src/commands/generate_node_key.rs b/client/cli/src/commands/generate_node_key.rs index 2221c8a99ded1..8c634dca9acf2 100644 --- a/client/cli/src/commands/generate_node_key.rs +++ b/client/cli/src/commands/generate_node_key.rs @@ -18,13 +18,13 @@ //! Implementation of the `generate-node-key` subcommand use crate::Error; +use clap::Parser; use libp2p::identity::{ed25519 as libp2p_ed25519, PublicKey}; use std::{fs, path::PathBuf}; -use structopt::StructOpt; /// The `generate-node-key` command -#[derive(Debug, StructOpt)] -#[structopt( +#[derive(Debug, Parser)] +#[clap( name = "generate-node-key", about = "Generate a random node libp2p key, save it to \ file or print it to stdout and print its peer ID to stderr" @@ -33,7 +33,7 @@ pub struct GenerateNodeKeyCmd { /// Name of file to save secret key to. /// /// If not given, the secret key is printed to stdout. - #[structopt(long)] + #[clap(long)] file: Option, } @@ -66,7 +66,7 @@ mod tests { fn generate_node_key() { let mut file = Builder::new().prefix("keyfile").tempfile().unwrap(); let file_path = file.path().display().to_string(); - let generate = GenerateNodeKeyCmd::from_iter(&["generate-node-key", "--file", &file_path]); + let generate = GenerateNodeKeyCmd::parse_from(&["generate-node-key", "--file", &file_path]); assert!(generate.run().is_ok()); let mut buf = String::new(); assert!(file.read_to_string(&mut buf).is_ok()); diff --git a/client/cli/src/commands/import_blocks_cmd.rs b/client/cli/src/commands/import_blocks_cmd.rs index d0a0b39a5bf8c..fece33ba23a2c 100644 --- a/client/cli/src/commands/import_blocks_cmd.rs +++ b/client/cli/src/commands/import_blocks_cmd.rs @@ -21,6 +21,7 @@ use crate::{ params::{ImportParams, SharedParams}, CliConfiguration, }; +use clap::Parser; use sc_client_api::HeaderBackend; use sc_service::chain_ops::import_blocks; use sp_runtime::traits::Block as BlockT; @@ -31,31 +32,30 @@ use std::{ path::PathBuf, sync::Arc, }; -use structopt::StructOpt; /// The `import-blocks` command used to import blocks. -#[derive(Debug, StructOpt)] +#[derive(Debug, Parser)] pub struct ImportBlocksCmd { /// Input file or stdin if unspecified. - #[structopt(parse(from_os_str))] + #[clap(parse(from_os_str))] pub input: Option, /// The default number of 64KB pages to ever allocate for Wasm execution. /// /// Don't alter this unless you know what you're doing. - #[structopt(long = "default-heap-pages", value_name = "COUNT")] + #[clap(long, value_name = "COUNT")] pub default_heap_pages: Option, /// Try importing blocks from binary format rather than JSON. - #[structopt(long)] + #[clap(long)] pub binary: bool, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub shared_params: SharedParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub import_params: ImportParams, } diff --git a/client/cli/src/commands/insert_key.rs b/client/cli/src/commands/insert_key.rs index cf40fb7ec4bfd..852b4e50376ff 100644 --- a/client/cli/src/commands/insert_key.rs +++ b/client/cli/src/commands/insert_key.rs @@ -20,42 +20,37 @@ use crate::{ utils, with_crypto_scheme, CryptoScheme, Error, KeystoreParams, SharedParams, SubstrateCli, }; +use clap::Parser; use sc_keystore::LocalKeystore; use sc_service::config::{BasePath, KeystoreConfig}; use sp_core::crypto::{KeyTypeId, SecretString}; use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use std::{convert::TryFrom, sync::Arc}; -use structopt::StructOpt; /// The `insert` command -#[derive(Debug, StructOpt, Clone)] -#[structopt(name = "insert", about = "Insert a key to the keystore of a node.")] +#[derive(Debug, Clone, Parser)] +#[clap(name = "insert", about = "Insert a key to the keystore of a node.")] pub struct InsertKeyCmd { /// The secret key URI. /// If the value is a file, the file content is used as URI. /// If not given, you will be prompted for the URI. - #[structopt(long)] + #[clap(long)] suri: Option, /// Key type, examples: "gran", or "imon" - #[structopt(long)] + #[clap(long)] key_type: String, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub shared_params: SharedParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub keystore_params: KeystoreParams, /// The cryptography scheme that should be used to generate the key out of the given URI. - #[structopt( - long, - value_name = "SCHEME", - possible_values = &CryptoScheme::variants(), - case_insensitive = true, - )] + #[clap(long, value_name = "SCHEME", arg_enum, ignore_case = true)] pub scheme: CryptoScheme, } @@ -100,7 +95,6 @@ mod tests { use super::*; use sc_service::{ChainSpec, ChainType, GenericChainSpec, NoExtension}; use sp_core::{sr25519::Pair, ByteArray, Pair as _}; - use structopt::StructOpt; use tempfile::TempDir; struct Cli; @@ -156,7 +150,7 @@ mod tests { let path_str = format!("{}", path.path().display()); let (key, uri, _) = Pair::generate_with_phrase(None); - let inspect = InsertKeyCmd::from_iter(&[ + let inspect = InsertKeyCmd::parse_from(&[ "insert-key", "-d", &path_str, diff --git a/client/cli/src/commands/inspect_key.rs b/client/cli/src/commands/inspect_key.rs index 34f51dc5ec42f..61fa8d2157e3b 100644 --- a/client/cli/src/commands/inspect_key.rs +++ b/client/cli/src/commands/inspect_key.rs @@ -21,13 +21,13 @@ use crate::{ utils::{self, print_from_public, print_from_uri}, with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams, NetworkSchemeFlag, OutputTypeFlag, }; +use clap::Parser; use sp_core::crypto::{ExposeSecret, SecretString, SecretUri, Ss58Codec}; use std::str::FromStr; -use structopt::StructOpt; /// The `inspect` command -#[derive(Debug, StructOpt)] -#[structopt( +#[derive(Debug, Parser)] +#[clap( name = "inspect", about = "Gets a public key and a SS58 address from the provided Secret URI" )] @@ -44,23 +44,23 @@ pub struct InspectKeyCmd { uri: Option, /// Is the given `uri` a hex encoded public key? - #[structopt(long)] + #[clap(long)] public: bool, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub keystore_params: KeystoreParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub network_scheme: NetworkSchemeFlag, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub output_scheme: OutputTypeFlag, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub crypto_scheme: CryptoSchemeFlag, /// Expect that `--uri` has the given public key/account-id. @@ -72,7 +72,7 @@ pub struct InspectKeyCmd { /// /// If there is no derivation in `--uri`, the public key will be checked against the public key /// of `--uri` directly. - #[structopt(long, conflicts_with = "public")] + #[clap(long, conflicts_with = "public")] pub expect_public: Option, } @@ -158,7 +158,6 @@ mod tests { use super::*; use sp_core::crypto::{ByteArray, Pair}; use sp_runtime::traits::IdentifyAccount; - use structopt::StructOpt; #[test] fn inspect() { @@ -166,10 +165,10 @@ mod tests { "remember fiber forum demise paper uniform squirrel feel access exclude casual effort"; let seed = "0xad1fb77243b536b90cfe5f0d351ab1b1ac40e3890b41dc64f766ee56340cfca5"; - let inspect = InspectKeyCmd::from_iter(&["inspect-key", words, "--password", "12345"]); + let inspect = InspectKeyCmd::parse_from(&["inspect-key", words, "--password", "12345"]); assert!(inspect.run().is_ok()); - let inspect = InspectKeyCmd::from_iter(&["inspect-key", seed]); + let inspect = InspectKeyCmd::parse_from(&["inspect-key", seed]); assert!(inspect.run().is_ok()); } @@ -177,14 +176,14 @@ mod tests { fn inspect_public_key() { let public = "0x12e76e0ae8ce41b6516cce52b3f23a08dcb4cfeed53c6ee8f5eb9f7367341069"; - let inspect = InspectKeyCmd::from_iter(&["inspect-key", "--public", public]); + let inspect = InspectKeyCmd::parse_from(&["inspect-key", "--public", public]); assert!(inspect.run().is_ok()); } #[test] fn inspect_with_expected_public_key() { let check_cmd = |seed, expected_public, success| { - let inspect = InspectKeyCmd::from_iter(&[ + let inspect = InspectKeyCmd::parse_from(&[ "inspect-key", "--expect-public", expected_public, diff --git a/client/cli/src/commands/inspect_node_key.rs b/client/cli/src/commands/inspect_node_key.rs index a5793873dd68f..4c0798cc0635c 100644 --- a/client/cli/src/commands/inspect_node_key.rs +++ b/client/cli/src/commands/inspect_node_key.rs @@ -18,23 +18,23 @@ //! Implementation of the `inspect-node-key` subcommand use crate::{Error, NetworkSchemeFlag}; +use clap::Parser; use libp2p::identity::{ed25519, PublicKey}; use std::{fs, path::PathBuf}; -use structopt::StructOpt; /// The `inspect-node-key` command -#[derive(Debug, StructOpt)] -#[structopt( +#[derive(Debug, Parser)] +#[clap( name = "inspect-node-key", about = "Print the peer ID corresponding to the node key in the given file." )] pub struct InspectNodeKeyCmd { /// Name of file to read the secret key from. - #[structopt(long)] + #[clap(long)] file: PathBuf, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub network_scheme: NetworkSchemeFlag, } @@ -63,11 +63,11 @@ mod tests { fn inspect_node_key() { let path = tempfile::tempdir().unwrap().into_path().join("node-id").into_os_string(); let path = path.to_str().unwrap(); - let cmd = GenerateNodeKeyCmd::from_iter(&["generate-node-key", "--file", path.clone()]); + let cmd = GenerateNodeKeyCmd::parse_from(&["generate-node-key", "--file", path.clone()]); assert!(cmd.run().is_ok()); - let cmd = InspectNodeKeyCmd::from_iter(&["inspect-node-key", "--file", path]); + let cmd = InspectNodeKeyCmd::parse_from(&["inspect-node-key", "--file", path]); assert!(cmd.run().is_ok()); } } diff --git a/client/cli/src/commands/key.rs b/client/cli/src/commands/key.rs index 0bfc68f8c32e2..e0f3524196e2c 100644 --- a/client/cli/src/commands/key.rs +++ b/client/cli/src/commands/key.rs @@ -17,16 +17,14 @@ //! Key related CLI utilities -use crate::{Error, SubstrateCli}; -use structopt::StructOpt; - use super::{ generate::GenerateCmd, generate_node_key::GenerateNodeKeyCmd, insert_key::InsertKeyCmd, inspect_key::InspectKeyCmd, inspect_node_key::InspectNodeKeyCmd, }; +use crate::{Error, SubstrateCli}; /// Key utilities for the cli. -#[derive(Debug, StructOpt)] +#[derive(Debug, clap::Subcommand)] pub enum KeySubcommand { /// Generate a random node libp2p key, save it to file or print it to stdout /// and print its peer ID to stderr. diff --git a/client/cli/src/commands/purge_chain_cmd.rs b/client/cli/src/commands/purge_chain_cmd.rs index eb19762df7d8a..7dd7c1f5a5a5a 100644 --- a/client/cli/src/commands/purge_chain_cmd.rs +++ b/client/cli/src/commands/purge_chain_cmd.rs @@ -21,27 +21,27 @@ use crate::{ params::{DatabaseParams, SharedParams}, CliConfiguration, }; +use clap::Parser; use sc_service::DatabaseSource; use std::{ fmt::Debug, fs, io::{self, Write}, }; -use structopt::StructOpt; /// The `purge-chain` command used to remove the whole chain. -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Parser)] pub struct PurgeChainCmd { /// Skip interactive prompt by answering yes automatically. - #[structopt(short = "y")] + #[clap(short = 'y')] pub yes: bool, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub shared_params: SharedParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub database_params: DatabaseParams, } diff --git a/client/cli/src/commands/revert_cmd.rs b/client/cli/src/commands/revert_cmd.rs index a671469ba7fdf..c207d198d5a27 100644 --- a/client/cli/src/commands/revert_cmd.rs +++ b/client/cli/src/commands/revert_cmd.rs @@ -21,25 +21,25 @@ use crate::{ params::{GenericNumber, PruningParams, SharedParams}, CliConfiguration, }; +use clap::Parser; use sc_client_api::{Backend, UsageProvider}; use sc_service::chain_ops::revert_chain; use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use std::{fmt::Debug, str::FromStr, sync::Arc}; -use structopt::StructOpt; /// The `revert` command used revert the chain to a previous state. -#[derive(Debug, StructOpt)] +#[derive(Debug, Parser)] pub struct RevertCmd { /// Number of blocks to revert. - #[structopt(default_value = "256")] + #[clap(default_value = "256")] pub num: GenericNumber, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub shared_params: SharedParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub pruning_params: PruningParams, } diff --git a/client/cli/src/commands/run_cmd.rs b/client/cli/src/commands/run_cmd.rs index 08b8fd87e2c82..b9318813b0480 100644 --- a/client/cli/src/commands/run_cmd.rs +++ b/client/cli/src/commands/run_cmd.rs @@ -25,6 +25,7 @@ use crate::{ }, CliConfiguration, }; +use clap::Parser; use regex::Regex; use sc_service::{ config::{BasePath, PrometheusConfig, TransactionPoolOptions}, @@ -32,26 +33,25 @@ use sc_service::{ }; use sc_telemetry::TelemetryEndpoints; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use structopt::StructOpt; /// The `run` command used to run a node. -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Parser)] pub struct RunCmd { /// Enable validator mode. /// /// The node will be started with the authority role and actively /// participate in any consensus task that it can (e.g. depending on /// availability of local keys). - #[structopt(long)] + #[clap(long)] pub validator: bool, /// Disable GRANDPA voter when running in validator mode, otherwise disable the GRANDPA /// observer. - #[structopt(long)] + #[clap(long)] pub no_grandpa: bool, /// Experimental: Run in light client mode. - #[structopt(long = "light")] + #[clap(long)] pub light: bool, /// Listen to all RPC interfaces. @@ -60,13 +60,13 @@ pub struct RunCmd { /// proxy server to filter out dangerous methods. More details: /// . /// Use `--unsafe-rpc-external` to suppress the warning if you understand the risks. - #[structopt(long = "rpc-external")] + #[clap(long)] pub rpc_external: bool, /// Listen to all RPC interfaces. /// /// Same as `--rpc-external`. - #[structopt(long)] + #[clap(long)] pub unsafe_rpc_external: bool, /// RPC methods to expose. @@ -75,11 +75,11 @@ pub struct RunCmd { /// - `Safe`: Exposes only a safe subset of RPC methods, denying unsafe RPC methods. /// - `Auto`: Acts as `Safe` if RPC is served externally, e.g. when `--{rpc,ws}-external` is /// passed, otherwise acts as `Unsafe`. - #[structopt( + #[clap( long, value_name = "METHOD SET", - possible_values = &RpcMethods::variants(), - case_insensitive = true, + arg_enum, + ignore_case = true, default_value = "Auto", verbatim_doc_comment )] @@ -91,44 +91,44 @@ pub struct RunCmd { /// proxy server to filter out dangerous methods. More details: /// . /// Use `--unsafe-ws-external` to suppress the warning if you understand the risks. - #[structopt(long = "ws-external")] + #[clap(long)] pub ws_external: bool, /// Listen to all Websocket interfaces. /// /// Same as `--ws-external` but doesn't warn you about it. - #[structopt(long = "unsafe-ws-external")] + #[clap(long)] pub unsafe_ws_external: bool, /// Set the the maximum RPC payload size for both requests and responses (both http and ws), in /// megabytes. Default is 15MiB. - #[structopt(long = "rpc-max-payload")] + #[clap(long)] pub rpc_max_payload: Option, /// Expose Prometheus exporter on all interfaces. /// /// Default is local. - #[structopt(long = "prometheus-external")] + #[clap(long)] pub prometheus_external: bool, /// Specify IPC RPC server path - #[structopt(long = "ipc-path", value_name = "PATH")] + #[clap(long, value_name = "PATH")] pub ipc_path: Option, /// Specify HTTP RPC server TCP port. - #[structopt(long = "rpc-port", value_name = "PORT")] + #[clap(long, value_name = "PORT")] pub rpc_port: Option, /// Specify WebSockets RPC server TCP port. - #[structopt(long = "ws-port", value_name = "PORT")] + #[clap(long, value_name = "PORT")] pub ws_port: Option, /// Maximum number of WS RPC server connections. - #[structopt(long = "ws-max-connections", value_name = "COUNT")] + #[clap(long, value_name = "COUNT")] pub ws_max_connections: Option, /// Set the the maximum WebSocket output buffer size in MiB. Default is 16. - #[structopt(long = "ws-max-out-buffer-capacity")] + #[clap(long)] pub ws_max_out_buffer_capacity: Option, /// Specify browser Origins allowed to access the HTTP & WS RPC servers. @@ -137,29 +137,29 @@ pub struct RunCmd { /// value). Value of `all` will disable origin validation. Default is to /// allow localhost and origins. When running in /// --dev mode the default is to allow all origins. - #[structopt(long = "rpc-cors", value_name = "ORIGINS", parse(try_from_str = parse_cors))] + #[clap(long, value_name = "ORIGINS", parse(from_str = parse_cors))] pub rpc_cors: Option, /// Specify Prometheus exporter TCP Port. - #[structopt(long = "prometheus-port", value_name = "PORT")] + #[clap(long, value_name = "PORT")] pub prometheus_port: Option, /// Do not expose a Prometheus exporter endpoint. /// /// Prometheus metric endpoint is enabled by default. - #[structopt(long = "no-prometheus")] + #[clap(long)] pub no_prometheus: bool, /// The human-readable name for this node. /// /// The node name will be reported to the telemetry server, if enabled. - #[structopt(long = "name", value_name = "NAME")] + #[clap(long, value_name = "NAME")] pub name: Option, /// Disable connecting to the Substrate telemetry server. /// /// Telemetry is on by default on global chains. - #[structopt(long = "no-telemetry")] + #[clap(long)] pub no_telemetry: bool, /// The URL of the telemetry server to connect to. @@ -168,78 +168,78 @@ pub struct RunCmd { /// telemetry endpoints. Verbosity levels range from 0-9, with 0 denoting /// the least verbosity. /// Expected format is 'URL VERBOSITY', e.g. `--telemetry-url 'wss://foo/bar 0'`. - #[structopt(long = "telemetry-url", value_name = "URL VERBOSITY", parse(try_from_str = parse_telemetry_endpoints))] + #[clap(long = "telemetry-url", value_name = "URL VERBOSITY", parse(try_from_str = parse_telemetry_endpoints))] pub telemetry_endpoints: Vec<(String, u8)>, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub offchain_worker_params: OffchainWorkerParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub shared_params: SharedParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub import_params: ImportParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub network_params: NetworkParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub pool_config: TransactionPoolParams, /// Shortcut for `--name Alice --validator` with session keys for `Alice` added to keystore. - #[structopt(long, conflicts_with_all = &["bob", "charlie", "dave", "eve", "ferdie", "one", "two"])] + #[clap(long, conflicts_with_all = &["bob", "charlie", "dave", "eve", "ferdie", "one", "two"])] pub alice: bool, /// Shortcut for `--name Bob --validator` with session keys for `Bob` added to keystore. - #[structopt(long, conflicts_with_all = &["alice", "charlie", "dave", "eve", "ferdie", "one", "two"])] + #[clap(long, conflicts_with_all = &["alice", "charlie", "dave", "eve", "ferdie", "one", "two"])] pub bob: bool, /// Shortcut for `--name Charlie --validator` with session keys for `Charlie` added to /// keystore. - #[structopt(long, conflicts_with_all = &["alice", "bob", "dave", "eve", "ferdie", "one", "two"])] + #[clap(long, conflicts_with_all = &["alice", "bob", "dave", "eve", "ferdie", "one", "two"])] pub charlie: bool, /// Shortcut for `--name Dave --validator` with session keys for `Dave` added to keystore. - #[structopt(long, conflicts_with_all = &["alice", "bob", "charlie", "eve", "ferdie", "one", "two"])] + #[clap(long, conflicts_with_all = &["alice", "bob", "charlie", "eve", "ferdie", "one", "two"])] pub dave: bool, /// Shortcut for `--name Eve --validator` with session keys for `Eve` added to keystore. - #[structopt(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "ferdie", "one", "two"])] + #[clap(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "ferdie", "one", "two"])] pub eve: bool, /// Shortcut for `--name Ferdie --validator` with session keys for `Ferdie` added to keystore. - #[structopt(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "one", "two"])] + #[clap(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "one", "two"])] pub ferdie: bool, /// Shortcut for `--name One --validator` with session keys for `One` added to keystore. - #[structopt(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "ferdie", "two"])] + #[clap(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "ferdie", "two"])] pub one: bool, /// Shortcut for `--name Two --validator` with session keys for `Two` added to keystore. - #[structopt(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "ferdie", "one"])] + #[clap(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "ferdie", "one"])] pub two: bool, /// Enable authoring even when offline. - #[structopt(long = "force-authoring")] + #[clap(long)] pub force_authoring: bool, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub keystore_params: KeystoreParams, /// The size of the instances cache for each runtime. /// /// The default value is 8 and the values higher than 256 are ignored. - #[structopt(long)] + #[clap(long)] pub max_runtime_instances: Option, /// Maximum number of different runtimes that can be cached. - #[structopt(long, default_value = "2")] + #[clap(long, default_value = "2")] pub runtime_cache_size: u8, /// Run a temporary node. @@ -251,7 +251,7 @@ pub struct RunCmd { /// which includes: database, node key and keystore. /// /// When `--dev` is given and no explicit `--base-path`, this option is implied. - #[structopt(long, conflicts_with = "base-path")] + #[clap(long, conflicts_with = "base-path")] pub tmp: bool, } @@ -562,8 +562,7 @@ fn parse_telemetry_endpoints(s: &str) -> std::result::Result<(String, u8), Telem /// CORS setting /// -/// The type is introduced to overcome `Option>` -/// handling of `structopt`. +/// The type is introduced to overcome `Option>` handling of `clap`. #[derive(Clone, Debug)] pub enum Cors { /// All hosts allowed. @@ -582,7 +581,7 @@ impl From for Option> { } /// Parse cors origins. -fn parse_cors(s: &str) -> std::result::Result> { +fn parse_cors(s: &str) -> Cors { let mut is_all = false; let mut origins = Vec::new(); for part in s.split(',') { @@ -595,7 +594,11 @@ fn parse_cors(s: &str) -> std::result::Result> } } - Ok(if is_all { Cors::All } else { Cors::List(origins) }) + if is_all { + Cors::All + } else { + Cors::List(origins) + } } #[cfg(test)] diff --git a/client/cli/src/commands/sign.rs b/client/cli/src/commands/sign.rs index 8d331d7994595..e0a5fce353ef4 100644 --- a/client/cli/src/commands/sign.rs +++ b/client/cli/src/commands/sign.rs @@ -18,34 +18,34 @@ //! Implementation of the `sign` subcommand use crate::{error, utils, with_crypto_scheme, CryptoSchemeFlag, KeystoreParams}; +use clap::Parser; use sp_core::crypto::SecretString; -use structopt::StructOpt; /// The `sign` command -#[derive(Debug, StructOpt, Clone)] -#[structopt(name = "sign", about = "Sign a message, with a given (secret) key")] +#[derive(Debug, Clone, Parser)] +#[clap(name = "sign", about = "Sign a message, with a given (secret) key")] pub struct SignCmd { /// The secret key URI. /// If the value is a file, the file content is used as URI. /// If not given, you will be prompted for the URI. - #[structopt(long)] + #[clap(long)] suri: Option, /// Message to sign, if not provided you will be prompted to /// pass the message via STDIN - #[structopt(long)] + #[clap(long)] message: Option, /// The message on STDIN is hex-encoded data - #[structopt(long)] + #[clap(long)] hex: bool, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub keystore_params: KeystoreParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub crypto_scheme: CryptoSchemeFlag, } @@ -75,14 +75,13 @@ fn sign( #[cfg(test)] mod test { - use super::SignCmd; - use structopt::StructOpt; + use super::*; #[test] fn sign() { let seed = "0xad1fb77243b536b90cfe5f0d351ab1b1ac40e3890b41dc64f766ee56340cfca5"; - let sign = SignCmd::from_iter(&[ + let sign = SignCmd::parse_from(&[ "sign", "--suri", seed, diff --git a/client/cli/src/commands/vanity.rs b/client/cli/src/commands/vanity.rs index f2959a33dbfdf..834b220df6388 100644 --- a/client/cli/src/commands/vanity.rs +++ b/client/cli/src/commands/vanity.rs @@ -21,30 +21,30 @@ use crate::{ error, utils, with_crypto_scheme, CryptoSchemeFlag, NetworkSchemeFlag, OutputTypeFlag, }; +use clap::Parser; use rand::{rngs::OsRng, RngCore}; use sp_core::crypto::{unwrap_or_default_ss58_version, Ss58AddressFormat, Ss58Codec}; use sp_runtime::traits::IdentifyAccount; -use structopt::StructOpt; use utils::print_from_uri; /// The `vanity` command -#[derive(Debug, StructOpt, Clone)] -#[structopt(name = "vanity", about = "Generate a seed that provides a vanity address")] +#[derive(Debug, Clone, Parser)] +#[clap(name = "vanity", about = "Generate a seed that provides a vanity address")] pub struct VanityCmd { /// Desired pattern - #[structopt(long, parse(try_from_str = assert_non_empty_string))] + #[clap(long, parse(try_from_str = assert_non_empty_string))] pattern: String, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] network_scheme: NetworkSchemeFlag, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] output_scheme: OutputTypeFlag, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] crypto_scheme: CryptoSchemeFlag, } @@ -166,13 +166,12 @@ mod tests { crypto::{default_ss58_version, Ss58AddressFormatRegistry, Ss58Codec}, sr25519, Pair, }; - use structopt::StructOpt; #[cfg(feature = "bench")] use test::Bencher; #[test] fn vanity() { - let vanity = VanityCmd::from_iter(&["vanity", "--pattern", "j"]); + let vanity = VanityCmd::parse_from(&["vanity", "--pattern", "j"]); assert!(vanity.run().is_ok()); } diff --git a/client/cli/src/commands/verify.rs b/client/cli/src/commands/verify.rs index 9ffd5d9d4844e..a8879f42caafc 100644 --- a/client/cli/src/commands/verify.rs +++ b/client/cli/src/commands/verify.rs @@ -19,12 +19,12 @@ //! implementation of the `verify` subcommand use crate::{error, utils, with_crypto_scheme, CryptoSchemeFlag}; +use clap::Parser; use sp_core::crypto::{ByteArray, Ss58Codec}; -use structopt::StructOpt; /// The `verify` command -#[derive(Debug, StructOpt, Clone)] -#[structopt( +#[derive(Debug, Clone, Parser)] +#[clap( name = "verify", about = "Verify a signature for a message, provided on STDIN, with a given (public or secret) key" )] @@ -39,15 +39,15 @@ pub struct VerifyCmd { /// Message to verify, if not provided you will be prompted to /// pass the message via STDIN - #[structopt(long)] + #[clap(long)] message: Option, /// The message on STDIN is hex-encoded data - #[structopt(long)] + #[clap(long)] hex: bool, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub crypto_scheme: CryptoSchemeFlag, } diff --git a/client/cli/src/error.rs b/client/cli/src/error.rs index 7f3bd84148d12..69b2eeaaf6186 100644 --- a/client/cli/src/error.rs +++ b/client/cli/src/error.rs @@ -31,7 +31,7 @@ pub enum Error { Io(#[from] std::io::Error), #[error(transparent)] - Cli(#[from] structopt::clap::Error), + Cli(#[from] clap::Error), #[error(transparent)] Service(#[from] sc_service::Error), diff --git a/client/cli/src/lib.rs b/client/cli/src/lib.rs index 8760e955c69ba..c242050dbf32a 100644 --- a/client/cli/src/lib.rs +++ b/client/cli/src/lib.rs @@ -30,6 +30,8 @@ mod params; mod runner; pub use arg_enums::*; +pub use clap; +use clap::{AppSettings, FromArgMatches, IntoApp, Parser}; pub use commands::*; pub use config::*; pub use error::*; @@ -39,12 +41,6 @@ use sc_service::Configuration; pub use sc_service::{ChainSpec, Role}; pub use sc_tracing::logging::LoggerBuilder; pub use sp_version::RuntimeVersion; -use std::io::Write; -pub use structopt; -use structopt::{ - clap::{self, AppSettings}, - StructOpt, -}; /// Substrate client CLI /// @@ -103,7 +99,7 @@ pub trait SubstrateCli: Sized { /// error message and quit the program in case of failure. fn from_args() -> Self where - Self: StructOpt + Sized, + Self: Parser + Sized, { ::from_iter(&mut std::env::args_os()) } @@ -120,11 +116,11 @@ pub trait SubstrateCli: Sized { /// Print the error message and quit the program in case of failure. fn from_iter(iter: I) -> Self where - Self: StructOpt + Sized, + Self: Parser + Sized, I: IntoIterator, I::Item: Into + Clone, { - let app = ::clap(); + let app = ::into_app(); let mut full_version = Self::impl_version(); full_version.push_str("\n"); @@ -137,34 +133,15 @@ pub trait SubstrateCli: Sized { .author(author.as_str()) .about(about.as_str()) .version(full_version.as_str()) - .settings(&[ - AppSettings::GlobalVersion, - AppSettings::ArgsNegateSubcommands, - AppSettings::SubcommandsNegateReqs, - AppSettings::ColoredHelp, - ]); - - let matches = match app.get_matches_from_safe(iter) { - Ok(matches) => matches, - Err(mut e) => { - // To support pipes, we can not use `writeln!` as any error - // results in a "broken pipe" error. - // - // Instead we write directly to `stdout` and ignore any error - // as we exit afterwards anyway. - e.message.extend("\n".chars()); - - if e.use_stderr() { - let _ = std::io::stderr().write_all(e.message.as_bytes()); - std::process::exit(1); - } else { - let _ = std::io::stdout().write_all(e.message.as_bytes()); - std::process::exit(0); - } - }, - }; - - ::from_clap(&matches) + .setting( + AppSettings::PropagateVersion | + AppSettings::ArgsNegateSubcommands | + AppSettings::SubcommandsNegateReqs, + ); + + let matches = app.try_get_matches_from(iter).unwrap_or_else(|e| e.exit()); + + ::from_arg_matches(&matches).unwrap_or_else(|e| e.exit()) } /// Helper function used to parse the command line arguments. This is the equivalent of @@ -180,15 +157,15 @@ pub trait SubstrateCli: Sized { /// /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are /// used. It will return a [`clap::Error`], where the [`clap::Error::kind`] is a - /// [`clap::ErrorKind::HelpDisplayed`] or [`clap::ErrorKind::VersionDisplayed`] respectively. + /// [`clap::ErrorKind::DisplayHelp`] or [`clap::ErrorKind::DisplayVersion`] respectively. /// You must call [`clap::Error::exit`] or perform a [`std::process::exit`]. fn try_from_iter(iter: I) -> clap::Result where - Self: StructOpt + Sized, + Self: Parser + Sized, I: IntoIterator, I::Item: Into + Clone, { - let app = ::clap(); + let app = ::into_app(); let mut full_version = Self::impl_version(); full_version.push_str("\n"); @@ -202,9 +179,9 @@ pub trait SubstrateCli: Sized { .about(about.as_str()) .version(full_version.as_str()); - let matches = app.get_matches_from_safe(iter)?; + let matches = app.try_get_matches_from(iter)?; - Ok(::from_clap(&matches)) + ::from_arg_matches(&matches) } /// Returns the client ID: `{impl_name}/v{impl_version}` diff --git a/client/cli/src/params/database_params.rs b/client/cli/src/params/database_params.rs index f034ae00473ca..dd11c21f432b1 100644 --- a/client/cli/src/params/database_params.rs +++ b/client/cli/src/params/database_params.rs @@ -17,24 +17,24 @@ // along with this program. If not, see . use crate::arg_enums::Database; +use clap::Args; use sc_service::TransactionStorageMode; -use structopt::StructOpt; /// Parameters for block import. -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Args)] pub struct DatabaseParams { /// Select database backend to use. - #[structopt( + #[clap( long, alias = "db", value_name = "DB", - case_insensitive = true, - possible_values = &Database::variants(), + ignore_case = true, + possible_values = Database::variants(), )] pub database: Option, /// Limit the memory the database cache can use. - #[structopt(long = "db-cache", value_name = "MiB")] + #[clap(long = "db-cache", value_name = "MiB")] pub database_cache_size: Option, /// Enable storage chain mode @@ -43,7 +43,7 @@ pub struct DatabaseParams { /// If this is enabled, each transaction is stored separately in the /// transaction database column and is only referenced by hash /// in the block body column. - #[structopt(long)] + #[clap(long)] pub storage_chain: bool, } diff --git a/client/cli/src/params/import_params.rs b/client/cli/src/params/import_params.rs index 7e1478d71e3fc..1ec79800136d3 100644 --- a/client/cli/src/params/import_params.rs +++ b/client/cli/src/params/import_params.rs @@ -24,9 +24,9 @@ use crate::{ }, params::{DatabaseParams, PruningParams}, }; +use clap::Args; use sc_client_api::execution_extensions::ExecutionStrategies; use std::path::PathBuf; -use structopt::StructOpt; #[cfg(feature = "wasmtime")] const WASM_METHOD_DEFAULT: &str = "Compiled"; @@ -35,14 +35,14 @@ const WASM_METHOD_DEFAULT: &str = "Compiled"; const WASM_METHOD_DEFAULT: &str = "interpreted-i-know-what-i-do"; /// Parameters for block import. -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Args)] pub struct ImportParams { #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub pruning_params: PruningParams, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub database_params: DatabaseParams, /// Force start with unsafe pruning settings. @@ -50,15 +50,15 @@ pub struct ImportParams { /// When running as a validator it is highly recommended to disable state /// pruning (i.e. 'archive') which is the default. The node will refuse to /// start as a validator if pruning is enabled unless this option is set. - #[structopt(long = "unsafe-pruning")] + #[clap(long)] pub unsafe_pruning: bool, /// Method for executing Wasm runtime code. - #[structopt( + #[clap( long = "wasm-execution", value_name = "METHOD", - possible_values = &WasmExecutionMethod::variants(), - case_insensitive = true, + possible_values = WasmExecutionMethod::variants(), + ignore_case = true, default_value = WASM_METHOD_DEFAULT )] pub wasm_method: WasmExecutionMethod, @@ -66,15 +66,15 @@ pub struct ImportParams { /// Specify the path where local WASM runtimes are stored. /// /// These runtimes will override on-chain runtimes when the version matches. - #[structopt(long, value_name = "PATH", parse(from_os_str))] + #[clap(long, value_name = "PATH", parse(from_os_str))] pub wasm_runtime_overrides: Option, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub execution_strategies: ExecutionStrategiesParams, /// Specify the state cache size. - #[structopt(long = "state-cache-size", value_name = "Bytes", default_value = "67108864")] + #[clap(long, value_name = "Bytes", default_value = "67108864")] pub state_cache_size: usize, } @@ -127,62 +127,37 @@ impl ImportParams { } /// Execution strategies parameters. -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Args)] pub struct ExecutionStrategiesParams { /// The means of execution used when calling into the runtime for importing blocks as /// part of an initial sync. - #[structopt( - long = "execution-syncing", - value_name = "STRATEGY", - possible_values = &ExecutionStrategy::variants(), - case_insensitive = true, - )] + #[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)] pub execution_syncing: Option, /// The means of execution used when calling into the runtime for general block import /// (including locally authored blocks). - #[structopt( - long = "execution-import-block", - value_name = "STRATEGY", - possible_values = &ExecutionStrategy::variants(), - case_insensitive = true, - )] + #[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)] pub execution_import_block: Option, /// The means of execution used when calling into the runtime while constructing blocks. - #[structopt( - long = "execution-block-construction", - value_name = "STRATEGY", - possible_values = &ExecutionStrategy::variants(), - case_insensitive = true, - )] + #[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)] pub execution_block_construction: Option, /// The means of execution used when calling into the runtime while using an off-chain worker. - #[structopt( - long = "execution-offchain-worker", - value_name = "STRATEGY", - possible_values = &ExecutionStrategy::variants(), - case_insensitive = true, - )] + #[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)] pub execution_offchain_worker: Option, /// The means of execution used when calling into the runtime while not syncing, importing or /// constructing blocks. - #[structopt( - long = "execution-other", - value_name = "STRATEGY", - possible_values = &ExecutionStrategy::variants(), - case_insensitive = true, - )] + #[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)] pub execution_other: Option, /// The execution strategy that should be used by all execution contexts. - #[structopt( - long = "execution", + #[clap( + long, value_name = "STRATEGY", - possible_values = &ExecutionStrategy::variants(), - case_insensitive = true, + arg_enum, + ignore_case = true, conflicts_with_all = &[ "execution-other", "execution-offchain-worker", diff --git a/client/cli/src/params/keystore_params.rs b/client/cli/src/params/keystore_params.rs index 5dbab5d9e8e34..72b09134f57a4 100644 --- a/client/cli/src/params/keystore_params.rs +++ b/client/cli/src/params/keystore_params.rs @@ -17,50 +17,47 @@ // along with this program. If not, see . use crate::{error, error::Result}; +use clap::Args; use sc_service::config::KeystoreConfig; use sp_core::crypto::SecretString; use std::{ fs, path::{Path, PathBuf}, }; -use structopt::StructOpt; /// default sub directory for the key store const DEFAULT_KEYSTORE_CONFIG_PATH: &'static str = "keystore"; /// Parameters of the keystore -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Args)] pub struct KeystoreParams { /// Specify custom URIs to connect to for keystore-services - #[structopt(long = "keystore-uri")] + #[clap(long)] pub keystore_uri: Option, /// Specify custom keystore path. - #[structopt(long = "keystore-path", value_name = "PATH", parse(from_os_str))] + #[clap(long, value_name = "PATH", parse(from_os_str))] pub keystore_path: Option, /// Use interactive shell for entering the password used by the keystore. - #[structopt( - long = "password-interactive", - conflicts_with_all = &[ "password", "password-filename" ] - )] + #[clap(long, conflicts_with_all = &["password", "password-filename"])] pub password_interactive: bool, /// Password used by the keystore. This allows appending an extra user-defined secret to the /// seed. - #[structopt( - long = "password", + #[clap( + long, parse(try_from_str = secret_string_from_str), - conflicts_with_all = &[ "password-interactive", "password-filename" ] + conflicts_with_all = &["password-interactive", "password-filename"] )] pub password: Option, /// File that contains the password used by the keystore. - #[structopt( - long = "password-filename", + #[clap( + long, value_name = "PATH", parse(from_os_str), - conflicts_with_all = &[ "password-interactive", "password" ] + conflicts_with_all = &["password-interactive", "password"] )] pub password_filename: Option, } diff --git a/client/cli/src/params/mod.rs b/client/cli/src/params/mod.rs index e6f81079263de..e0571aa4bbbf8 100644 --- a/client/cli/src/params/mod.rs +++ b/client/cli/src/params/mod.rs @@ -26,13 +26,13 @@ mod shared_params; mod transaction_pool_params; use crate::arg_enums::{CryptoScheme, OutputType}; +use clap::Args; use sp_core::crypto::Ss58AddressFormat; use sp_runtime::{ generic::BlockId, traits::{Block as BlockT, NumberFor}, }; use std::{convert::TryFrom, fmt::Debug, str::FromStr}; -use structopt::StructOpt; pub use crate::params::{ database_params::*, import_params::*, keystore_params::*, network_params::*, @@ -115,44 +115,32 @@ impl BlockNumberOrHash { } /// Optional flag for specifying crypto algorithm -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Args)] pub struct CryptoSchemeFlag { /// cryptography scheme - #[structopt( - long, - value_name = "SCHEME", - possible_values = &CryptoScheme::variants(), - case_insensitive = true, - default_value = "Sr25519" - )] + #[clap(long, value_name = "SCHEME", arg_enum, ignore_case = true, default_value = "Sr25519")] pub scheme: CryptoScheme, } /// Optional flag for specifying output type -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Args)] pub struct OutputTypeFlag { /// output format - #[structopt( - long, - value_name = "FORMAT", - possible_values = &OutputType::variants(), - case_insensitive = true, - default_value = "Text" - )] + #[clap(long, value_name = "FORMAT", arg_enum, ignore_case = true, default_value = "Text")] pub output_type: OutputType, } /// Optional flag for specifying network scheme -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Args)] pub struct NetworkSchemeFlag { /// network address format - #[structopt( + #[clap( + short = 'n', long, value_name = "NETWORK", - short = "n", possible_values = &Ss58AddressFormat::all_names()[..], + ignore_case = true, parse(try_from_str = Ss58AddressFormat::try_from), - case_insensitive = true, )] pub network: Option, } diff --git a/client/cli/src/params/network_params.rs b/client/cli/src/params/network_params.rs index 86060486144ac..1de2896cba731 100644 --- a/client/cli/src/params/network_params.rs +++ b/client/cli/src/params/network_params.rs @@ -17,6 +17,7 @@ // along with this program. If not, see . use crate::{arg_enums::SyncMode, params::node_key_params::NodeKeyParams}; +use clap::Args; use sc_network::{ config::{ NetworkConfiguration, NodeKeyConfig, NonReservedPeerMode, SetConfig, TransportConfig, @@ -28,17 +29,16 @@ use sc_service::{ ChainSpec, ChainType, }; use std::{borrow::Cow, path::PathBuf}; -use structopt::StructOpt; /// Parameters used to create the network configuration. -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Args)] pub struct NetworkParams { /// Specify a list of bootnodes. - #[structopt(long = "bootnodes", value_name = "ADDR")] + #[clap(long, value_name = "ADDR")] pub bootnodes: Vec, /// Specify a list of reserved node addresses. - #[structopt(long = "reserved-nodes", value_name = "ADDR")] + #[clap(long, value_name = "ADDR")] pub reserved_nodes: Vec, /// Whether to only synchronize the chain with reserved nodes. @@ -49,12 +49,12 @@ pub struct NetworkParams { /// In particular, if you are a validator your node might still connect to other /// validator nodes and collator nodes regardless of whether they are defined as /// reserved nodes. - #[structopt(long = "reserved-only")] + #[clap(long)] pub reserved_only: bool, /// The public address that other nodes will use to connect to it. /// This can be used if there's a proxy in front of this node. - #[structopt(long, value_name = "PUBLIC_ADDR")] + #[clap(long, value_name = "PUBLIC_ADDR")] pub public_addr: Vec, /// Listen on this multiaddress. @@ -62,60 +62,60 @@ pub struct NetworkParams { /// By default: /// If `--validator` is passed: `/ip4/0.0.0.0/tcp/` and `/ip6/[::]/tcp/`. /// Otherwise: `/ip4/0.0.0.0/tcp//ws` and `/ip6/[::]/tcp//ws`. - #[structopt(long = "listen-addr", value_name = "LISTEN_ADDR")] + #[clap(long, value_name = "LISTEN_ADDR")] pub listen_addr: Vec, /// Specify p2p protocol TCP port. - #[structopt(long = "port", value_name = "PORT", conflicts_with_all = &[ "listen-addr" ])] + #[clap(long, value_name = "PORT", conflicts_with_all = &[ "listen-addr" ])] pub port: Option, /// Always forbid connecting to private IPv4 addresses (as specified in /// [RFC1918](https://tools.ietf.org/html/rfc1918)), unless the address was passed with /// `--reserved-nodes` or `--bootnodes`. Enabled by default for chains marked as "live" in /// their chain specifications. - #[structopt(long = "no-private-ipv4", conflicts_with_all = &["allow-private-ipv4"])] + #[clap(long, conflicts_with_all = &["allow-private-ipv4"])] pub no_private_ipv4: bool, /// Always accept connecting to private IPv4 addresses (as specified in /// [RFC1918](https://tools.ietf.org/html/rfc1918)). Enabled by default for chains marked as /// "local" in their chain specifications, or when `--dev` is passed. - #[structopt(long = "allow-private-ipv4", conflicts_with_all = &["no-private-ipv4"])] + #[clap(long, conflicts_with_all = &["no-private-ipv4"])] pub allow_private_ipv4: bool, /// Specify the number of outgoing connections we're trying to maintain. - #[structopt(long = "out-peers", value_name = "COUNT", default_value = "25")] + #[clap(long, value_name = "COUNT", default_value = "25")] pub out_peers: u32, /// Maximum number of inbound full nodes peers. - #[structopt(long = "in-peers", value_name = "COUNT", default_value = "25")] + #[clap(long, value_name = "COUNT", default_value = "25")] pub in_peers: u32, /// Maximum number of inbound light nodes peers. - #[structopt(long = "in-peers-light", value_name = "COUNT", default_value = "100")] + #[clap(long, value_name = "COUNT", default_value = "100")] pub in_peers_light: u32, /// Disable mDNS discovery. /// /// By default, the network will use mDNS to discover other nodes on the /// local network. This disables it. Automatically implied when using --dev. - #[structopt(long = "no-mdns")] + #[clap(long)] pub no_mdns: bool, /// Maximum number of peers from which to ask for the same blocks in parallel. /// /// This allows downloading announced blocks from multiple peers. Decrease to save /// traffic and risk increased latency. - #[structopt(long = "max-parallel-downloads", value_name = "COUNT", default_value = "5")] + #[clap(long, value_name = "COUNT", default_value = "5")] pub max_parallel_downloads: u32, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub node_key_params: NodeKeyParams, /// Enable peer discovery on local networks. /// /// By default this option is `true` for `--dev` or when the chain type is /// `Local`/`Development` and false otherwise. - #[structopt(long)] + #[clap(long)] pub discover_local: bool, /// Require iterative Kademlia DHT queries to use disjoint paths for increased resiliency in @@ -123,11 +123,11 @@ pub struct NetworkParams { /// /// See the S/Kademlia paper for more information on the high level design as well as its /// security improvements. - #[structopt(long)] + #[clap(long)] pub kademlia_disjoint_query_paths: bool, /// Join the IPFS network and serve transactions over bitswap protocol. - #[structopt(long)] + #[clap(long)] pub ipfs_server: bool, /// Blockchain syncing mode. @@ -137,7 +137,7 @@ pub struct NetworkParams { /// - `Fast`: Download blocks and the latest state only. /// /// - `FastUnsafe`: Same as `Fast`, but skip downloading state proofs. - #[structopt(long, value_name = "SYNC_MODE", default_value = "Full")] + #[clap(long, arg_enum, value_name = "SYNC_MODE", default_value = "Full")] pub sync: SyncMode, } diff --git a/client/cli/src/params/node_key_params.rs b/client/cli/src/params/node_key_params.rs index 23f3fba1cdb04..f31fd854cbb56 100644 --- a/client/cli/src/params/node_key_params.rs +++ b/client/cli/src/params/node_key_params.rs @@ -16,10 +16,10 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use clap::Args; use sc_network::config::{identity::ed25519, NodeKeyConfig}; use sp_core::H256; use std::{path::PathBuf, str::FromStr}; -use structopt::StructOpt; use crate::{arg_enums::NodeKeyType, error}; @@ -30,7 +30,7 @@ const NODE_KEY_ED25519_FILE: &str = "secret_ed25519"; /// Parameters used to create the `NodeKeyConfig`, which determines the keypair /// used for libp2p networking. -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Args)] pub struct NodeKeyParams { /// The secret key to use for libp2p networking. /// @@ -46,7 +46,7 @@ pub struct NodeKeyParams { /// WARNING: Secrets provided as command-line arguments are easily exposed. /// Use of this option should be limited to development and testing. To use /// an externally managed secret key, use `--node-key-file` instead. - #[structopt(long = "node-key", value_name = "KEY")] + #[clap(long, value_name = "KEY")] pub node_key: Option, /// The type of secret key to use for libp2p networking. @@ -66,13 +66,7 @@ pub struct NodeKeyParams { /// /// The node's secret key determines the corresponding public key and hence the /// node's peer ID in the context of libp2p. - #[structopt( - long = "node-key-type", - value_name = "TYPE", - possible_values = &NodeKeyType::variants(), - case_insensitive = true, - default_value = "Ed25519" - )] + #[clap(long, value_name = "TYPE", arg_enum, ignore_case = true, default_value = "Ed25519")] pub node_key_type: NodeKeyType, /// The file from which to read the node's secret key to use for libp2p networking. @@ -85,7 +79,7 @@ pub struct NodeKeyParams { /// /// If the file does not exist, it is created with a newly generated secret key of /// the chosen type. - #[structopt(long = "node-key-file", value_name = "FILE")] + #[clap(long, value_name = "FILE")] pub node_key_file: Option, } @@ -128,14 +122,15 @@ fn parse_ed25519_secret(hex: &str) -> error::Result error::Result<()> { - NodeKeyType::variants().iter().try_for_each(|t| { - let node_key_type = NodeKeyType::from_str(t).unwrap(); + NodeKeyType::value_variants().iter().try_for_each(|t| { + let node_key_type = *t; let sk = match node_key_type { NodeKeyType::Ed25519 => ed25519::SecretKey::generate().as_ref().to_vec(), }; @@ -194,8 +189,8 @@ mod tests { where F: Fn(NodeKeyParams) -> error::Result<()>, { - NodeKeyType::variants().iter().try_for_each(|t| { - let node_key_type = NodeKeyType::from_str(t).unwrap(); + NodeKeyType::value_variants().iter().try_for_each(|t| { + let node_key_type = *t; f(NodeKeyParams { node_key_type, node_key: None, node_key_file: None }) }) } diff --git a/client/cli/src/params/offchain_worker_params.rs b/client/cli/src/params/offchain_worker_params.rs index ac71d3a7580e7..3ab507f108598 100644 --- a/client/cli/src/params/offchain_worker_params.rs +++ b/client/cli/src/params/offchain_worker_params.rs @@ -23,23 +23,23 @@ //! targeted at handling input parameter parsing providing //! a reasonable abstraction. +use clap::Args; use sc_network::config::Role; use sc_service::config::OffchainWorkerConfig; -use structopt::StructOpt; use crate::{error, OffchainWorkerEnabled}; /// Offchain worker related parameters. -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Args)] pub struct OffchainWorkerParams { /// Should execute offchain workers on every block. /// /// By default it's only enabled for nodes that are authoring new blocks. - #[structopt( + #[clap( long = "offchain-worker", value_name = "ENABLED", - possible_values = &OffchainWorkerEnabled::variants(), - case_insensitive = true, + arg_enum, + ignore_case = true, default_value = "WhenValidating" )] pub enabled: OffchainWorkerEnabled, @@ -48,7 +48,7 @@ pub struct OffchainWorkerParams { /// /// Enables a runtime to write directly to a offchain workers /// DB during block import. - #[structopt(long = "enable-offchain-indexing", value_name = "ENABLE_OFFCHAIN_INDEXING")] + #[clap(long = "enable-offchain-indexing", value_name = "ENABLE_OFFCHAIN_INDEXING")] pub indexing_enabled: bool, } diff --git a/client/cli/src/params/pruning_params.rs b/client/cli/src/params/pruning_params.rs index facf982ef8dd5..a8516ee1453ac 100644 --- a/client/cli/src/params/pruning_params.rs +++ b/client/cli/src/params/pruning_params.rs @@ -17,23 +17,23 @@ // along with this program. If not, see . use crate::error; +use clap::Args; use sc_service::{KeepBlocks, PruningMode, Role}; -use structopt::StructOpt; /// Parameters to define the pruning mode -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Args)] pub struct PruningParams { /// Specify the state pruning mode, a number of blocks to keep or 'archive'. /// /// Default is to keep all block states if the node is running as a /// validator (i.e. 'archive'), otherwise state is only kept for the last /// 256 blocks. - #[structopt(long = "pruning", value_name = "PRUNING_MODE")] + #[clap(long, value_name = "PRUNING_MODE")] pub pruning: Option, /// Specify the number of finalized blocks to keep in the database. /// /// Default is to keep all blocks. - #[structopt(long, value_name = "COUNT")] + #[clap(long, value_name = "COUNT")] pub keep_blocks: Option, } diff --git a/client/cli/src/params/shared_params.rs b/client/cli/src/params/shared_params.rs index d385efad42784..a4f2271e12c48 100644 --- a/client/cli/src/params/shared_params.rs +++ b/client/cli/src/params/shared_params.rs @@ -17,36 +17,36 @@ // along with this program. If not, see . use crate::arg_enums::TracingReceiver; +use clap::Args; use sc_service::config::BasePath; use std::path::PathBuf; -use structopt::StructOpt; /// Shared parameters used by all `CoreParams`. -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Args)] pub struct SharedParams { /// Specify the chain specification. /// /// It can be one of the predefined ones (dev, local, or staging) or it can be a path to a file /// with the chainspec (such as one exported by the `build-spec` subcommand). - #[structopt(long, value_name = "CHAIN_SPEC")] + #[clap(long, value_name = "CHAIN_SPEC")] pub chain: Option, /// Specify the development chain. /// /// This flag sets `--chain=dev`, `--force-authoring`, `--rpc-cors=all`, /// `--alice`, and `--tmp` flags, unless explicitly overridden. - #[structopt(long, conflicts_with_all = &["chain"])] + #[clap(long, conflicts_with_all = &["chain"])] pub dev: bool, /// Specify custom base path. - #[structopt(long, short = "d", value_name = "PATH", parse(from_os_str))] + #[clap(long, short = 'd', value_name = "PATH", parse(from_os_str))] pub base_path: Option, /// Sets a custom logging filter. Syntax is =, e.g. -lsync=debug. /// /// Log levels (least to most verbose) are error, warn, info, debug, and trace. /// By default, all targets log `info`. The global log level can be set with -l. - #[structopt(short = "l", long, value_name = "LOG_PATTERN")] + #[clap(short = 'l', long, value_name = "LOG_PATTERN")] pub log: Vec, /// Enable detailed log output. @@ -54,11 +54,11 @@ pub struct SharedParams { /// This includes displaying the log target, log level and thread name. /// /// This is automatically enabled when something is logged with any higher level than `info`. - #[structopt(long)] + #[clap(long)] pub detailed_log_output: bool, /// Disable log color output. - #[structopt(long)] + #[clap(long)] pub disable_log_color: bool, /// Enable feature to dynamically update and reload the log filter. @@ -68,21 +68,15 @@ pub struct SharedParams { /// /// The `system_addLogFilter` and `system_resetLogFilter` RPCs will have no effect with this /// option not being set. - #[structopt(long)] + #[clap(long)] pub enable_log_reloading: bool, /// Sets a custom profiling filter. Syntax is the same as for logging: = - #[structopt(long = "tracing-targets", value_name = "TARGETS")] + #[clap(long, value_name = "TARGETS")] pub tracing_targets: Option, /// Receiver to process tracing messages. - #[structopt( - long = "tracing-receiver", - value_name = "RECEIVER", - possible_values = &TracingReceiver::variants(), - case_insensitive = true, - default_value = "Log" - )] + #[clap(long, value_name = "RECEIVER", arg_enum, ignore_case = true, default_value = "Log")] pub tracing_receiver: TracingReceiver, } diff --git a/client/cli/src/params/transaction_pool_params.rs b/client/cli/src/params/transaction_pool_params.rs index dee8f57eb39c8..efb78430ced55 100644 --- a/client/cli/src/params/transaction_pool_params.rs +++ b/client/cli/src/params/transaction_pool_params.rs @@ -16,18 +16,18 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use clap::Args; use sc_service::config::TransactionPoolOptions; -use structopt::StructOpt; /// Parameters used to create the pool configuration. -#[derive(Debug, StructOpt, Clone)] +#[derive(Debug, Clone, Args)] pub struct TransactionPoolParams { /// Maximum number of transactions in the transaction pool. - #[structopt(long = "pool-limit", value_name = "COUNT", default_value = "8192")] + #[clap(long, value_name = "COUNT", default_value = "8192")] pub pool_limit: usize, /// Maximum number of kilobytes of all transactions stored in the pool. - #[structopt(long = "pool-kbytes", value_name = "COUNT", default_value = "20480")] + #[clap(long, value_name = "COUNT", default_value = "20480")] pub pool_kbytes: usize, } diff --git a/client/consensus/aura/Cargo.toml b/client/consensus/aura/Cargo.toml index 97409c5944dbb..156842c35842e 100644 --- a/client/consensus/aura/Cargo.toml +++ b/client/consensus/aura/Cargo.toml @@ -13,7 +13,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-application-crypto = { version = "4.0.0", path = "../../../primitives/application-crypto" } +sp-application-crypto = { version = "5.0.0", path = "../../../primitives/application-crypto" } sp-consensus-aura = { version = "0.10.0-dev", path = "../../../primitives/consensus/aura" } sp-block-builder = { version = "4.0.0-dev", path = "../../../primitives/block-builder" } sc-block-builder = { version = "0.10.0-dev", path = "../../block-builder" } @@ -22,16 +22,16 @@ codec = { package = "parity-scale-codec", version = "2.0.0" } sp-consensus = { version = "0.10.0-dev", path = "../../../primitives/consensus/common" } sc-consensus = { version = "0.10.0-dev", path = "../../../client/consensus/common" } sp-consensus-slots = { version = "0.10.0-dev", path = "../../../primitives/consensus/slots" } -derive_more = "0.99.16" +thiserror = "1.0" futures = "0.3.9" sp-inherents = { version = "4.0.0-dev", path = "../../../primitives/inherents" } log = "0.4.8" -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } sc-consensus-slots = { version = "0.10.0-dev", path = "../slots" } sp-api = { version = "4.0.0-dev", path = "../../../primitives/api" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } -sp-keystore = { version = "0.10.0", path = "../../../primitives/keystore" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } +sp-keystore = { version = "0.11.0", path = "../../../primitives/keystore" } sc-telemetry = { version = "4.0.0-dev", path = "../../telemetry" } prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../utils/prometheus", version = "0.10.0-dev" } async-trait = "0.1.50" @@ -41,7 +41,7 @@ getrandom = { version = "0.2", features = ["js"], optional = true } [dev-dependencies] sp-timestamp = { version = "4.0.0-dev", path = "../../../primitives/timestamp" } -sp-keyring = { version = "4.1.0-dev", path = "../../../primitives/keyring" } +sp-keyring = { version = "5.0.0", path = "../../../primitives/keyring" } sp-tracing = { version = "4.0.0", path = "../../../primitives/tracing" } sc-keystore = { version = "4.0.0-dev", path = "../../keystore" } sc-network = { version = "0.10.0-dev", path = "../../network" } diff --git a/client/consensus/aura/src/import_queue.rs b/client/consensus/aura/src/import_queue.rs index 593ea193c3d12..56eb45c621a1b 100644 --- a/client/consensus/aura/src/import_queue.rs +++ b/client/consensus/aura/src/import_queue.rs @@ -205,7 +205,7 @@ where let hash = block.header.hash(); let parent_hash = *block.header.parent_hash(); let authorities = authorities(self.client.as_ref(), &BlockId::Hash(parent_hash)) - .map_err(|e| format!("Could not fetch authorities at {:?}: {:?}", parent_hash, e))?; + .map_err(|e| format!("Could not fetch authorities at {:?}: {}", parent_hash, e))?; let create_inherent_data_providers = self .create_inherent_data_providers @@ -249,7 +249,7 @@ where &BlockId::Hash(parent_hash), |v| v >= 2, ) - .map_err(|e| format!("{:?}", e))? + .map_err(|e| e.to_string())? { self.check_inherents( new_block.clone(), diff --git a/client/consensus/aura/src/lib.rs b/client/consensus/aura/src/lib.rs index d7fe613139382..61c5610883149 100644 --- a/client/consensus/aura/src/lib.rs +++ b/client/consensus/aura/src/lib.rs @@ -491,33 +491,34 @@ fn aura_err(error: Error) -> Error { } /// Aura Errors -#[derive(derive_more::Display, Debug)] +#[derive(Debug, thiserror::Error)] pub enum Error { /// Multiple Aura pre-runtime headers - #[display(fmt = "Multiple Aura pre-runtime headers")] + #[error("Multiple Aura pre-runtime headers")] MultipleHeaders, /// No Aura pre-runtime digest found - #[display(fmt = "No Aura pre-runtime digest found")] + #[error("No Aura pre-runtime digest found")] NoDigestFound, /// Header is unsealed - #[display(fmt = "Header {:?} is unsealed", _0)] + #[error("Header {0:?} is unsealed")] HeaderUnsealed(B::Hash), /// Header has a bad seal - #[display(fmt = "Header {:?} has a bad seal", _0)] + #[error("Header {0:?} has a bad seal")] HeaderBadSeal(B::Hash), /// Slot Author not found - #[display(fmt = "Slot Author not found")] + #[error("Slot Author not found")] SlotAuthorNotFound, /// Bad signature - #[display(fmt = "Bad signature on {:?}", _0)] + #[error("Bad signature on {0:?}")] BadSignature(B::Hash), /// Client Error + #[error(transparent)] Client(sp_blockchain::Error), /// Unknown inherent error for identifier - #[display(fmt = "Unknown inherent error for identifier: {}", "String::from_utf8_lossy(_0)")] + #[error("Unknown inherent error for identifier: {}", String::from_utf8_lossy(.0))] UnknownInherentError(sp_inherents::InherentIdentifier), - #[display(fmt = "Inherent error: {}", _0)] /// Inherents Error + #[error("Inherent error: {0}")] Inherent(sp_inherents::Error), } diff --git a/client/consensus/babe/Cargo.toml b/client/consensus/babe/Cargo.toml index e4d66fcad87cc..76ec6a25879f8 100644 --- a/client/consensus/babe/Cargo.toml +++ b/client/consensus/babe/Cargo.toml @@ -19,15 +19,15 @@ codec = { package = "parity-scale-codec", version = "2.0.0", features = [ ] } sp-consensus-babe = { version = "0.10.0-dev", path = "../../../primitives/consensus/babe" } sc-consensus = { version = "0.10.0-dev", path = "../../../client/consensus/common" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } -sp-application-crypto = { version = "4.0.0", path = "../../../primitives/application-crypto" } -sp-keystore = { version = "0.10.0", path = "../../../primitives/keystore" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } +sp-application-crypto = { version = "5.0.0", path = "../../../primitives/application-crypto" } +sp-keystore = { version = "0.11.0", path = "../../../primitives/keystore" } num-bigint = "0.2.3" num-rational = "0.2.2" num-traits = "0.2.8" -serde = { version = "1.0.132", features = ["derive"] } +serde = { version = "1.0.136", features = ["derive"] } sp-version = { version = "4.0.0-dev", path = "../../../primitives/version" } -sp-io = { version = "4.0.0", path = "../../../primitives/io" } +sp-io = { version = "5.0.0", path = "../../../primitives/io" } sp-inherents = { version = "4.0.0-dev", path = "../../../primitives/inherents" } sc-telemetry = { version = "4.0.0-dev", path = "../../telemetry" } sc-keystore = { version = "4.0.0-dev", path = "../../keystore" } @@ -40,7 +40,7 @@ sp-consensus = { version = "0.10.0-dev", path = "../../../primitives/consensus/c sp-consensus-slots = { version = "0.10.0-dev", path = "../../../primitives/consensus/slots" } sp-consensus-vrf = { version = "0.10.0-dev", path = "../../../primitives/consensus/vrf" } sc-consensus-slots = { version = "0.10.0-dev", path = "../slots" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } fork-tree = { version = "3.0.0", path = "../../../utils/fork-tree" } prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../utils/prometheus", version = "0.10.0-dev" } futures = "0.3.9" @@ -49,7 +49,7 @@ log = "0.4.8" schnorrkel = { version = "0.9.1", features = ["preaudit_deprecated"] } rand = "0.7.2" merlin = "2.0" -derive_more = "0.99.16" +thiserror = "1.0" retain_mut = "0.1.4" async-trait = "0.1.50" diff --git a/client/consensus/babe/rpc/Cargo.toml b/client/consensus/babe/rpc/Cargo.toml index 93be56b9d3601..8ceada5fe1f1d 100644 --- a/client/consensus/babe/rpc/Cargo.toml +++ b/client/consensus/babe/rpc/Cargo.toml @@ -19,22 +19,22 @@ jsonrpc-core = "18.0.0" jsonrpc-core-client = "18.0.0" jsonrpc-derive = "18.0.0" sp-consensus-babe = { version = "0.10.0-dev", path = "../../../../primitives/consensus/babe" } -serde = { version = "1.0.132", features=["derive"] } +serde = { version = "1.0.136", features = ["derive"] } sp-blockchain = { version = "4.0.0-dev", path = "../../../../primitives/blockchain" } -sp-runtime = { version = "4.1.0-dev", path = "../../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../../../primitives/runtime" } sc-consensus-epochs = { version = "0.10.0-dev", path = "../../epochs" } futures = "0.3.16" -derive_more = "0.99.16" +thiserror = "1.0" sp-api = { version = "4.0.0-dev", path = "../../../../primitives/api" } sp-consensus = { version = "0.10.0-dev", path = "../../../../primitives/consensus/common" } -sp-core = { version = "4.1.0-dev", path = "../../../../primitives/core" } -sp-application-crypto = { version = "4.0.0", path = "../../../../primitives/application-crypto" } -sp-keystore = { version = "0.10.0", path = "../../../../primitives/keystore" } +sp-core = { version = "5.0.0", path = "../../../../primitives/core" } +sp-application-crypto = { version = "5.0.0", path = "../../../../primitives/application-crypto" } +sp-keystore = { version = "0.11.0", path = "../../../../primitives/keystore" } [dev-dependencies] sc-consensus = { version = "0.10.0-dev", path = "../../../consensus/common" } serde_json = "1.0.74" -sp-keyring = { version = "4.1.0-dev", path = "../../../../primitives/keyring" } +sp-keyring = { version = "5.0.0", path = "../../../../primitives/keyring" } sc-keystore = { version = "4.0.0-dev", path = "../../../keystore" } substrate-test-runtime-client = { version = "2.0.0", path = "../../../../test-utils/runtime/client" } tempfile = "3.1.0" diff --git a/client/consensus/babe/rpc/src/lib.rs b/client/consensus/babe/rpc/src/lib.rs index c9d2f9b76c2a2..88a176e2de10d 100644 --- a/client/consensus/babe/rpc/src/lib.rs +++ b/client/consensus/babe/rpc/src/lib.rs @@ -104,7 +104,7 @@ where let epoch_start = client .runtime_api() .current_epoch_start(&BlockId::Hash(header.hash())) - .map_err(|err| Error::StringError(format!("{:?}", err)))?; + .map_err(|err| Error::StringError(err.to_string()))?; let epoch = epoch_data(&shared_epoch, &client, &babe_config, *epoch_start, &select_chain) .await?; @@ -166,11 +166,13 @@ pub struct EpochAuthorship { } /// Errors encountered by the RPC -#[derive(Debug, derive_more::Display, derive_more::From)] +#[derive(Debug, thiserror::Error)] pub enum Error { /// Consensus error - Consensus(ConsensusError), + #[error(transparent)] + Consensus(#[from] ConsensusError), /// Errors that can be formatted as a String + #[error("{0}")] StringError(String), } @@ -207,7 +209,7 @@ where slot.into(), |slot| Epoch::genesis(&babe_config, slot), ) - .map_err(|e| Error::Consensus(ConsensusError::ChainLookup(format!("{:?}", e))))? + .map_err(|e| Error::Consensus(ConsensusError::ChainLookup(e.to_string())))? .ok_or(Error::Consensus(ConsensusError::InvalidAuthoritiesSet)) } diff --git a/client/consensus/babe/src/lib.rs b/client/consensus/babe/src/lib.rs index a86eac35a1000..9ad50eb9c0e5c 100644 --- a/client/consensus/babe/src/lib.rs +++ b/client/consensus/babe/src/lib.rs @@ -217,95 +217,94 @@ impl Epoch { } /// Errors encountered by the babe authorship task. -#[derive(derive_more::Display, Debug)] +#[derive(Debug, thiserror::Error)] pub enum Error { /// Multiple BABE pre-runtime digests - #[display(fmt = "Multiple BABE pre-runtime digests, rejecting!")] + #[error("Multiple BABE pre-runtime digests, rejecting!")] MultiplePreRuntimeDigests, /// No BABE pre-runtime digest found - #[display(fmt = "No BABE pre-runtime digest found")] + #[error("No BABE pre-runtime digest found")] NoPreRuntimeDigest, /// Multiple BABE epoch change digests - #[display(fmt = "Multiple BABE epoch change digests, rejecting!")] + #[error("Multiple BABE epoch change digests, rejecting!")] MultipleEpochChangeDigests, /// Multiple BABE config change digests - #[display(fmt = "Multiple BABE config change digests, rejecting!")] + #[error("Multiple BABE config change digests, rejecting!")] MultipleConfigChangeDigests, /// Could not extract timestamp and slot - #[display(fmt = "Could not extract timestamp and slot: {:?}", _0)] + #[error("Could not extract timestamp and slot: {0}")] Extraction(sp_consensus::Error), /// Could not fetch epoch - #[display(fmt = "Could not fetch epoch at {:?}", _0)] + #[error("Could not fetch epoch at {0:?}")] FetchEpoch(B::Hash), /// Header rejected: too far in the future - #[display(fmt = "Header {:?} rejected: too far in the future", _0)] + #[error("Header {0:?} rejected: too far in the future")] TooFarInFuture(B::Hash), /// Parent unavailable. Cannot import - #[display(fmt = "Parent ({}) of {} unavailable. Cannot import", _0, _1)] + #[error("Parent ({0}) of {1} unavailable. Cannot import")] ParentUnavailable(B::Hash, B::Hash), /// Slot number must increase - #[display(fmt = "Slot number must increase: parent slot: {}, this slot: {}", _0, _1)] + #[error("Slot number must increase: parent slot: {0}, this slot: {1}")] SlotMustIncrease(Slot, Slot), /// Header has a bad seal - #[display(fmt = "Header {:?} has a bad seal", _0)] + #[error("Header {0:?} has a bad seal")] HeaderBadSeal(B::Hash), /// Header is unsealed - #[display(fmt = "Header {:?} is unsealed", _0)] + #[error("Header {0:?} is unsealed")] HeaderUnsealed(B::Hash), /// Slot author not found - #[display(fmt = "Slot author not found")] + #[error("Slot author not found")] SlotAuthorNotFound, /// Secondary slot assignments are disabled for the current epoch. - #[display(fmt = "Secondary slot assignments are disabled for the current epoch.")] + #[error("Secondary slot assignments are disabled for the current epoch.")] SecondarySlotAssignmentsDisabled, /// Bad signature - #[display(fmt = "Bad signature on {:?}", _0)] + #[error("Bad signature on {0:?}")] BadSignature(B::Hash), /// Invalid author: Expected secondary author - #[display(fmt = "Invalid author: Expected secondary author: {:?}, got: {:?}.", _0, _1)] + #[error("Invalid author: Expected secondary author: {0:?}, got: {1:?}.")] InvalidAuthor(AuthorityId, AuthorityId), /// No secondary author expected. - #[display(fmt = "No secondary author expected.")] + #[error("No secondary author expected.")] NoSecondaryAuthorExpected, /// VRF verification of block by author failed - #[display( - fmt = "VRF verification of block by author {:?} failed: threshold {} exceeded", - _0, - _1 - )] + #[error("VRF verification of block by author {0:?} failed: threshold {1} exceeded")] VRFVerificationOfBlockFailed(AuthorityId, u128), /// VRF verification failed - #[display(fmt = "VRF verification failed: {:?}", _0)] + #[error("VRF verification failed: {0:?}")] VRFVerificationFailed(SignatureError), /// Could not fetch parent header - #[display(fmt = "Could not fetch parent header: {:?}", _0)] + #[error("Could not fetch parent header: {0}")] FetchParentHeader(sp_blockchain::Error), /// Expected epoch change to happen. - #[display(fmt = "Expected epoch change to happen at {:?}, s{}", _0, _1)] + #[error("Expected epoch change to happen at {0:?}, s{1}")] ExpectedEpochChange(B::Hash, Slot), /// Unexpected config change. - #[display(fmt = "Unexpected config change")] + #[error("Unexpected config change")] UnexpectedConfigChange, /// Unexpected epoch change - #[display(fmt = "Unexpected epoch change")] + #[error("Unexpected epoch change")] UnexpectedEpochChange, /// Parent block has no associated weight - #[display(fmt = "Parent block of {} has no associated weight", _0)] + #[error("Parent block of {0} has no associated weight")] ParentBlockNoAssociatedWeight(B::Hash), /// Check inherents error - #[display(fmt = "Checking inherents failed: {}", _0)] + #[error("Checking inherents failed: {0}")] CheckInherents(sp_inherents::Error), /// Unhandled check inherents error - #[display(fmt = "Checking inherents unhandled error: {}", "String::from_utf8_lossy(_0)")] + #[error("Checking inherents unhandled error: {}", String::from_utf8_lossy(.0))] CheckInherentsUnhandled(sp_inherents::InherentIdentifier), /// Create inherents error. - #[display(fmt = "Creating inherents failed: {}", _0)] + #[error("Creating inherents failed: {0}")] CreateInherents(sp_inherents::Error), /// Client error + #[error(transparent)] Client(sp_blockchain::Error), /// Runtime Api error. + #[error(transparent)] RuntimeApi(sp_api::ApiError), /// Fork tree error + #[error(transparent)] ForkTree(Box>), } @@ -714,7 +713,7 @@ where parent.number().clone(), slot, ) - .map_err(|e| ConsensusError::ChainLookup(format!("{:?}", e)))? + .map_err(|e| ConsensusError::ChainLookup(e.to_string()))? .ok_or(sp_consensus::Error::InvalidAuthoritiesSet) } @@ -1202,7 +1201,7 @@ where ) .await { - warn!(target: "babe", "Error checking/reporting BABE equivocation: {:?}", err); + warn!(target: "babe", "Error checking/reporting BABE equivocation: {}", err); } // if the body is passed through, we need to use the runtime @@ -1552,7 +1551,7 @@ where ) .map_err(|e| { ConsensusError::ClientImport(format!( - "Error importing epoch changes: {:?}", + "Error importing epoch changes: {}", e )) })?; @@ -1560,7 +1559,7 @@ where }; if let Err(e) = prune_and_import() { - debug!(target: "babe", "Failed to launch next epoch: {:?}", e); + debug!(target: "babe", "Failed to launch next epoch: {}", e); *epoch_changes = old_epoch_changes.expect("set `Some` above and not taken; qed"); return Err(e) @@ -1591,7 +1590,7 @@ where parent_weight } else { aux_schema::load_block_weight(&*self.client, last_best) - .map_err(|e| ConsensusError::ChainLookup(format!("{:?}", e)))? + .map_err(|e| ConsensusError::ChainLookup(e.to_string()))? .ok_or_else(|| { ConsensusError::ChainLookup( "No block weight for parent header.".to_string(), @@ -1650,7 +1649,7 @@ where let finalized_slot = { let finalized_header = client .header(BlockId::Hash(info.finalized_hash)) - .map_err(|e| ConsensusError::ClientImport(format!("{:?}", e)))? + .map_err(|e| ConsensusError::ClientImport(e.to_string()))? .expect( "best finalized hash was given by client; finalized headers must exist in db; qed", ); @@ -1667,7 +1666,7 @@ where info.finalized_number, finalized_slot, ) - .map_err(|e| ConsensusError::ClientImport(format!("{:?}", e)))?; + .map_err(|e| ConsensusError::ClientImport(e.to_string()))?; Ok(()) } diff --git a/client/consensus/common/Cargo.toml b/client/consensus/common/Cargo.toml index 72a0544535ad7..a14a367690332 100644 --- a/client/consensus/common/Cargo.toml +++ b/client/consensus/common/Cargo.toml @@ -20,10 +20,10 @@ futures = { version = "0.3.1", features = ["thread-pool"] } futures-timer = "3.0.1" sc-client-api = { version = "4.0.0-dev", path = "../../api" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } -sp-core = { path = "../../../primitives/core", version = "4.1.0-dev" } +sp-core = { path = "../../../primitives/core", version = "5.0.0"} sp-consensus = { path = "../../../primitives/consensus/common", version = "0.10.0-dev" } -sp-state-machine = { version = "0.10.0", path = "../../../primitives/state-machine" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-state-machine = { version = "0.11.0", path = "../../../primitives/state-machine" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } sc-utils = { version = "4.0.0-dev", path = "../../utils" } sp-api = { version = "4.0.0-dev", path = "../../../primitives/api" } parking_lot = "0.11.2" diff --git a/client/consensus/common/src/import_queue.rs b/client/consensus/common/src/import_queue.rs index f71996fe2b1fa..8b560d0447411 100644 --- a/client/consensus/common/src/import_queue.rs +++ b/client/consensus/common/src/import_queue.rs @@ -161,21 +161,34 @@ pub enum BlockImportStatus { } /// Block import error. -#[derive(Debug)] +#[derive(Debug, thiserror::Error)] pub enum BlockImportError { /// Block missed header, can't be imported + #[error("block is missing a header (origin = {0:?})")] IncompleteHeader(Option), + /// Block verification failed, can't be imported + #[error("block verification failed (origin = {0:?}): {1}")] VerificationFailed(Option, String), + /// Block is known to be Bad + #[error("bad block (origin = {0:?})")] BadBlock(Option), + /// Parent state is missing. + #[error("block is missing parent state")] MissingState, + /// Block has an unknown parent + #[error("block has an unknown parent")] UnknownParent, + /// Block import has been cancelled. This can happen if the parent block fails to be imported. + #[error("import has been cancelled")] Cancelled, + /// Other error. + #[error("consensus error: {0}")] Other(ConsensusError), } @@ -245,7 +258,7 @@ pub(crate) async fn import_single_block_metered< Err(BlockImportError::BadBlock(peer.clone())) }, Err(e) => { - debug!(target: "sync", "Error importing block {}: {:?}: {:?}", number, hash, e); + debug!(target: "sync", "Error importing block {}: {:?}: {}", number, hash, e); Err(BlockImportError::Other(e)) }, }; diff --git a/client/consensus/common/src/import_queue/basic_queue.rs b/client/consensus/common/src/import_queue/basic_queue.rs index 0f23d9b546bd6..5134dc041c26b 100644 --- a/client/consensus/common/src/import_queue/basic_queue.rs +++ b/client/consensus/common/src/import_queue/basic_queue.rs @@ -303,11 +303,11 @@ impl BlockImportWorker { .map_err(|e| { debug!( target: "sync", - "Justification import failed with {:?} for hash: {:?} number: {:?} coming from node: {:?}", - e, + "Justification import failed for hash = {:?} with number = {:?} coming from node = {:?} with error: {}", hash, number, who, + e, ); e }) diff --git a/client/consensus/epochs/Cargo.toml b/client/consensus/epochs/Cargo.toml index bb4a77b559e0a..b377dccfd3689 100644 --- a/client/consensus/epochs/Cargo.toml +++ b/client/consensus/epochs/Cargo.toml @@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", features = ["derive"] } fork-tree = { version = "3.0.0", path = "../../../utils/fork-tree" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } sc-client-api = { path = "../../api" , version = "4.0.0-dev"} sc-consensus = { path = "../common" , version = "0.10.0-dev"} diff --git a/client/consensus/manual-seal/Cargo.toml b/client/consensus/manual-seal/Cargo.toml index 89f3335899f1b..c2c36b1fc5867 100644 --- a/client/consensus/manual-seal/Cargo.toml +++ b/client/consensus/manual-seal/Cargo.toml @@ -13,7 +13,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -derive_more = "0.99.16" +thiserror = "1.0" futures = "0.3.9" jsonrpc-core = "18.0.0" jsonrpc-core-client = "18.0.0" @@ -37,9 +37,9 @@ sp-blockchain = { path = "../../../primitives/blockchain", version = "4.0.0-dev" sp-consensus = { path = "../../../primitives/consensus/common", version = "0.10.0-dev" } sp-consensus-slots = { path = "../../../primitives/consensus/slots", version = "0.10.0-dev" } sp-inherents = { path = "../../../primitives/inherents", version = "4.0.0-dev" } -sp-runtime = { path = "../../../primitives/runtime", version = "4.1.0-dev" } -sp-core = { path = "../../../primitives/core", version = "4.1.0-dev" } -sp-keystore = { path = "../../../primitives/keystore", version = "0.10.0" } +sp-runtime = { path = "../../../primitives/runtime", version = "5.0.0"} +sp-core = { path = "../../../primitives/core", version = "5.0.0"} +sp-keystore = { path = "../../../primitives/keystore", version = "0.11.0"} sp-api = { path = "../../../primitives/api", version = "4.0.0-dev" } sc-transaction-pool-api = { path = "../../../client/transaction-pool/api", version = "4.0.0-dev" } sp-timestamp = { path = "../../../primitives/timestamp", version = "4.0.0-dev" } diff --git a/client/consensus/manual-seal/src/consensus/babe.rs b/client/consensus/manual-seal/src/consensus/babe.rs index 9c2a1638043a7..dd3f9a253478a 100644 --- a/client/consensus/manual-seal/src/consensus/babe.rs +++ b/client/consensus/manual-seal/src/consensus/babe.rs @@ -118,7 +118,7 @@ where pre_digest.slot(), ) .map_err(|e| format!("failed to fetch epoch_descriptor: {}", e))? - .ok_or_else(|| format!("{:?}", sp_consensus::Error::InvalidAuthoritiesSet))?; + .ok_or_else(|| format!("{}", sp_consensus::Error::InvalidAuthoritiesSet))?; // drop the lock drop(epoch_changes); diff --git a/client/consensus/manual-seal/src/error.rs b/client/consensus/manual-seal/src/error.rs index 3a67b36bc62bc..2f946f3de3ccc 100644 --- a/client/consensus/manual-seal/src/error.rs +++ b/client/consensus/manual-seal/src/error.rs @@ -38,40 +38,52 @@ mod codes { } /// errors encountered by background block authorship task -#[derive(Debug, derive_more::Display, derive_more::From)] +#[derive(Debug, thiserror::Error)] pub enum Error { /// An error occurred while importing the block - #[display(fmt = "Block import failed: {:?}", _0)] + #[error("Block import failed: {0:?}")] BlockImportError(ImportResult), /// Transaction pool is empty, cannot create a block - #[display(fmt = "Transaction pool is empty, set create_empty to true,\ - if you want to create empty blocks")] + #[error( + "Transaction pool is empty, set create_empty to true, if you want to create empty blocks" + )] EmptyTransactionPool, /// encountered during creation of Proposer. - #[display(fmt = "Consensus Error: {}", _0)] - ConsensusError(ConsensusError), + #[error("Consensus Error: {0}")] + ConsensusError(#[from] ConsensusError), /// Failed to create Inherents data - #[display(fmt = "Inherents Error: {}", _0)] - InherentError(InherentsError), + #[error("Inherents Error: {0}")] + InherentError(#[from] InherentsError), /// error encountered during finalization - #[display(fmt = "Finalization Error: {}", _0)] - BlockchainError(BlockchainError), + #[error("Finalization Error: {0}")] + BlockchainError(#[from] BlockchainError), /// Supplied parent_hash doesn't exist in chain - #[display(fmt = "Supplied parent_hash: {} doesn't exist in chain", _0)] - #[from(ignore)] + #[error("Supplied parent_hash: {0} doesn't exist in chain")] BlockNotFound(String), /// Some string error - #[display(fmt = "{}", _0)] + #[error("{0}")] StringError(String), /// send error - #[display(fmt = "Consensus process is terminating")] - Canceled(oneshot::Canceled), + #[error("Consensus process is terminating")] + Canceled(#[from] oneshot::Canceled), /// send error - #[display(fmt = "Consensus process is terminating")] - SendError(SendError), + #[error("Consensus process is terminating")] + SendError(#[from] SendError), /// Some other error. - #[display(fmt = "Other error: {}", _0)] - Other(Box), + #[error("Other error: {0}")] + Other(#[from] Box), +} + +impl From for Error { + fn from(err: ImportResult) -> Self { + Error::BlockImportError(err) + } +} + +impl From for Error { + fn from(s: String) -> Self { + Error::StringError(s) + } } impl Error { diff --git a/client/consensus/manual-seal/src/finalize_block.rs b/client/consensus/manual-seal/src/finalize_block.rs index bc242ad6085ee..d134ce7734571 100644 --- a/client/consensus/manual-seal/src/finalize_block.rs +++ b/client/consensus/manual-seal/src/finalize_block.rs @@ -48,7 +48,7 @@ where match finalizer.finalize_block(BlockId::Hash(hash), justification, true) { Err(e) => { - log::warn!("Failed to finalize block {:?}", e); + log::warn!("Failed to finalize block {}", e); rpc::send_result(&mut sender, Err(e.into())) }, Ok(()) => { diff --git a/client/consensus/manual-seal/src/rpc.rs b/client/consensus/manual-seal/src/rpc.rs index 7b4063e9b2b1b..4a8dcbc0cb765 100644 --- a/client/consensus/manual-seal/src/rpc.rs +++ b/client/consensus/manual-seal/src/rpc.rs @@ -155,7 +155,10 @@ pub fn send_result( ) { if let Some(sender) = sender.take() { if let Err(err) = sender.send(result) { - log::warn!("Server is shutting down: {:?}", err) + match err { + Ok(value) => log::warn!("Server is shutting down: {:?}", value), + Err(error) => log::warn!("Server is shutting down with error: {}", error), + } } } else { // instant seal doesn't report errors over rpc, simply log them. diff --git a/client/consensus/manual-seal/src/seal_block.rs b/client/consensus/manual-seal/src/seal_block.rs index 99b003c32f136..202b54fe5d0c5 100644 --- a/client/consensus/manual-seal/src/seal_block.rs +++ b/client/consensus/manual-seal/src/seal_block.rs @@ -114,10 +114,7 @@ pub async fn seal_block( let inherent_data = inherent_data_providers.create_inherent_data()?; - let proposer = env - .init(&parent) - .map_err(|err| Error::StringError(format!("{:?}", err))) - .await?; + let proposer = env.init(&parent).map_err(|err| Error::StringError(err.to_string())).await?; let inherents_len = inherent_data.len(); let digest = if let Some(digest_provider) = digest_provider { @@ -133,7 +130,7 @@ pub async fn seal_block( Duration::from_secs(MAX_PROPOSAL_DURATION), None, ) - .map_err(|err| Error::StringError(format!("{:?}", err))) + .map_err(|err| Error::StringError(err.to_string())) .await?; if proposal.block.extrinsics().len() == inherents_len && !create_empty { diff --git a/client/consensus/pow/Cargo.toml b/client/consensus/pow/Cargo.toml index db9e4e164e4e9..eb609489290a0 100644 --- a/client/consensus/pow/Cargo.toml +++ b/client/consensus/pow/Cargo.toml @@ -14,9 +14,9 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", features = ["derive"] } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } sp-api = { version = "4.0.0-dev", path = "../../../primitives/api" } sc-client-api = { version = "4.0.0-dev", path = "../../api" } sp-block-builder = { version = "4.0.0-dev", path = "../../../primitives/block-builder" } @@ -28,6 +28,6 @@ log = "0.4.8" futures = "0.3.16" futures-timer = "3.0.1" parking_lot = "0.11.2" -derive_more = "0.99.16" +thiserror = "1.0" prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../utils/prometheus", version = "0.10.0-dev"} async-trait = "0.1.50" diff --git a/client/consensus/pow/src/lib.rs b/client/consensus/pow/src/lib.rs index 0bcb9f3d00a54..6d0bc3fc5a192 100644 --- a/client/consensus/pow/src/lib.rs +++ b/client/consensus/pow/src/lib.rs @@ -72,45 +72,50 @@ use std::{ time::Duration, }; -#[derive(derive_more::Display, Debug)] +#[derive(Debug, thiserror::Error)] pub enum Error { - #[display(fmt = "Header uses the wrong engine {:?}", _0)] + #[error("Header uses the wrong engine {0:?}")] WrongEngine([u8; 4]), - #[display(fmt = "Header {:?} is unsealed", _0)] + #[error("Header {0:?} is unsealed")] HeaderUnsealed(B::Hash), - #[display(fmt = "PoW validation error: invalid seal")] + #[error("PoW validation error: invalid seal")] InvalidSeal, - #[display(fmt = "PoW validation error: preliminary verification failed")] + #[error("PoW validation error: preliminary verification failed")] FailedPreliminaryVerify, - #[display(fmt = "Rejecting block too far in future")] + #[error("Rejecting block too far in future")] TooFarInFuture, - #[display(fmt = "Fetching best header failed using select chain: {:?}", _0)] + #[error("Fetching best header failed using select chain: {0}")] BestHeaderSelectChain(ConsensusError), - #[display(fmt = "Fetching best header failed: {:?}", _0)] + #[error("Fetching best header failed: {0}")] BestHeader(sp_blockchain::Error), - #[display(fmt = "Best header does not exist")] + #[error("Best header does not exist")] NoBestHeader, - #[display(fmt = "Block proposing error: {:?}", _0)] + #[error("Block proposing error: {0}")] BlockProposingError(String), - #[display(fmt = "Fetch best hash failed via select chain: {:?}", _0)] + #[error("Fetch best hash failed via select chain: {0}")] BestHashSelectChain(ConsensusError), - #[display(fmt = "Error with block built on {:?}: {:?}", _0, _1)] + #[error("Error with block built on {0:?}: {1}")] BlockBuiltError(B::Hash, ConsensusError), - #[display(fmt = "Creating inherents failed: {}", _0)] + #[error("Creating inherents failed: {0}")] CreateInherents(sp_inherents::Error), - #[display(fmt = "Checking inherents failed: {}", _0)] + #[error("Checking inherents failed: {0}")] CheckInherents(sp_inherents::Error), - #[display( - fmt = "Checking inherents unknown error for identifier: {:?}", - "String::from_utf8_lossy(_0)" + #[error( + "Checking inherents unknown error for identifier: {}", + String::from_utf8_lossy(.0) )] CheckInherentsUnknownError(sp_inherents::InherentIdentifier), - #[display(fmt = "Multiple pre-runtime digests")] + #[error("Multiple pre-runtime digests")] MultiplePreRuntimeDigests, + #[error(transparent)] Client(sp_blockchain::Error), + #[error(transparent)] Codec(codec::Error), + #[error("{0}")] Environment(String), + #[error("{0}")] Runtime(RuntimeString), + #[error("{0}")] Other(String), } @@ -345,7 +350,7 @@ where .select_chain .best_chain() .await - .map_err(|e| format!("Fetch best chain failed via select chain: {:?}", e))?; + .map_err(|e| format!("Fetch best chain failed via select chain: {}", e))?; let best_hash = best_header.hash(); let parent_hash = *block.header.parent_hash(); @@ -560,7 +565,7 @@ where warn!( target: "pow", "Unable to pull new block for authoring. \ - Select best chain error: {:?}", + Select best chain error: {}", err ); continue @@ -591,7 +596,7 @@ where warn!( target: "pow", "Unable to propose new block for authoring. \ - Fetch difficulty failed: {:?}", + Fetch difficulty failed: {}", err, ); continue @@ -607,7 +612,7 @@ where warn!( target: "pow", "Unable to propose new block for authoring. \ - Creating inherent data providers failed: {:?}", + Creating inherent data providers failed: {}", err, ); continue @@ -620,7 +625,7 @@ where warn!( target: "pow", "Unable to propose new block for authoring. \ - Creating inherent data failed: {:?}", + Creating inherent data failed: {}", e, ); continue @@ -656,7 +661,7 @@ where warn!( target: "pow", "Unable to propose new block for authoring. \ - Creating proposal failed: {:?}", + Creating proposal failed: {}", err, ); continue diff --git a/client/consensus/pow/src/worker.rs b/client/consensus/pow/src/worker.rs index 031cf7f6a2940..42f82fb43ef7b 100644 --- a/client/consensus/pow/src/worker.rs +++ b/client/consensus/pow/src/worker.rs @@ -169,7 +169,7 @@ where Err(err) => { warn!( target: "pow", - "Unable to import mined block: {:?}", + "Unable to import mined block: {}", err, ); return false @@ -238,7 +238,7 @@ where Err(err) => { warn!( target: "pow", - "Unable to import mined block: {:?}", + "Unable to import mined block: {}", err, ); false diff --git a/client/consensus/slots/Cargo.toml b/client/consensus/slots/Cargo.toml index 60f57449a3a33..b13c1bb6b5b32 100644 --- a/client/consensus/slots/Cargo.toml +++ b/client/consensus/slots/Cargo.toml @@ -16,13 +16,13 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0" } sc-client-api = { version = "4.0.0-dev", path = "../../api" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } sp-arithmetic = { version = "4.0.0", path = "../../../primitives/arithmetic" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } sc-consensus = { version = "0.10.0-dev", path = "../../../client/consensus/common" } sp-consensus-slots = { version = "0.10.0-dev", path = "../../../primitives/consensus/slots" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } -sp-state-machine = { version = "0.10.0", path = "../../../primitives/state-machine" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } +sp-state-machine = { version = "0.11.0", path = "../../../primitives/state-machine" } sc-telemetry = { version = "4.0.0-dev", path = "../../telemetry" } sp-consensus = { version = "0.10.0-dev", path = "../../../primitives/consensus/common" } sp-inherents = { version = "4.0.0-dev", path = "../../../primitives/inherents" } diff --git a/client/consensus/slots/src/lib.rs b/client/consensus/slots/src/lib.rs index a1b335f7a5940..9fc93788a33e9 100644 --- a/client/consensus/slots/src/lib.rs +++ b/client/consensus/slots/src/lib.rs @@ -214,7 +214,7 @@ pub trait SimpleSlotWorker { Err(err) => { warn!( target: logging_target, - "Unable to fetch epoch data at block {:?}: {:?}", + "Unable to fetch epoch data at block {:?}: {}", slot_info.chain_head.hash(), err, ); @@ -274,10 +274,7 @@ pub trait SimpleSlotWorker { let proposer = match self.proposer(&slot_info.chain_head).await { Ok(p) => p, Err(err) => { - warn!( - target: logging_target, - "Unable to author block in slot {:?}: {:?}", slot, err, - ); + warn!(target: logging_target, "Unable to author block in slot {:?}: {}", slot, err,); telemetry!( telemetry; @@ -303,12 +300,12 @@ pub trait SimpleSlotWorker { proposing_remaining_duration.mul_f32(0.98), None, ) - .map_err(|e| sp_consensus::Error::ClientImport(format!("{:?}", e))); + .map_err(|e| sp_consensus::Error::ClientImport(e.to_string())); let proposal = match futures::future::select(proposing, proposing_remaining).await { Either::Left((Ok(p), _)) => p, Either::Left((Err(err), _)) => { - warn!(target: logging_target, "Proposing failed: {:?}", err); + warn!(target: logging_target, "Proposing failed: {}", err); return None }, @@ -353,7 +350,7 @@ pub trait SimpleSlotWorker { { Ok(bi) => bi, Err(err) => { - warn!(target: logging_target, "Failed to create block import params: {:?}", err); + warn!(target: logging_target, "Failed to create block import params: {}", err); return None }, @@ -388,7 +385,7 @@ pub trait SimpleSlotWorker { Err(err) => { warn!( target: logging_target, - "Error with block built on {:?}: {:?}", parent_hash, err, + "Error with block built on {:?}: {}", parent_hash, err, ); telemetry!( @@ -488,7 +485,7 @@ pub async fn start_slot_worker( let slot_info = match slots.next_slot().await { Ok(r) => r, Err(e) => { - warn!(target: "slots", "Error while polling for next slot: {:?}", e); + warn!(target: "slots", "Error while polling for next slot: {}", e); return }, }; diff --git a/client/consensus/slots/src/slots.rs b/client/consensus/slots/src/slots.rs index 2b792af7da8c4..a7b9f3e3ff611 100644 --- a/client/consensus/slots/src/slots.rs +++ b/client/consensus/slots/src/slots.rs @@ -150,7 +150,7 @@ where Err(e) => { log::warn!( target: "slots", - "Unable to author block in slot. No best block header: {:?}", + "Unable to author block in slot. No best block header: {}", e, ); // Let's try at the next slot.. diff --git a/client/consensus/uncles/Cargo.toml b/client/consensus/uncles/Cargo.toml index b9eaae4773a6a..7482fdc12d081 100644 --- a/client/consensus/uncles/Cargo.toml +++ b/client/consensus/uncles/Cargo.toml @@ -14,6 +14,6 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] sc-client-api = { version = "4.0.0-dev", path = "../../api" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } sp-authorship = { version = "4.0.0-dev", path = "../../../primitives/authorship" } thiserror = "1.0.30" diff --git a/client/db/Cargo.toml b/client/db/Cargo.toml index 0db0f8309e2eb..f2c21abf6c1d6 100644 --- a/client/db/Cargo.toml +++ b/client/db/Cargo.toml @@ -26,11 +26,11 @@ codec = { package = "parity-scale-codec", version = "2.0.0", features = [ sc-client-api = { version = "4.0.0-dev", path = "../api" } sp-arithmetic = { version = "4.0.0", path = "../../primitives/arithmetic" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } -sp-state-machine = { version = "0.10.0", path = "../../primitives/state-machine" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } +sp-state-machine = { version = "0.11.0", path = "../../primitives/state-machine" } sc-state-db = { version = "0.10.0-dev", path = "../state-db" } -sp-trie = { version = "4.0.0", path = "../../primitives/trie" } +sp-trie = { version = "5.0.0", path = "../../primitives/trie" } sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } sp-database = { version = "4.0.0-dev", path = "../../primitives/database" } parity-db = { version = "0.3.5", optional = true } diff --git a/client/executor/Cargo.toml b/client/executor/Cargo.toml index e10cbf347db59..0d0f2a8bd92ed 100644 --- a/client/executor/Cargo.toml +++ b/client/executor/Cargo.toml @@ -15,18 +15,18 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0" } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } sp-tasks = { version = "4.0.0-dev", path = "../../primitives/tasks" } -sp-trie = { version = "4.0.0", path = "../../primitives/trie" } +sp-trie = { version = "5.0.0", path = "../../primitives/trie" } sp-version = { version = "4.0.0-dev", path = "../../primitives/version" } sp-panic-handler = { version = "4.0.0", path = "../../primitives/panic-handler" } wasmi = "0.9.1" lazy_static = "1.4.0" sp-api = { version = "4.0.0-dev", path = "../../primitives/api" } -sp-wasm-interface = { version = "4.1.0-dev", path = "../../primitives/wasm-interface" } -sp-runtime-interface = { version = "4.1.0-dev", path = "../../primitives/runtime-interface" } -sp-externalities = { version = "0.10.0", path = "../../primitives/externalities" } +sp-wasm-interface = { version = "5.0.0", path = "../../primitives/wasm-interface" } +sp-runtime-interface = { version = "5.0.0", path = "../../primitives/runtime-interface" } +sp-externalities = { version = "0.11.0", path = "../../primitives/externalities" } sc-executor-common = { version = "0.10.0-dev", path = "common" } sc-executor-wasmi = { version = "0.10.0-dev", path = "wasmi" } sc-executor-wasmtime = { version = "0.10.0-dev", path = "wasmtime", optional = true } @@ -41,8 +41,8 @@ wat = "1.0" hex-literal = "0.3.4" sc-runtime-test = { version = "2.0.0", path = "runtime-test" } substrate-test-runtime = { version = "2.0.0", path = "../../test-utils/runtime" } -sp-state-machine = { version = "0.10.0", path = "../../primitives/state-machine" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-state-machine = { version = "0.11.0", path = "../../primitives/state-machine" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } sp-maybe-compressed-blob = { version = "4.1.0-dev", path = "../../primitives/maybe-compressed-blob" } sc-tracing = { version = "4.0.0-dev", path = "../tracing" } tracing = "0.1.29" diff --git a/client/executor/common/Cargo.toml b/client/executor/common/Cargo.toml index 8e4b11f8f8fae..e23db203b3a40 100644 --- a/client/executor/common/Cargo.toml +++ b/client/executor/common/Cargo.toml @@ -14,13 +14,12 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -derive_more = "0.99.16" wasm-instrument = "0.1" codec = { package = "parity-scale-codec", version = "2.0.0" } wasmi = "0.9.1" -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } sc-allocator = { version = "4.1.0-dev", path = "../../allocator" } -sp-wasm-interface = { version = "4.1.0-dev", path = "../../../primitives/wasm-interface" } +sp-wasm-interface = { version = "5.0.0", path = "../../../primitives/wasm-interface" } sp-maybe-compressed-blob = { version = "4.1.0-dev", path = "../../../primitives/maybe-compressed-blob" } sp-serializer = { version = "4.0.0-dev", path = "../../../primitives/serializer" } thiserror = "1.0.30" diff --git a/client/executor/common/src/error.rs b/client/executor/common/src/error.rs index 90e658a896281..c5de737376c15 100644 --- a/client/executor/common/src/error.rs +++ b/client/executor/common/src/error.rs @@ -31,9 +31,6 @@ pub enum Error { #[error("Unserializable data encountered")] InvalidData(#[from] sp_serializer::Error), - #[error(transparent)] - Trap(#[from] wasmi::Trap), - #[error(transparent)] Wasmi(#[from] wasmi::Error), @@ -108,6 +105,12 @@ pub enum Error { #[error("Invalid initializer expression provided {0}")] InvalidInitializerExpression(String), + + #[error("Execution aborted due to panic: {0}")] + AbortedDueToPanic(MessageWithBacktrace), + + #[error("Execution aborted due to trap: {0}")] + AbortedDueToTrap(MessageWithBacktrace), } impl wasmi::HostError for Error {} @@ -125,28 +128,73 @@ impl From for Error { } /// Type for errors occurring during Wasm runtime construction. -#[derive(Debug, derive_more::Display)] +#[derive(Debug, thiserror::Error)] +#[allow(missing_docs)] pub enum WasmError { - /// Code could not be read from the state. + #[error("Code could not be read from the state.")] CodeNotFound, - /// Failure to reinitialize runtime instance from snapshot. + + #[error("Failure to reinitialize runtime instance from snapshot.")] ApplySnapshotFailed, + /// Failure to erase the wasm memory. /// /// Depending on the implementation might mean failure of allocating memory. + #[error("Failure to erase the wasm memory: {0}")] ErasingFailed(String), - /// Wasm code failed validation. + + #[error("Wasm code failed validation.")] InvalidModule, - /// Wasm code could not be deserialized. + + #[error("Wasm code could not be deserialized.")] CantDeserializeWasm, - /// The module does not export a linear memory named `memory`. + + #[error("The module does not export a linear memory named `memory`.")] InvalidMemory, - /// The number of heap pages requested is disallowed by the module. + + #[error("The number of heap pages requested is disallowed by the module.")] InvalidHeapPages, + /// Instantiation error. + #[error("{0}")] Instantiation(String), + /// Other error happenend. + #[error("{0}")] Other(String), } -impl std::error::Error for WasmError {} +/// An error message with an attached backtrace. +#[derive(Debug)] +pub struct MessageWithBacktrace { + /// The error message. + pub message: String, + + /// The backtrace associated with the error message. + pub backtrace: Option, +} + +impl std::fmt::Display for MessageWithBacktrace { + fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { + fmt.write_str(&self.message)?; + if let Some(ref backtrace) = self.backtrace { + fmt.write_str("\nWASM backtrace:\n")?; + backtrace.backtrace_string.fmt(fmt)?; + } + + Ok(()) + } +} + +/// A WASM backtrace. +#[derive(Debug)] +pub struct Backtrace { + /// The string containing the backtrace. + pub backtrace_string: String, +} + +impl std::fmt::Display for Backtrace { + fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { + fmt.write_str(&self.backtrace_string) + } +} diff --git a/client/executor/runtime-test/Cargo.toml b/client/executor/runtime-test/Cargo.toml index 1318c7246a848..ca1746c842e15 100644 --- a/client/executor/runtime-test/Cargo.toml +++ b/client/executor/runtime-test/Cargo.toml @@ -13,9 +13,9 @@ repository = "https://github.com/paritytech/substrate/" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/core" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../../primitives/io", features = ["improved_panic_error_reporting"] } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } sp-sandbox = { version = "0.10.0-dev", default-features = false, path = "../../../primitives/sandbox" } sp-std = { version = "4.0.0", default-features = false, path = "../../../primitives/std" } sp-tasks = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/tasks" } diff --git a/client/executor/runtime-test/src/lib.rs b/client/executor/runtime-test/src/lib.rs index 0655160c1ab7a..bf9f76edd945e 100644 --- a/client/executor/runtime-test/src/lib.rs +++ b/client/executor/runtime-test/src/lib.rs @@ -341,6 +341,14 @@ sp_core::wasm_export_functions! { fn test_take_i8(value: i8) { assert_eq!(value, -66); } + + fn test_abort_on_panic() { + sp_io::panic_handler::abort_on_panic("test_abort_on_panic called"); + } + + fn test_unreachable_intrinsic() { + core::arch::wasm32::unreachable() + } } #[cfg(not(feature = "std"))] diff --git a/client/executor/src/integration_tests/mod.rs b/client/executor/src/integration_tests/mod.rs index 67e9a96cd6bae..462a8ba1b8766 100644 --- a/client/executor/src/integration_tests/mod.rs +++ b/client/executor/src/integration_tests/mod.rs @@ -22,7 +22,7 @@ mod sandbox; use codec::{Decode, Encode}; use hex_literal::hex; -use sc_executor_common::{runtime_blob::RuntimeBlob, wasm_runtime::WasmModule}; +use sc_executor_common::{error::Error, runtime_blob::RuntimeBlob, wasm_runtime::WasmModule}; use sc_runtime_test::wasm_binary_unwrap; use sp_core::{ blake2_128, blake2_256, ed25519, map, @@ -122,7 +122,7 @@ fn call_in_wasm( call_data: &[u8], execution_method: WasmExecutionMethod, ext: &mut E, -) -> Result, String> { +) -> Result, Error> { let executor = crate::WasmExecutor::::new(execution_method, Some(1024), 8, None, 2); executor.uncached_call( @@ -148,25 +148,16 @@ fn call_not_existing_function(wasm_method: WasmExecutionMethod) { let mut ext = TestExternalities::default(); let mut ext = ext.ext(); - match call_in_wasm( - "test_calling_missing_external", - &[], - wasm_method, - &mut ext, - ) { - Ok(_) => panic!("was expected an `Err`"), - Err(e) => { - match wasm_method { - WasmExecutionMethod::Interpreted => assert_eq!( - &format!("{:?}", e), - "\"Trap: Trap { kind: Host(Other(\\\"Function `missing_external` is only a stub. Calling a stub is not allowed.\\\")) }\"" - ), + match call_in_wasm("test_calling_missing_external", &[], wasm_method, &mut ext).unwrap_err() { + Error::AbortedDueToTrap(error) => { + let expected = match wasm_method { + WasmExecutionMethod::Interpreted => "Trap: Host(Other(\"Function `missing_external` is only a stub. Calling a stub is not allowed.\"))", #[cfg(feature = "wasmtime")] - WasmExecutionMethod::Compiled => assert!( - format!("{:?}", e).contains("Wasm execution trapped: call to a missing function env:missing_external") - ), - } - } + WasmExecutionMethod::Compiled => "call to a missing function env:missing_external" + }; + assert_eq!(error.message, expected); + }, + error => panic!("unexpected error: {:?}", error), } } @@ -175,25 +166,18 @@ fn call_yet_another_not_existing_function(wasm_method: WasmExecutionMethod) { let mut ext = TestExternalities::default(); let mut ext = ext.ext(); - match call_in_wasm( - "test_calling_yet_another_missing_external", - &[], - wasm_method, - &mut ext, - ) { - Ok(_) => panic!("was expected an `Err`"), - Err(e) => { - match wasm_method { - WasmExecutionMethod::Interpreted => assert_eq!( - &format!("{:?}", e), - "\"Trap: Trap { kind: Host(Other(\\\"Function `yet_another_missing_external` is only a stub. Calling a stub is not allowed.\\\")) }\"" - ), + match call_in_wasm("test_calling_yet_another_missing_external", &[], wasm_method, &mut ext) + .unwrap_err() + { + Error::AbortedDueToTrap(error) => { + let expected = match wasm_method { + WasmExecutionMethod::Interpreted => "Trap: Host(Other(\"Function `yet_another_missing_external` is only a stub. Calling a stub is not allowed.\"))", #[cfg(feature = "wasmtime")] - WasmExecutionMethod::Compiled => assert!( - format!("{:?}", e).contains("Wasm execution trapped: call to a missing function env:yet_another_missing_external") - ), - } - } + WasmExecutionMethod::Compiled => "call to a missing function env:yet_another_missing_external" + }; + assert_eq!(error.message, expected); + }, + error => panic!("unexpected error: {:?}", error), } } @@ -485,6 +469,7 @@ fn should_trap_when_heap_exhausted(wasm_method: WasmExecutionMethod) { "test_exhaust_heap", &[0], ) + .map_err(|e| e.to_string()) .unwrap_err(); assert!(err.contains("Allocator ran out of space")); @@ -691,7 +676,7 @@ fn panic_in_spawned_instance_panics_on_joining_its_result(wasm_method: WasmExecu let error_result = call_in_wasm("test_panic_in_spawned", &[], wasm_method, &mut ext).unwrap_err(); - assert!(error_result.contains("Spawned task")); + assert!(error_result.to_string().contains("Spawned task")); } test_wasm_execution!(memory_is_cleared_between_invocations); @@ -789,3 +774,32 @@ fn take_i8(wasm_method: WasmExecutionMethod) { call_in_wasm("test_take_i8", &(-66_i8).encode(), wasm_method, &mut ext).unwrap(); } + +test_wasm_execution!(abort_on_panic); +fn abort_on_panic(wasm_method: WasmExecutionMethod) { + let mut ext = TestExternalities::default(); + let mut ext = ext.ext(); + + match call_in_wasm("test_abort_on_panic", &[], wasm_method, &mut ext).unwrap_err() { + Error::AbortedDueToPanic(error) => assert_eq!(error.message, "test_abort_on_panic called"), + error => panic!("unexpected error: {:?}", error), + } +} + +test_wasm_execution!(unreachable_intrinsic); +fn unreachable_intrinsic(wasm_method: WasmExecutionMethod) { + let mut ext = TestExternalities::default(); + let mut ext = ext.ext(); + + match call_in_wasm("test_unreachable_intrinsic", &[], wasm_method, &mut ext).unwrap_err() { + Error::AbortedDueToTrap(error) => { + let expected = match wasm_method { + WasmExecutionMethod::Interpreted => "Trap: Unreachable", + #[cfg(feature = "wasmtime")] + WasmExecutionMethod::Compiled => "wasm trap: wasm `unreachable` instruction executed", + }; + assert_eq!(error.message, expected); + }, + error => panic!("unexpected error: {:?}", error), + } +} diff --git a/client/executor/src/native_executor.rs b/client/executor/src/native_executor.rs index b36d6f1297e91..1bc87840ba353 100644 --- a/client/executor/src/native_executor.rs +++ b/client/executor/src/native_executor.rs @@ -220,7 +220,7 @@ where allow_missing_host_functions: bool, export_name: &str, call_data: &[u8], - ) -> std::result::Result, String> { + ) -> std::result::Result, Error> { let module = crate::wasm_runtime::create_wasm_runtime_with_code::( self.method, self.default_heap_pages, @@ -228,11 +228,10 @@ where allow_missing_host_functions, self.cache_path.as_deref(), ) - .map_err(|e| format!("Failed to create module: {:?}", e))?; + .map_err(|e| format!("Failed to create module: {}", e))?; - let instance = module - .new_instance() - .map_err(|e| format!("Failed to create instance: {:?}", e))?; + let instance = + module.new_instance().map_err(|e| format!("Failed to create instance: {}", e))?; let mut instance = AssertUnwindSafe(instance); let mut ext = AssertUnwindSafe(ext); @@ -243,7 +242,6 @@ where instance.call_export(export_name, call_data) }) .and_then(|r| r) - .map_err(|e| e.to_string()) } } @@ -281,6 +279,7 @@ where "Core_version", &[], ) + .map_err(|e| e.to_string()) } } @@ -456,12 +455,18 @@ impl RuntimeSpawn for RuntimeInstanceSpawn { // pool of instances should be used. // // https://github.com/paritytech/substrate/issues/7354 - let mut instance = - module.new_instance().expect("Failed to create new instance from module"); + let mut instance = match module.new_instance() { + Ok(instance) => instance, + Err(error) => + panic!("failed to create new instance from module: {}", error), + }; - instance + match instance .call(InvokeMethod::TableWithWrapper { dispatcher_ref, func }, &data[..]) - .expect("Failed to invoke instance.") + { + Ok(result) => result, + Err(error) => panic!("failed to invoke instance: {}", error), + } }); match result { @@ -471,7 +476,7 @@ impl RuntimeSpawn for RuntimeInstanceSpawn { Err(error) => { // If execution is panicked, the `join` in the original runtime code will // panic as well, since the sender is dropped without sending anything. - log::error!("Call error in spawned task: {:?}", error); + log::error!("Call error in spawned task: {}", error); }, } }), diff --git a/client/executor/src/wasm_runtime.rs b/client/executor/src/wasm_runtime.rs index 0775755aff7cf..2cccb6f9c38b0 100644 --- a/client/executor/src/wasm_runtime.rs +++ b/client/executor/src/wasm_runtime.rs @@ -105,13 +105,13 @@ impl VersionedRuntime { if new_inst { log::warn!( target: "wasm-runtime", - "Fresh runtime instance failed with {:?}", + "Fresh runtime instance failed with {}", e, ) } else { log::warn!( target: "wasm-runtime", - "Evicting failed runtime instance: {:?}", + "Evicting failed runtime instance: {}", e, ); } diff --git a/client/executor/wasmi/Cargo.toml b/client/executor/wasmi/Cargo.toml index 9dc63747166b5..d333e98bf6cfb 100644 --- a/client/executor/wasmi/Cargo.toml +++ b/client/executor/wasmi/Cargo.toml @@ -19,7 +19,7 @@ wasmi = "0.9.1" codec = { package = "parity-scale-codec", version = "2.0.0" } sc-executor-common = { version = "0.10.0-dev", path = "../common" } sc-allocator = { version = "4.1.0-dev", path = "../../allocator" } -sp-wasm-interface = { version = "4.1.0-dev", path = "../../../primitives/wasm-interface" } -sp-runtime-interface = { version = "4.1.0-dev", path = "../../../primitives/runtime-interface" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } +sp-wasm-interface = { version = "5.0.0", path = "../../../primitives/wasm-interface" } +sp-runtime-interface = { version = "5.0.0", path = "../../../primitives/runtime-interface" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } scoped-tls = "1.0" diff --git a/client/executor/wasmi/src/lib.rs b/client/executor/wasmi/src/lib.rs index 78fd300e05e3d..f0488972daca9 100644 --- a/client/executor/wasmi/src/lib.rs +++ b/client/executor/wasmi/src/lib.rs @@ -21,7 +21,7 @@ use codec::{Decode, Encode}; use log::{debug, error, trace}; use sc_executor_common::{ - error::{Error, WasmError}, + error::{Error, MessageWithBacktrace, WasmError}, runtime_blob::{DataSegmentsSnapshot, RuntimeBlob}, sandbox, util::MemoryTransfer, @@ -48,6 +48,7 @@ struct FunctionExecutor { host_functions: Arc>, allow_missing_func_imports: bool, missing_functions: Arc>, + panic_message: Option, } impl FunctionExecutor { @@ -69,6 +70,7 @@ impl FunctionExecutor { host_functions, allow_missing_func_imports, missing_functions, + panic_message: None, }) } } @@ -100,7 +102,10 @@ impl<'a> sandbox::SandboxContext for SandboxContext<'a> { match result { Ok(Some(RuntimeValue::I64(val))) => Ok(val), Ok(_) => return Err("Supervisor function returned unexpected result!".into()), - Err(err) => Err(Error::Trap(err)), + Err(err) => Err(Error::AbortedDueToTrap(MessageWithBacktrace { + message: err.to_string(), + backtrace: None, + })), } } @@ -133,6 +138,10 @@ impl FunctionContext for FunctionExecutor { fn sandbox(&mut self) -> &mut dyn Sandbox { self } + + fn register_panic_error_message(&mut self, message: &str) { + self.panic_message = Some(message.to_owned()); + } } impl Sandbox for FunctionExecutor { @@ -502,12 +511,31 @@ fn call_in_wasm_module( let offset = function_executor.allocate_memory(data.len() as u32)?; function_executor.write_memory(offset, data)?; + fn convert_trap(executor: &mut FunctionExecutor, trap: wasmi::Trap) -> Error { + if let Some(message) = executor.panic_message.take() { + Error::AbortedDueToPanic(MessageWithBacktrace { message, backtrace: None }) + } else { + Error::AbortedDueToTrap(MessageWithBacktrace { + message: trap.to_string(), + backtrace: None, + }) + } + } + let result = match method { - InvokeMethod::Export(method) => module_instance.invoke_export( - method, - &[I32(u32::from(offset) as i32), I32(data.len() as i32)], - &mut function_executor, - ), + InvokeMethod::Export(method) => module_instance + .invoke_export( + method, + &[I32(u32::from(offset) as i32), I32(data.len() as i32)], + &mut function_executor, + ) + .map_err(|error| { + if let wasmi::Error::Trap(trap) = error { + convert_trap(&mut function_executor, trap) + } else { + error.into() + } + }), InvokeMethod::Table(func_ref) => { let func = table .ok_or(Error::NoTable)? @@ -518,7 +546,7 @@ fn call_in_wasm_module( &[I32(u32::from(offset) as i32), I32(data.len() as i32)], &mut function_executor, ) - .map_err(Into::into) + .map_err(|trap| convert_trap(&mut function_executor, trap)) }, InvokeMethod::TableWithWrapper { dispatcher_ref, func } => { let dispatcher = table @@ -531,7 +559,7 @@ fn call_in_wasm_module( &[I32(func as _), I32(u32::from(offset) as i32), I32(data.len() as i32)], &mut function_executor, ) - .map_err(Into::into) + .map_err(|trap| convert_trap(&mut function_executor, trap)) }, }; diff --git a/client/executor/wasmtime/Cargo.toml b/client/executor/wasmtime/Cargo.toml index 8b3cd1a58e75f..0423b384943e8 100644 --- a/client/executor/wasmtime/Cargo.toml +++ b/client/executor/wasmtime/Cargo.toml @@ -19,9 +19,9 @@ log = "0.4.8" parity-wasm = "0.42.0" codec = { package = "parity-scale-codec", version = "2.0.0" } sc-executor-common = { version = "0.10.0-dev", path = "../common" } -sp-wasm-interface = { version = "4.1.0-dev", path = "../../../primitives/wasm-interface", features = ["wasmtime"] } -sp-runtime-interface = { version = "4.1.0-dev", path = "../../../primitives/runtime-interface" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } +sp-wasm-interface = { version = "5.0.0", path = "../../../primitives/wasm-interface", features = ["wasmtime"] } +sp-runtime-interface = { version = "5.0.0", path = "../../../primitives/runtime-interface" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } sc-allocator = { version = "4.1.0-dev", path = "../../allocator" } wasmtime = { version = "0.33.0", default-features = false, features = [ "cache", @@ -32,5 +32,5 @@ wasmtime = { version = "0.33.0", default-features = false, features = [ [dev-dependencies] sc-runtime-test = { version = "2.0.0", path = "../runtime-test" } -sp-io = { version = "4.0.0", path = "../../../primitives/io" } +sp-io = { version = "5.0.0", path = "../../../primitives/io" } wat = "1.0" diff --git a/client/executor/wasmtime/src/host.rs b/client/executor/wasmtime/src/host.rs index 5da8ff3259031..b310ada24b629 100644 --- a/client/executor/wasmtime/src/host.rs +++ b/client/executor/wasmtime/src/host.rs @@ -45,6 +45,7 @@ unsafe impl Send for SandboxStore {} pub struct HostState { sandbox_store: SandboxStore, allocator: FreeingBumpHeapAllocator, + panic_message: Option, } impl HostState { @@ -55,8 +56,14 @@ impl HostState { sandbox::SandboxBackend::TryWasmer, )))), allocator, + panic_message: None, } } + + /// Takes the error message out of the host state, leaving a `None` in its place. + pub fn take_panic_message(&mut self) -> Option { + self.panic_message.take() + } } /// A `HostContext` implements `FunctionContext` for making host calls from a Wasmtime @@ -134,6 +141,14 @@ impl<'a> sp_wasm_interface::FunctionContext for HostContext<'a> { fn sandbox(&mut self) -> &mut dyn Sandbox { self } + + fn register_panic_error_message(&mut self, message: &str) { + self.caller + .data_mut() + .host_state_mut() + .expect("host state is not empty when calling a function in wasm; qed") + .panic_message = Some(message.to_owned()); + } } impl<'a> Sandbox for HostContext<'a> { diff --git a/client/executor/wasmtime/src/instance_wrapper.rs b/client/executor/wasmtime/src/instance_wrapper.rs index af21a8080cd58..896b71cea21dd 100644 --- a/client/executor/wasmtime/src/instance_wrapper.rs +++ b/client/executor/wasmtime/src/instance_wrapper.rs @@ -21,7 +21,7 @@ use crate::runtime::{Store, StoreData}; use sc_executor_common::{ - error::{Error, Result}, + error::{Backtrace, Error, MessageWithBacktrace, Result}, wasm_runtime::InvokeMethod, }; use sp_wasm_interface::{HostFunctions, Pointer, Value, WordSize}; @@ -53,25 +53,51 @@ pub struct EntryPoint { impl EntryPoint { /// Call this entry point. - pub fn call( + pub(crate) fn call( &self, - ctx: impl AsContextMut, + store: &mut Store, data_ptr: Pointer, data_len: WordSize, ) -> Result { let data_ptr = u32::from(data_ptr); let data_len = u32::from(data_len); - fn handle_trap(err: wasmtime::Trap) -> Error { - Error::from(format!("Wasm execution trapped: {}", err)) - } - match self.call_type { EntryPointType::Direct { ref entrypoint } => - entrypoint.call(ctx, (data_ptr, data_len)).map_err(handle_trap), + entrypoint.call(&mut *store, (data_ptr, data_len)), EntryPointType::Wrapped { func, ref dispatcher } => - dispatcher.call(ctx, (func, data_ptr, data_len)).map_err(handle_trap), + dispatcher.call(&mut *store, (func, data_ptr, data_len)), } + .map_err(|trap| { + let host_state = store + .data_mut() + .host_state + .as_mut() + .expect("host state cannot be empty while a function is being called; qed"); + + // The logic to print out a backtrace is somewhat complicated, + // so let's get wasmtime to print it out for us. + let mut backtrace_string = trap.to_string(); + let suffix = "\nwasm backtrace:"; + if let Some(index) = backtrace_string.find(suffix) { + // Get rid of the error message and just grab the backtrace, + // since we're storing the error message ourselves separately. + backtrace_string.replace_range(0..index + suffix.len(), ""); + } + + let backtrace = Backtrace { backtrace_string }; + if let Some(error) = host_state.take_panic_message() { + Error::AbortedDueToPanic(MessageWithBacktrace { + message: error, + backtrace: Some(backtrace), + }) + } else { + Error::AbortedDueToTrap(MessageWithBacktrace { + message: trap.display_reason().to_string(), + backtrace: Some(backtrace), + }) + } + }) } pub fn direct( @@ -361,6 +387,33 @@ impl InstanceWrapper { return; } } + } else if #[cfg(target_os = "macos")] { + use std::sync::Once; + + unsafe { + let ptr = self.memory.data_ptr(&self.store); + let len = self.memory.data_size(&self.store); + + // On MacOS we can simply overwrite memory mapping. + if libc::mmap( + ptr as _, + len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_FIXED | libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) == libc::MAP_FAILED { + static LOGGED: Once = Once::new(); + LOGGED.call_once(|| { + log::warn!( + "Failed to decommit WASM instance memory through mmap: {}", + std::io::Error::last_os_error(), + ); + }); + } else { + return; + } + } } } @@ -377,3 +430,15 @@ impl InstanceWrapper { &mut self.store } } + +#[test] +fn decommit_works() { + let engine = wasmtime::Engine::default(); + let code = wat::parse_str("(module (memory (export \"memory\") 1 4))").unwrap(); + let module = Module::new(&engine, code).unwrap(); + let mut wrapper = InstanceWrapper::new::<()>(&module, 2, true, None).unwrap(); + unsafe { *wrapper.memory.data_ptr(&wrapper.store) = 42 }; + assert_eq!(unsafe { *wrapper.memory.data_ptr(&wrapper.store) }, 42); + wrapper.decommit(); + assert_eq!(unsafe { *wrapper.memory.data_ptr(&wrapper.store) }, 0); +} diff --git a/client/executor/wasmtime/src/tests.rs b/client/executor/wasmtime/src/tests.rs index 773e1d707a354..664d05f5387fc 100644 --- a/client/executor/wasmtime/src/tests.rs +++ b/client/executor/wasmtime/src/tests.rs @@ -17,7 +17,7 @@ // along with this program. If not, see . use codec::{Decode as _, Encode as _}; -use sc_executor_common::{runtime_blob::RuntimeBlob, wasm_runtime::WasmModule}; +use sc_executor_common::{error::Error, runtime_blob::RuntimeBlob, wasm_runtime::WasmModule}; use sc_runtime_test::wasm_binary_unwrap; use std::sync::Arc; @@ -158,11 +158,13 @@ fn test_stack_depth_reaching() { }; let mut instance = runtime.new_instance().expect("failed to instantiate a runtime"); - let err = instance.call_export("test-many-locals", &[]).unwrap_err(); - - assert!(format!("{:?}", err).starts_with( - "Other(\"Wasm execution trapped: wasm trap: wasm `unreachable` instruction executed" - )); + match instance.call_export("test-many-locals", &[]).unwrap_err() { + Error::AbortedDueToTrap(error) => { + let expected = "wasm trap: wasm `unreachable` instruction executed"; + assert_eq!(error.message, expected); + }, + error => panic!("unexpected error: {:?}", error), + } } #[test] diff --git a/client/finality-grandpa/Cargo.toml b/client/finality-grandpa/Cargo.toml index 3f9261c0c17af..6d4c3b13662dc 100644 --- a/client/finality-grandpa/Cargo.toml +++ b/client/finality-grandpa/Cargo.toml @@ -13,9 +13,8 @@ readme = "README.md" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] - [dependencies] -derive_more = "0.99.16" +thiserror = "1.0" dyn-clone = "1.0" fork-tree = { version = "3.0.0", path = "../../utils/fork-tree" } futures = "0.3.9" @@ -24,15 +23,15 @@ log = "0.4.8" parking_lot = "0.11.2" rand = "0.8.4" parity-scale-codec = { version = "2.3.1", features = ["derive"] } -sp-application-crypto = { version = "4.0.0", path = "../../primitives/application-crypto" } +sp-application-crypto = { version = "5.0.0", path = "../../primitives/application-crypto" } sp-arithmetic = { version = "4.0.0", path = "../../primitives/arithmetic" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } sc-chain-spec = { version = "4.0.0-dev", path = "../../client/chain-spec" } sc-utils = { version = "4.0.0-dev", path = "../utils" } sp-consensus = { version = "0.10.0-dev", path = "../../primitives/consensus/common" } sc-consensus = { version = "0.10.0-dev", path = "../consensus/common" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-keystore = { version = "0.10.0", path = "../../primitives/keystore" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-keystore = { version = "0.11.0", path = "../../primitives/keystore" } sp-api = { version = "4.0.0-dev", path = "../../primitives/api" } sc-telemetry = { version = "4.0.0-dev", path = "../telemetry" } sc-keystore = { version = "4.0.0-dev", path = "../keystore" } @@ -55,7 +54,7 @@ finality-grandpa = { version = "0.14.1", features = [ ] } sc-network = { version = "0.10.0-dev", path = "../network" } sc-network-test = { version = "0.8.0", path = "../network/test" } -sp-keyring = { version = "4.1.0-dev", path = "../../primitives/keyring" } +sp-keyring = { version = "5.0.0", path = "../../primitives/keyring" } substrate-test-runtime-client = { version = "2.0.0", path = "../../test-utils/runtime/client" } sp-tracing = { version = "4.0.0", path = "../../primitives/tracing" } tokio = "1.15" diff --git a/client/finality-grandpa/rpc/Cargo.toml b/client/finality-grandpa/rpc/Cargo.toml index be6dfc371e4ad..b544287a6002c 100644 --- a/client/finality-grandpa/rpc/Cargo.toml +++ b/client/finality-grandpa/rpc/Cargo.toml @@ -12,8 +12,8 @@ readme = "README.md" sc-finality-grandpa = { version = "0.10.0-dev", path = "../" } sc-rpc = { version = "4.0.0-dev", path = "../../rpc" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } finality-grandpa = { version = "0.14.4", features = ["derive-codec"] } jsonrpc-core = "18.0.0" jsonrpc-core-client = "18.0.0" @@ -23,7 +23,7 @@ futures = "0.3.16" serde = { version = "1.0.105", features = ["derive"] } serde_json = "1.0.50" log = "0.4.8" -derive_more = "0.99.2" +thiserror = "1.0" parity-scale-codec = { version = "2.0.0", features = ["derive"] } sc-client-api = { version = "4.0.0-dev", path = "../../api" } @@ -32,7 +32,7 @@ sc-block-builder = { version = "0.10.0-dev", path = "../../block-builder" } sc-rpc = { version = "4.0.0-dev", path = "../../rpc", features = [ "test-helpers", ] } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } sp-finality-grandpa = { version = "4.0.0-dev", path = "../../../primitives/finality-grandpa" } -sp-keyring = { version = "4.1.0-dev", path = "../../../primitives/keyring" } +sp-keyring = { version = "5.0.0", path = "../../../primitives/keyring" } substrate-test-runtime-client = { version = "2.0.0", path = "../../../test-utils/runtime/client" } diff --git a/client/finality-grandpa/rpc/src/error.rs b/client/finality-grandpa/rpc/src/error.rs index 1c1361bcaeda7..845b4d99dcc1a 100644 --- a/client/finality-grandpa/rpc/src/error.rs +++ b/client/finality-grandpa/rpc/src/error.rs @@ -16,21 +16,21 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -#[derive(derive_more::Display, derive_more::From)] +#[derive(Debug, thiserror::Error)] /// Top-level error type for the RPC handler pub enum Error { /// The GRANDPA RPC endpoint is not ready. - #[display(fmt = "GRANDPA RPC endpoint not ready")] + #[error("GRANDPA RPC endpoint not ready")] EndpointNotReady, /// GRANDPA reports the authority set id to be larger than 32-bits. - #[display(fmt = "GRANDPA reports authority set id unreasonably large")] + #[error("GRANDPA reports authority set id unreasonably large")] AuthoritySetIdReportedAsUnreasonablyLarge, /// GRANDPA reports voter state with round id or weights larger than 32-bits. - #[display(fmt = "GRANDPA reports voter state as unreasonably large")] + #[error("GRANDPA reports voter state as unreasonably large")] VoterStateReportsUnreasonablyLargeNumbers, /// GRANDPA prove finality failed. - #[display(fmt = "GRANDPA prove finality rpc failed: {}", _0)] - ProveFinalityFailed(sc_finality_grandpa::FinalityProofError), + #[error("GRANDPA prove finality rpc failed: {0}")] + ProveFinalityFailed(#[from] sc_finality_grandpa::FinalityProofError), } /// The error codes returned by jsonrpc. diff --git a/client/finality-grandpa/src/authorities.rs b/client/finality-grandpa/src/authorities.rs index aa8be83b9529a..033a1c4bbb239 100644 --- a/client/finality-grandpa/src/authorities.rs +++ b/client/finality-grandpa/src/authorities.rs @@ -32,23 +32,22 @@ use sp_finality_grandpa::{AuthorityId, AuthorityList}; use crate::SetId; /// Error type returned on operations on the `AuthoritySet`. -#[derive(Debug, derive_more::Display)] +#[derive(Debug, thiserror::Error)] pub enum Error { - #[display(fmt = "Invalid authority set, either empty or with an authority weight set to 0.")] + #[error("Invalid authority set, either empty or with an authority weight set to 0.")] InvalidAuthoritySet, - #[display(fmt = "Client error during ancestry lookup: {}", _0)] + #[error("Client error during ancestry lookup: {0}")] Client(E), - #[display(fmt = "Duplicate authority set change.")] + #[error("Duplicate authority set change.")] DuplicateAuthoritySetChange, - #[display(fmt = "Multiple pending forced authority set changes are not allowed.")] + #[error("Multiple pending forced authority set changes are not allowed.")] MultiplePendingForcedAuthoritySetChanges, - #[display( - fmt = "A pending forced authority set change could not be applied since it must be applied \ - after the pending standard change at #{}", - _0 + #[error( + "A pending forced authority set change could not be applied since it must be applied \ + after the pending standard change at #{0}" )] ForcedAuthoritySetChangeDependencyUnsatisfied(N), - #[display(fmt = "Invalid operation in the pending changes tree: {}", _0)] + #[error("Invalid operation in the pending changes tree: {0}")] ForkTree(fork_tree::Error), } diff --git a/client/finality-grandpa/src/aux_schema.rs b/client/finality-grandpa/src/aux_schema.rs index 2ec48a804c936..0ac9ba9e64bd2 100644 --- a/client/finality-grandpa/src/aux_schema.rs +++ b/client/finality-grandpa/src/aux_schema.rs @@ -100,7 +100,7 @@ where // previously we only supported at most one pending change per fork &|_, _| Ok(false), ) { - warn!(target: "afg", "Error migrating pending authority set change: {:?}.", err); + warn!(target: "afg", "Error migrating pending authority set change: {}", err); warn!(target: "afg", "Node is in a potentially inconsistent state."); } } diff --git a/client/finality-grandpa/src/environment.rs b/client/finality-grandpa/src/environment.rs index 81bb24f1a5eed..6ffcdc719a166 100644 --- a/client/finality-grandpa/src/environment.rs +++ b/client/finality-grandpa/src/environment.rs @@ -609,7 +609,7 @@ where let tree_route = match tree_route_res { Ok(tree_route) => tree_route, Err(e) => { - debug!(target: "afg", "Encountered error computing ancestry between block {:?} and base {:?}: {:?}", + debug!(target: "afg", "Encountered error computing ancestry between block {:?} and base {:?}: {}", block, base, e); return Err(GrandpaError::NotDescendent) @@ -1098,7 +1098,7 @@ where ) { warn!(target: "afg", "Detected prevote equivocation in the finality worker: {:?}", equivocation); if let Err(err) = self.report_equivocation(equivocation.into()) { - warn!(target: "afg", "Error reporting prevote equivocation: {:?}", err); + warn!(target: "afg", "Error reporting prevote equivocation: {}", err); } } @@ -1109,7 +1109,7 @@ where ) { warn!(target: "afg", "Detected precommit equivocation in the finality worker: {:?}", equivocation); if let Err(err) = self.report_equivocation(equivocation.into()) { - warn!(target: "afg", "Error reporting precommit equivocation: {:?}", err); + warn!(target: "afg", "Error reporting precommit equivocation: {}", err); } } } @@ -1224,7 +1224,7 @@ where .or_else(|| Some((target_header.hash(), *target_header.number()))) }, Err(e) => { - warn!(target: "afg", "Encountered error finding best chain containing {:?}: {:?}", block, e); + warn!(target: "afg", "Encountered error finding best chain containing {:?}: {}", block, e); None }, }; @@ -1293,7 +1293,7 @@ where ) { if let Some(sender) = justification_sender { if let Err(err) = sender.notify(justification) { - warn!(target: "afg", "Error creating justification for subscriber: {:?}", err); + warn!(target: "afg", "Error creating justification for subscriber: {}", err); } } } @@ -1344,7 +1344,7 @@ where client .apply_finality(import_op, BlockId::Hash(hash), persisted_justification, true) .map_err(|e| { - warn!(target: "afg", "Error applying finality to block {:?}: {:?}", (hash, number), e); + warn!(target: "afg", "Error applying finality to block {:?}: {}", (hash, number), e); e })?; diff --git a/client/finality-grandpa/src/finality_proof.rs b/client/finality-grandpa/src/finality_proof.rs index cc6853bee3b07..03a4f2ff450a3 100644 --- a/client/finality-grandpa/src/finality_proof.rs +++ b/client/finality-grandpa/src/finality_proof.rs @@ -132,17 +132,18 @@ pub struct FinalityProof { } /// Errors occurring when trying to prove finality -#[derive(Debug, derive_more::Display, derive_more::From)] +#[derive(Debug, thiserror::Error)] pub enum FinalityProofError { /// The requested block has not yet been finalized. - #[display(fmt = "Block not yet finalized")] + #[error("Block not yet finalized")] BlockNotYetFinalized, /// The requested block is not covered by authority set changes. Likely this means the block is /// in the latest authority set, and the subscription API is more appropriate. - #[display(fmt = "Block not covered by authority set changes")] + #[error("Block not covered by authority set changes")] BlockNotInAuthoritySetChanges, /// Errors originating from the client. - Client(sp_blockchain::Error), + #[error(transparent)] + Client(#[from] sp_blockchain::Error), } fn prove_finality( diff --git a/client/finality-grandpa/src/import.rs b/client/finality-grandpa/src/import.rs index 71d74045f4760..ae5839d0c24e6 100644 --- a/client/finality-grandpa/src/import.rs +++ b/client/finality-grandpa/src/import.rs @@ -598,7 +598,7 @@ where Err(e) => { debug!( target: "afg", - "Restoring old authority set after block import error: {:?}", + "Restoring old authority set after block import error: {}", e, ); pending_changes.revert(); @@ -663,8 +663,12 @@ where import_res.unwrap_or_else(|err| { if needs_justification { - debug!(target: "afg", "Imported block #{} that enacts authority set change with \ - invalid justification: {:?}, requesting justification from peers.", number, err); + debug!( + target: "afg", + "Requesting justification from peers due to imported block #{} that enacts authority set change with invalid justification: {}", + number, + err + ); imported_aux.bad_justification = true; imported_aux.needs_justification = true; } diff --git a/client/finality-grandpa/src/lib.rs b/client/finality-grandpa/src/lib.rs index b99f6c0544197..8316e56b5b5e5 100644 --- a/client/finality-grandpa/src/lib.rs +++ b/client/finality-grandpa/src/lib.rs @@ -275,23 +275,38 @@ impl Config { } /// Errors that can occur while voting in GRANDPA. -#[derive(Debug)] +#[derive(Debug, thiserror::Error)] pub enum Error { /// An error within grandpa. + #[error("grandpa error: {0}")] Grandpa(GrandpaError), + /// A network error. + #[error("network error: {0}")] Network(String), + /// A blockchain error. + #[error("blockchain error: {0}")] Blockchain(String), + /// Could not complete a round on disk. + #[error("could not complete a round on disk: {0}")] Client(ClientError), + /// Could not sign outgoing message + #[error("could not sign outgoing message: {0}")] Signing(String), + /// An invariant has been violated (e.g. not finalizing pending change blocks in-order) + #[error("safety invariant has been violated: {0}")] Safety(String), + /// A timer failed to fire. + #[error("a timer failed to fire: {0}")] Timer(io::Error), + /// A runtime api request failed. + #[error("runtime API request failed: {0}")] RuntimeApi(sp_api::ApiError), } @@ -322,7 +337,7 @@ where { fn block_number(&self, hash: Block::Hash) -> Result>, Error> { self.block_number_from_id(&BlockId::Hash(hash)) - .map_err(|e| Error::Blockchain(format!("{:?}", e))) + .map_err(|e| Error::Blockchain(e.to_string())) } } @@ -459,7 +474,7 @@ impl ::std::error::Error for CommandOrError impl fmt::Display for CommandOrError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - CommandOrError::Error(ref e) => write!(f, "{:?}", e), + CommandOrError::Error(ref e) => write!(f, "{}", e), CommandOrError::VoterCommand(ref cmd) => write!(f, "{}", cmd), } } @@ -838,7 +853,7 @@ where Ok(()) => error!(target: "afg", "GRANDPA voter future has concluded naturally, this should be unreachable." ), - Err(e) => error!(target: "afg", "GRANDPA voter error: {:?}", e), + Err(e) => error!(target: "afg", "GRANDPA voter error: {}", e), }); // Make sure that `telemetry_task` doesn't accidentally finish and kill grandpa. diff --git a/client/finality-grandpa/src/observer.rs b/client/finality-grandpa/src/observer.rs index ab0c69ef7fc26..a7c951cc33db9 100644 --- a/client/finality-grandpa/src/observer.rs +++ b/client/finality-grandpa/src/observer.rs @@ -203,7 +203,7 @@ where ); let observer_work = observer_work.map_ok(|_| ()).map_err(|e| { - warn!("GRANDPA Observer failed: {:?}", e); + warn!("GRANDPA Observer failed: {}", e); }); Ok(observer_work.map(drop)) diff --git a/client/finality-grandpa/src/warp_proof.rs b/client/finality-grandpa/src/warp_proof.rs index 39d570d22bd7d..bdb8e36373de3 100644 --- a/client/finality-grandpa/src/warp_proof.rs +++ b/client/finality-grandpa/src/warp_proof.rs @@ -34,26 +34,25 @@ use sp_runtime::{ use std::{collections::HashMap, sync::Arc}; /// Warp proof processing error. -#[derive(Debug, derive_more::Display, derive_more::From)] +#[derive(Debug, thiserror::Error)] pub enum Error { /// Decoding error. - #[display(fmt = "Failed to decode block hash: {}.", _0)] - DecodeScale(codec::Error), + #[error("Failed to decode block hash: {0}.")] + DecodeScale(#[from] codec::Error), /// Client backend error. - Client(sp_blockchain::Error), + #[error("{0}")] + Client(#[from] sp_blockchain::Error), /// Invalid request data. - #[from(ignore)] + #[error("{0}")] InvalidRequest(String), /// Invalid warp proof. - #[from(ignore)] + #[error("{0}")] InvalidProof(String), /// Missing header or authority set change data. - #[display(fmt = "Missing required data to be able to answer request.")] + #[error("Missing required data to be able to answer request.")] MissingData, } -impl std::error::Error for Error {} - /// The maximum size in bytes of the `WarpSyncProof`. pub(super) const MAX_WARP_SYNC_PROOF_SIZE: usize = 8 * 1024 * 1024; diff --git a/client/informant/Cargo.toml b/client/informant/Cargo.toml index ce7fe31648a19..78ee90823f226 100644 --- a/client/informant/Cargo.toml +++ b/client/informant/Cargo.toml @@ -21,5 +21,5 @@ parity-util-mem = { version = "0.10.2", default-features = false, features = ["p sc-client-api = { version = "4.0.0-dev", path = "../api" } sc-network = { version = "0.10.0-dev", path = "../network" } sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } sc-transaction-pool-api = { version = "4.0.0-dev", path = "../transaction-pool/api" } diff --git a/client/keystore/Cargo.toml b/client/keystore/Cargo.toml index 7fe9e182efbdf..4d67be4167dd1 100644 --- a/client/keystore/Cargo.toml +++ b/client/keystore/Cargo.toml @@ -16,10 +16,10 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] async-trait = "0.1.50" -derive_more = "0.99.16" -sp-application-crypto = { version = "4.0.0", path = "../../primitives/application-crypto" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-keystore = { version = "0.10.0", path = "../../primitives/keystore" } +thiserror = "1.0" +sp-application-crypto = { version = "5.0.0", path = "../../primitives/application-crypto" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-keystore = { version = "0.11.0", path = "../../primitives/keystore" } hex = "0.4.0" parking_lot = "0.11.2" serde_json = "1.0.74" diff --git a/client/keystore/src/lib.rs b/client/keystore/src/lib.rs index 359326bb4cae0..cf94a16f08d86 100644 --- a/client/keystore/src/lib.rs +++ b/client/keystore/src/lib.rs @@ -28,29 +28,31 @@ mod local; pub use local::LocalKeystore; /// Keystore error. -#[derive(Debug, derive_more::Display, derive_more::From)] +#[derive(Debug, thiserror::Error)] pub enum Error { /// IO error. - Io(io::Error), + #[error(transparent)] + Io(#[from] io::Error), /// JSON error. - Json(serde_json::Error), + #[error(transparent)] + Json(#[from] serde_json::Error), /// Invalid password. - #[display( - fmt = "Requested public key and public key of the loaded private key do not match. \n + #[error( + "Requested public key and public key of the loaded private key do not match. \n This means either that the keystore password is incorrect or that the private key was stored under a wrong public key." )] PublicKeyMismatch, /// Invalid BIP39 phrase - #[display(fmt = "Invalid recovery phrase (BIP39) data")] + #[error("Invalid recovery phrase (BIP39) data")] InvalidPhrase, /// Invalid seed - #[display(fmt = "Invalid seed")] + #[error("Invalid seed")] InvalidSeed, /// Public key type is not supported - #[display(fmt = "Key crypto type is not supported")] + #[error("Key crypto type is not supported")] KeyNotSupported(KeyTypeId), /// Keystore unavailable - #[display(fmt = "Keystore unavailable")] + #[error("Keystore unavailable")] Unavailable, } @@ -69,13 +71,3 @@ impl From for TraitError { } } } - -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Error::Io(ref err) => Some(err), - Error::Json(ref err) => Some(err), - _ => None, - } - } -} diff --git a/client/network-gossip/Cargo.toml b/client/network-gossip/Cargo.toml index 9523e32f99e06..7952d97193ea9 100644 --- a/client/network-gossip/Cargo.toml +++ b/client/network-gossip/Cargo.toml @@ -22,7 +22,7 @@ log = "0.4.8" lru = "0.7.0" prometheus-endpoint = { package = "substrate-prometheus-endpoint", version = "0.10.0-dev", path = "../../utils/prometheus" } sc-network = { version = "0.10.0-dev", path = "../network" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } tracing = "0.1.29" [dev-dependencies] diff --git a/client/network/Cargo.toml b/client/network/Cargo.toml index f378b75990cb9..86a0380280471 100644 --- a/client/network/Cargo.toml +++ b/client/network/Cargo.toml @@ -25,7 +25,6 @@ bytes = "1" codec = { package = "parity-scale-codec", version = "2.0.0", features = [ "derive", ] } -derive_more = "0.99.16" either = "1.5.3" fnv = "1.0.6" fork-tree = { version = "3.0.0", path = "../../utils/fork-tree" } @@ -46,18 +45,18 @@ rand = "0.7.2" sc-block-builder = { version = "0.10.0-dev", path = "../block-builder" } sc-client-api = { version = "4.0.0-dev", path = "../api" } sc-peerset = { version = "4.0.0-dev", path = "../peerset" } -serde = { version = "1.0.132", features = ["derive"] } +serde = { version = "1.0.136", features = ["derive"] } serde_json = "1.0.74" smallvec = "1.7.0" sp-arithmetic = { version = "4.0.0", path = "../../primitives/arithmetic" } sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } sp-consensus = { version = "0.10.0-dev", path = "../../primitives/consensus/common" } sc-consensus = { version = "0.10.0-dev", path = "../consensus/common" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } sc-utils = { version = "4.0.0-dev", path = "../utils" } sp-finality-grandpa = { version = "4.0.0-dev", path = "../../primitives/finality-grandpa" } -thiserror = "1" +thiserror = "1.0" unsigned-varint = { version = "0.6.0", features = [ "futures", "asynchronous_codec", diff --git a/client/network/src/bitswap.rs b/client/network/src/bitswap.rs index e6cb1d9d79e3a..e7c37968b5f99 100644 --- a/client/network/src/bitswap.rs +++ b/client/network/src/bitswap.rs @@ -313,21 +313,29 @@ impl NetworkBehaviour for Bitswap { } /// Bitswap protocol error. -#[derive(derive_more::Display, derive_more::From)] +#[derive(Debug, thiserror::Error)] pub enum BitswapError { /// Protobuf decoding error. - #[display(fmt = "Failed to decode request: {}.", _0)] - DecodeProto(prost::DecodeError), + #[error("Failed to decode request: {0}.")] + DecodeProto(#[from] prost::DecodeError), + /// Protobuf encoding error. - #[display(fmt = "Failed to encode response: {}.", _0)] - EncodeProto(prost::EncodeError), + #[error("Failed to encode response: {0}.")] + EncodeProto(#[from] prost::EncodeError), + /// Client backend error. - Client(sp_blockchain::Error), + #[error(transparent)] + Client(#[from] sp_blockchain::Error), + /// Error parsing CID - BadCid(cid::Error), + #[error(transparent)] + BadCid(#[from] cid::Error), + /// Packet read error. - Read(io::Error), + #[error(transparent)] + Read(#[from] io::Error), + /// Error sending response. - #[display(fmt = "Failed to send response.")] + #[error("Failed to send response.")] SendResponse, } diff --git a/client/network/src/block_request_handler.rs b/client/network/src/block_request_handler.rs index 9d963480a7e01..2f17cdac0744b 100644 --- a/client/network/src/block_request_handler.rs +++ b/client/network/src/block_request_handler.rs @@ -379,19 +379,20 @@ impl BlockRequestHandler { } } -#[derive(derive_more::Display, derive_more::From)] +#[derive(Debug, thiserror::Error)] enum HandleRequestError { - #[display(fmt = "Failed to decode request: {}.", _0)] - DecodeProto(prost::DecodeError), - #[display(fmt = "Failed to encode response: {}.", _0)] - EncodeProto(prost::EncodeError), - #[display(fmt = "Failed to decode block hash: {}.", _0)] - DecodeScale(codec::Error), - #[display(fmt = "Missing `BlockRequest::from_block` field.")] + #[error("Failed to decode request: {0}.")] + DecodeProto(#[from] prost::DecodeError), + #[error("Failed to encode response: {0}.")] + EncodeProto(#[from] prost::EncodeError), + #[error("Failed to decode block hash: {0}.")] + DecodeScale(#[from] codec::Error), + #[error("Missing `BlockRequest::from_block` field.")] MissingFromField, - #[display(fmt = "Failed to parse BlockRequest::direction.")] + #[error("Failed to parse BlockRequest::direction.")] ParseDirection, - Client(sp_blockchain::Error), - #[display(fmt = "Failed to send response.")] + #[error(transparent)] + Client(#[from] sp_blockchain::Error), + #[error("Failed to send response.")] SendResponse, } diff --git a/client/network/src/error.rs b/client/network/src/error.rs index 1dafddd7bcc55..716235193a80f 100644 --- a/client/network/src/error.rs +++ b/client/network/src/error.rs @@ -27,18 +27,18 @@ use std::{borrow::Cow, fmt}; pub type Result = std::result::Result; /// Error type for the network. -#[derive(derive_more::Display, derive_more::From)] +#[derive(thiserror::Error)] pub enum Error { /// Io error - Io(std::io::Error), + #[error(transparent)] + Io(#[from] std::io::Error), + /// Client error - Client(Box), + #[error(transparent)] + Client(#[from] Box), /// The same bootnode (based on address) is registered with two different peer ids. - #[display( - fmt = "The same bootnode (`{}`) is registered with two different peer ids: `{}` and `{}`", - address, - first_id, - second_id + #[error( + "The same bootnode (`{address}`) is registered with two different peer ids: `{first_id}` and `{second_id}`" )] DuplicateBootnode { /// The address of the bootnode. @@ -49,11 +49,11 @@ pub enum Error { second_id: PeerId, }, /// Prometheus metrics error. - Prometheus(prometheus_endpoint::PrometheusError), + #[error(transparent)] + Prometheus(#[from] prometheus_endpoint::PrometheusError), /// The network addresses are invalid because they don't match the transport. - #[display( - fmt = "The following addresses are invalid because they don't match the transport: {:?}", - addresses + #[error( + "The following addresses are invalid because they don't match the transport: {addresses:?}" )] AddressesForAnotherTransport { /// Transport used. @@ -62,7 +62,7 @@ pub enum Error { addresses: Vec, }, /// The same request-response protocol has been registered multiple times. - #[display(fmt = "Request-response protocol registered multiple times: {}", protocol)] + #[error("Request-response protocol registered multiple times: {protocol}")] DuplicateRequestResponseProtocol { /// Name of the protocol registered multiple times. protocol: Cow<'static, str>, @@ -75,16 +75,3 @@ impl fmt::Debug for Error { fmt::Display::fmt(self, f) } } - -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::Io(ref err) => Some(err), - Self::Client(ref err) => Some(err), - Self::Prometheus(ref err) => Some(err), - Self::DuplicateBootnode { .. } | - Self::AddressesForAnotherTransport { .. } | - Self::DuplicateRequestResponseProtocol { .. } => None, - } - } -} diff --git a/client/network/src/light_client_requests/handler.rs b/client/network/src/light_client_requests/handler.rs index b5c6ccb196d5b..fb258304f2e8f 100644 --- a/client/network/src/light_client_requests/handler.rs +++ b/client/network/src/light_client_requests/handler.rs @@ -284,20 +284,20 @@ impl LightClientRequestHandler { } } -#[derive(derive_more::Display, derive_more::From)] +#[derive(Debug, thiserror::Error)] enum HandleRequestError { - #[display(fmt = "Failed to decode request: {}.", _0)] - DecodeProto(prost::DecodeError), - #[display(fmt = "Failed to encode response: {}.", _0)] - EncodeProto(prost::EncodeError), - #[display(fmt = "Failed to send response.")] + #[error("Failed to decode request: {0}.")] + DecodeProto(#[from] prost::DecodeError), + #[error("Failed to encode response: {0}.")] + EncodeProto(#[from] prost::EncodeError), + #[error("Failed to send response.")] SendResponse, /// A bad request has been received. - #[display(fmt = "bad request: {}", _0)] + #[error("bad request: {0}")] BadRequest(&'static str), /// Encoding or decoding of some data failed. - #[display(fmt = "codec error: {}", _0)] - Codec(codec::Error), + #[error("codec error: {0}")] + Codec(#[from] codec::Error), } fn fmt_keys(first: Option<&Vec>, last: Option<&Vec>) -> String { diff --git a/client/network/src/protocol.rs b/client/network/src/protocol.rs index 5541a0145366f..b39d0d1b8428b 100644 --- a/client/network/src/protocol.rs +++ b/client/network/src/protocol.rs @@ -886,7 +886,7 @@ impl Protocol { return }, Err(e) => { - warn!("Error reading block header {}: {:?}", hash, e); + warn!("Error reading block header {}: {}", hash, e); return }, }; diff --git a/client/network/src/protocol/notifications/handler.rs b/client/network/src/protocol/notifications/handler.rs index 158ab2ae379c6..91225f54203af 100644 --- a/client/network/src/protocol/notifications/handler.rs +++ b/client/network/src/protocol/notifications/handler.rs @@ -457,9 +457,9 @@ impl<'a> Ready<'a> { } /// Error specific to the collection of protocols. -#[derive(Debug, derive_more::Display, derive_more::Error)] +#[derive(Debug, thiserror::Error)] pub enum NotifsHandlerError { - /// Channel of synchronous notifications is full. + #[error("Channel of synchronous notifications is full.")] SyncNotificationsClogged, } diff --git a/client/network/src/protocol/notifications/upgrade/notifications.rs b/client/network/src/protocol/notifications/upgrade/notifications.rs index 5171d459fa400..53270975a5b0d 100644 --- a/client/network/src/protocol/notifications/upgrade/notifications.rs +++ b/client/network/src/protocol/notifications/upgrade/notifications.rs @@ -457,13 +457,14 @@ where } /// Error generated by sending on a notifications out substream. -#[derive(Debug, derive_more::From, derive_more::Display)] +#[derive(Debug, thiserror::Error)] pub enum NotificationsHandshakeError { /// I/O error on the substream. - Io(io::Error), + #[error(transparent)] + Io(#[from] io::Error), /// Initial message or handshake was too large. - #[display(fmt = "Initial message or handshake was too large: {}", requested)] + #[error("Initial message or handshake was too large: {requested}")] TooLarge { /// Size requested by the remote. requested: usize, @@ -472,7 +473,8 @@ pub enum NotificationsHandshakeError { }, /// Error while decoding the variable-length integer. - VarintDecode(unsigned_varint::decode::Error), + #[error(transparent)] + VarintDecode(#[from] unsigned_varint::decode::Error), } impl From for NotificationsHandshakeError { @@ -489,10 +491,11 @@ impl From for NotificationsHandshakeError { } /// Error generated by sending on a notifications out substream. -#[derive(Debug, derive_more::From, derive_more::Display)] +#[derive(Debug, thiserror::Error)] pub enum NotificationsOutError { /// I/O error on the substream. - Io(io::Error), + #[error(transparent)] + Io(#[from] io::Error), } #[cfg(test)] diff --git a/client/network/src/protocol/sync.rs b/client/network/src/protocol/sync.rs index fbb4e376b1b4f..d98c0d2c04abe 100644 --- a/client/network/src/protocol/sync.rs +++ b/client/network/src/protocol/sync.rs @@ -665,7 +665,7 @@ impl ChainSync { // There is nothing sync can get from the node that has no blockchain data. match self.block_status(&best_hash) { Err(e) => { - debug!(target:"sync", "Error reading blockchain: {:?}", e); + debug!(target:"sync", "Error reading blockchain: {}", e); Err(BadPeer(who, rep::BLOCKCHAIN_READ_ERROR)) }, Ok(BlockStatus::KnownBad) => { @@ -1192,7 +1192,7 @@ impl ChainSync { (_, Err(e)) => { info!( target: "sync", - "❌ Error answering legitimate blockchain query: {:?}", + "❌ Error answering legitimate blockchain query: {}", e, ); return Err(BadPeer(*who, rep::BLOCKCHAIN_READ_ERROR)) @@ -1629,7 +1629,7 @@ impl ChainSync { trace!(target: "sync", "Obsolete block {:?}", hash); }, e @ Err(BlockImportError::UnknownParent) | e @ Err(BlockImportError::Other(_)) => { - warn!(target: "sync", "💔 Error importing block {:?}: {:?}", hash, e); + warn!(target: "sync", "💔 Error importing block {:?}: {}", hash, e.unwrap_err()); self.state_sync = None; self.warp_sync = None; output.extend(self.restart()); @@ -1683,7 +1683,7 @@ impl ChainSync { if let Err(err) = r { warn!( target: "sync", - "💔 Error cleaning up pending extra justification data requests: {:?}", + "💔 Error cleaning up pending extra justification data requests: {}", err, ); } @@ -2081,7 +2081,7 @@ impl ChainSync { ) -> impl Iterator), BadPeer>> + 'a { self.blocks.clear(); if let Err(e) = self.reset_sync_start_point() { - warn!(target: "sync", "💔 Unable to restart sync. :{:?}", e); + warn!(target: "sync", "💔 Unable to restart sync: {}", e); } self.pending_requests.set_all(); debug!(target:"sync", "Restarted with {} ({})", self.best_queued_number, self.best_queued_hash); diff --git a/client/network/src/protocol/sync/extra_requests.rs b/client/network/src/protocol/sync/extra_requests.rs index 680094a74143e..d0bfebab66010 100644 --- a/client/network/src/protocol/sync/extra_requests.rs +++ b/client/network/src/protocol/sync/extra_requests.rs @@ -108,7 +108,7 @@ impl ExtraRequests { // ignore the `Revert` error. }, Err(err) => { - debug!(target: "sync", "Failed to insert request {:?} into tree: {:?}", request, err); + debug!(target: "sync", "Failed to insert request {:?} into tree: {}", request, err); }, _ => (), } @@ -173,9 +173,7 @@ impl ExtraRequests { } if best_finalized_number > self.best_seen_finalized_number { - // normally we'll receive finality notifications for every block => finalize would be - // enough but if many blocks are finalized at once, some notifications may be omitted - // => let's use finalize_with_ancestors here + // we receive finality notification only for the finalized branch head. match self.tree.finalize_with_ancestors( best_finalized_hash, best_finalized_number, diff --git a/client/network/src/protocol/sync/state.rs b/client/network/src/protocol/sync/state.rs index 3de165b83d9e0..0df862a48333f 100644 --- a/client/network/src/protocol/sync/state.rs +++ b/client/network/src/protocol/sync/state.rs @@ -99,7 +99,7 @@ impl StateSync { Err(e) => { debug!( target: "sync", - "StateResponse failed proof verification: {:?}", + "StateResponse failed proof verification: {}", e, ); return ImportResult::BadResponse diff --git a/client/network/src/protocol/sync/warp.rs b/client/network/src/protocol/sync/warp.rs index 6c51d4b3495f0..f12deb2dbb432 100644 --- a/client/network/src/protocol/sync/warp.rs +++ b/client/network/src/protocol/sync/warp.rs @@ -88,7 +88,7 @@ impl WarpSync { Phase::WarpProof { set_id, authorities, last_hash } => { match self.warp_sync_provider.verify(&response, *set_id, authorities.clone()) { Err(e) => { - log::debug!(target: "sync", "Bad warp proof response: {:?}", e); + log::debug!(target: "sync", "Bad warp proof response: {}", e); return WarpProofImportResult::BadResponse }, Ok(VerificationResult::Partial(new_set_id, new_authorities, new_last_hash)) => { diff --git a/client/network/src/request_responses.rs b/client/network/src/request_responses.rs index 24b3d3df00b2d..58007c7bc5ce1 100644 --- a/client/network/src/request_responses.rs +++ b/client/network/src/request_responses.rs @@ -884,34 +884,35 @@ impl NetworkBehaviour for RequestResponsesBehaviour { } /// Error when registering a protocol. -#[derive(Debug, derive_more::Display, derive_more::Error)] +#[derive(Debug, thiserror::Error)] pub enum RegisterError { /// A protocol has been specified multiple times. - DuplicateProtocol(#[error(ignore)] Cow<'static, str>), + #[error("{0}")] + DuplicateProtocol(Cow<'static, str>), } /// Error in a request. -#[derive(Debug, derive_more::Display, derive_more::Error)] +#[derive(Debug, thiserror::Error)] +#[allow(missing_docs)] pub enum RequestFailure { - /// We are not currently connected to the requested peer. + #[error("We are not currently connected to the requested peer.")] NotConnected, - /// Given protocol hasn't been registered. + #[error("Given protocol hasn't been registered.")] UnknownProtocol, - /// Remote has closed the substream before answering, thereby signaling that it considers the - /// request as valid, but refused to answer it. + #[error("Remote has closed the substream before answering, thereby signaling that it considers the request as valid, but refused to answer it.")] Refused, - /// The remote replied, but the local node is no longer interested in the response. + #[error("The remote replied, but the local node is no longer interested in the response.")] Obsolete, /// Problem on the network. - #[display(fmt = "Problem on the network: {}", _0)] + #[error("Problem on the network: {0}")] Network(OutboundFailure), } /// Error when processing a request sent by a remote. -#[derive(Debug, derive_more::Display, derive_more::Error)] +#[derive(Debug, thiserror::Error)] pub enum ResponseFailure { /// Problem on the network. - #[display(fmt = "Problem on the network: {}", _0)] + #[error("Problem on the network: {0}")] Network(InboundFailure), } diff --git a/client/network/src/service.rs b/client/network/src/service.rs index 9c8c58ef49e4d..b6a1d3c88e7f3 100644 --- a/client/network/src/service.rs +++ b/client/network/src/service.rs @@ -1391,7 +1391,7 @@ impl<'a> NotificationSenderReady<'a> { } /// Error returned by [`NetworkService::send_notification`]. -#[derive(Debug, derive_more::Display, derive_more::Error)] +#[derive(Debug, thiserror::Error)] pub enum NotificationSenderError { /// The notification receiver has been closed, usually because the underlying connection /// closed. @@ -1399,8 +1399,10 @@ pub enum NotificationSenderError { /// Some of the notifications most recently sent may not have been received. However, /// the peer may still be connected and a new `NotificationSender` for the same /// protocol obtained from [`NetworkService::notification_sender`]. + #[error("The notification receiver has been closed")] Closed, /// Protocol name hasn't been registered. + #[error("Protocol name hasn't been registered")] BadProtocol, } diff --git a/client/network/src/state_request_handler.rs b/client/network/src/state_request_handler.rs index 89f1f2b363c4c..10a77061a031d 100644 --- a/client/network/src/state_request_handler.rs +++ b/client/network/src/state_request_handler.rs @@ -241,15 +241,20 @@ impl StateRequestHandler { } } -#[derive(derive_more::Display, derive_more::From)] +#[derive(Debug, thiserror::Error)] enum HandleRequestError { - #[display(fmt = "Failed to decode request: {}.", _0)] - DecodeProto(prost::DecodeError), - #[display(fmt = "Failed to encode response: {}.", _0)] - EncodeProto(prost::EncodeError), - #[display(fmt = "Failed to decode block hash: {}.", _0)] - InvalidHash(codec::Error), - Client(sp_blockchain::Error), - #[display(fmt = "Failed to send response.")] + #[error("Failed to decode request: {0}.")] + DecodeProto(#[from] prost::DecodeError), + + #[error("Failed to encode response: {0}.")] + EncodeProto(#[from] prost::EncodeError), + + #[error("Failed to decode block hash: {0}.")] + InvalidHash(#[from] codec::Error), + + #[error(transparent)] + Client(#[from] sp_blockchain::Error), + + #[error("Failed to send response.")] SendResponse, } diff --git a/client/network/src/warp_request_handler.rs b/client/network/src/warp_request_handler.rs index ca5a93b752b62..4c839825ff5ec 100644 --- a/client/network/src/warp_request_handler.rs +++ b/client/network/src/warp_request_handler.rs @@ -149,18 +149,23 @@ impl RequestHandler { } } -#[derive(Debug, derive_more::Display, derive_more::From)] +#[derive(Debug, thiserror::Error)] enum HandleRequestError { - #[display(fmt = "Failed to decode request: {}.", _0)] - DecodeProto(prost::DecodeError), - #[display(fmt = "Failed to encode response: {}.", _0)] - EncodeProto(prost::EncodeError), - #[display(fmt = "Failed to decode block hash: {}.", _0)] - DecodeScale(codec::Error), - Client(sp_blockchain::Error), - #[from(ignore)] - #[display(fmt = "Invalid request {}.", _0)] - InvalidRequest(Box), - #[display(fmt = "Failed to send response.")] + #[error("Failed to decode request: {0}.")] + DecodeProto(#[from] prost::DecodeError), + + #[error("Failed to encode response: {0}.")] + EncodeProto(#[from] prost::EncodeError), + + #[error("Failed to decode block hash: {0}.")] + DecodeScale(#[from] codec::Error), + + #[error(transparent)] + Client(#[from] sp_blockchain::Error), + + #[error("Invalid request {0}.")] + InvalidRequest(#[from] Box), + + #[error("Failed to send response.")] SendResponse, } diff --git a/client/network/test/Cargo.toml b/client/network/test/Cargo.toml index 6b6d777e7396e..2750c613d42a2 100644 --- a/client/network/test/Cargo.toml +++ b/client/network/test/Cargo.toml @@ -25,8 +25,8 @@ sp-consensus = { version = "0.10.0-dev", path = "../../../primitives/consensus/c sc-consensus = { version = "0.10.0-dev", path = "../../consensus/common" } sc-client-api = { version = "4.0.0-dev", path = "../../api" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } sc-block-builder = { version = "0.10.0-dev", path = "../../block-builder" } sp-consensus-babe = { version = "0.10.0-dev", path = "../../../primitives/consensus/babe" } substrate-test-runtime-client = { version = "2.0.0", path = "../../../test-utils/runtime/client" } diff --git a/client/network/test/src/lib.rs b/client/network/test/src/lib.rs index 1e1c7adf2c519..3986ac47f3616 100644 --- a/client/network/test/src/lib.rs +++ b/client/network/test/src/lib.rs @@ -1000,14 +1000,10 @@ where peer.network.service().announce_block(notification.hash, None); } - // We poll `finality_notification_stream`, but we only take the last event. - let mut last = None; - while let Poll::Ready(Some(item)) = + // We poll `finality_notification_stream`. + while let Poll::Ready(Some(notification)) = peer.finality_notification_stream.as_mut().poll_next(cx) { - last = Some(item); - } - if let Some(notification) = last { peer.network.on_block_finalized(notification.hash, notification.header); } } diff --git a/client/offchain/Cargo.toml b/client/offchain/Cargo.toml index dd4bdb71f93b6..5cd823958eed4 100644 --- a/client/offchain/Cargo.toml +++ b/client/offchain/Cargo.toml @@ -25,9 +25,9 @@ rand = "0.7.2" sc-client-api = { version = "4.0.0-dev", path = "../api" } sc-network = { version = "0.10.0-dev", path = "../network" } sp-api = { version = "4.0.0-dev", path = "../../primitives/api" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } sp-offchain = { version = "4.0.0-dev", path = "../../primitives/offchain" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } sc-utils = { version = "4.0.0-dev", path = "../utils" } threadpool = "1.7" hyper = { version = "0.14.16", features = ["stream", "http2"] } diff --git a/client/offchain/src/lib.rs b/client/offchain/src/lib.rs index cc49c07bffcf4..8d016e945453b 100644 --- a/client/offchain/src/lib.rs +++ b/client/offchain/src/lib.rs @@ -194,7 +194,7 @@ where if let Err(e) = run { tracing::error!( target: LOG_TARGET, - "Error running offchain workers at {:?}: {:?}", + "Error running offchain workers at {:?}: {}", at, e ); diff --git a/client/proposer-metrics/src/lib.rs b/client/proposer-metrics/src/lib.rs index a34660faab5d3..c27d16ea04d7d 100644 --- a/client/proposer-metrics/src/lib.rs +++ b/client/proposer-metrics/src/lib.rs @@ -19,7 +19,8 @@ //! Prometheus basic proposer metrics. use prometheus_endpoint::{ - register, Gauge, Histogram, HistogramOpts, PrometheusError, Registry, U64, + prometheus::CounterVec, register, Gauge, Histogram, HistogramOpts, Opts, PrometheusError, + Registry, U64, }; /// Optional shareable link to basic authorship metrics. @@ -38,15 +39,24 @@ impl MetricsLink { } pub fn report(&self, do_this: impl FnOnce(&Metrics) -> O) -> Option { - Some(do_this(self.0.as_ref()?)) + self.0.as_ref().map(do_this) } } +/// The reason why proposing a block ended. +pub enum EndProposingReason { + NoMoreTransactions, + HitDeadline, + HitBlockSizeLimit, + HitBlockWeightLimit, +} + /// Authorship metrics. #[derive(Clone)] pub struct Metrics { pub block_constructed: Histogram, pub number_of_transactions: Gauge, + pub end_proposing_reason: CounterVec, pub create_inherents_time: Histogram, pub create_block_proposal_time: Histogram, } @@ -82,6 +92,28 @@ impl Metrics { ))?, registry, )?, + end_proposing_reason: register( + CounterVec::new( + Opts::new( + "substrate_proposer_end_proposal_reason", + "The reason why the block proposing was ended. This doesn't include errors.", + ), + &["reason"], + )?, + registry, + )?, }) } + + /// Report the reason why the proposing ended. + pub fn report_end_proposing_reason(&self, reason: EndProposingReason) { + let reason = match reason { + EndProposingReason::HitDeadline => "hit_deadline", + EndProposingReason::NoMoreTransactions => "no_more_transactions", + EndProposingReason::HitBlockSizeLimit => "hit_block_size_limit", + EndProposingReason::HitBlockWeightLimit => "hit_block_weight_limit", + }; + + self.end_proposing_reason.with_label_values(&[reason]).inc(); + } } diff --git a/client/rpc-api/Cargo.toml b/client/rpc-api/Cargo.toml index 4b2882ee827f7..00b2fa787ca6f 100644 --- a/client/rpc-api/Cargo.toml +++ b/client/rpc-api/Cargo.toml @@ -23,12 +23,12 @@ log = "0.4.8" parking_lot = "0.11.2" thiserror = "1.0" -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } sp-version = { version = "4.0.0-dev", path = "../../primitives/version" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } sc-chain-spec = { path = "../chain-spec", version = "4.0.0-dev" } -serde = { version = "1.0.132", features = ["derive"] } +serde = { version = "1.0.136", features = ["derive"] } serde_json = "1.0.74" sc-transaction-pool-api = { version = "4.0.0-dev", path = "../transaction-pool/api" } -sp-rpc = { version = "4.0.0-dev", path = "../../primitives/rpc" } +sp-rpc = { version = "5.0.0", path = "../../primitives/rpc" } sp-tracing = { version = "4.0.0", path = "../../primitives/tracing" } diff --git a/client/rpc-api/src/author/error.rs b/client/rpc-api/src/author/error.rs index 5b6bec7ed4bdc..eee77edd5e208 100644 --- a/client/rpc-api/src/author/error.rs +++ b/client/rpc-api/src/author/error.rs @@ -103,7 +103,7 @@ impl From for rpc::Error { Error::Verification(e) => rpc::Error { code: rpc::ErrorCode::ServerError(VERIFICATION_ERROR), message: format!("Verification Error: {}", e).into(), - data: Some(format!("{:?}", e).into()), + data: Some(e.to_string().into()), }, Error::Pool(PoolError::InvalidTransaction(InvalidTransaction::Custom(e))) => rpc::Error { code: rpc::ErrorCode::ServerError(POOL_INVALID_TX), diff --git a/client/rpc-api/src/errors.rs b/client/rpc-api/src/errors.rs index 42e563342fa4d..e59b1b0eda5ce 100644 --- a/client/rpc-api/src/errors.rs +++ b/client/rpc-api/src/errors.rs @@ -18,11 +18,11 @@ use log::warn; -pub fn internal(e: E) -> jsonrpc_core::Error { - warn!("Unknown error: {:?}", e); +pub fn internal(e: E) -> jsonrpc_core::Error { + warn!("Unknown error: {}", e); jsonrpc_core::Error { code: jsonrpc_core::ErrorCode::InternalError, message: "Unknown error occurred".into(), - data: Some(format!("{:?}", e).into()), + data: Some(e.to_string().into()), } } diff --git a/client/rpc/Cargo.toml b/client/rpc/Cargo.toml index 87fc263356a72..308d99bc4f376 100644 --- a/client/rpc/Cargo.toml +++ b/client/rpc/Cargo.toml @@ -20,16 +20,16 @@ codec = { package = "parity-scale-codec", version = "2.0.0" } futures = "0.3.16" jsonrpc-pubsub = "18.0.0" log = "0.4.8" -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } rpc = { package = "jsonrpc-core", version = "18.0.0" } sp-version = { version = "4.0.0-dev", path = "../../primitives/version" } serde_json = "1.0.74" sp-session = { version = "4.0.0-dev", path = "../../primitives/session" } sp-offchain = { version = "4.0.0-dev", path = "../../primitives/offchain" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } sc-utils = { version = "4.0.0-dev", path = "../utils" } -sp-rpc = { version = "4.0.0-dev", path = "../../primitives/rpc" } -sp-keystore = { version = "0.10.0", path = "../../primitives/keystore" } +sp-rpc = { version = "5.0.0", path = "../../primitives/rpc" } +sp-keystore = { version = "0.11.0", path = "../../primitives/keystore" } sc-chain-spec = { version = "4.0.0-dev", path = "../chain-spec" } sc-block-builder = { version = "0.10.0-dev", path = "../block-builder" } sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } @@ -43,7 +43,7 @@ sc-transaction-pool-api = { version = "4.0.0-dev", path = "../transaction-pool/a assert_matches = "1.3.0" lazy_static = "1.4.0" sc-network = { version = "0.10.0-dev", path = "../network" } -sp-io = { version = "4.0.0", path = "../../primitives/io" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } substrate-test-runtime-client = { version = "2.0.0", path = "../../test-utils/runtime/client" } sc-transaction-pool = { version = "4.0.0-dev", path = "../transaction-pool" } sp-consensus = { version = "0.10.0-dev", path = "../../primitives/consensus/common" } diff --git a/client/service/Cargo.toml b/client/service/Cargo.toml index f23bf3f55bbfe..8424fe31a810a 100644 --- a/client/service/Cargo.toml +++ b/client/service/Cargo.toml @@ -33,24 +33,24 @@ futures-timer = "3.0.1" exit-future = "0.2.0" pin-project = "1.0.10" hash-db = "0.15.2" -serde = "1.0.132" +serde = "1.0.136" serde_json = "1.0.74" sc-keystore = { version = "4.0.0-dev", path = "../keystore" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } -sp-trie = { version = "4.0.0", path = "../../primitives/trie" } -sp-externalities = { version = "0.10.0", path = "../../primitives/externalities" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } +sp-trie = { version = "5.0.0", path = "../../primitives/trie" } +sp-externalities = { version = "0.11.0", path = "../../primitives/externalities" } sc-utils = { version = "4.0.0-dev", path = "../utils" } sp-version = { version = "4.0.0-dev", path = "../../primitives/version" } sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-keystore = { version = "0.10.0", path = "../../primitives/keystore" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-keystore = { version = "0.11.0", path = "../../primitives/keystore" } sp-session = { version = "4.0.0-dev", path = "../../primitives/session" } -sp-state-machine = { version = "0.10.0", path = "../../primitives/state-machine" } -sp-application-crypto = { version = "4.0.0", path = "../../primitives/application-crypto" } +sp-state-machine = { version = "0.11.0", path = "../../primitives/state-machine" } +sp-application-crypto = { version = "5.0.0", path = "../../primitives/application-crypto" } sp-consensus = { version = "0.10.0-dev", path = "../../primitives/consensus/common" } sc-consensus = { version = "0.10.0-dev", path = "../../client/consensus/common" } sp-inherents = { version = "4.0.0-dev", path = "../../primitives/inherents" } -sp-storage = { version = "4.0.0", path = "../../primitives/storage" } +sp-storage = { version = "5.0.0", path = "../../primitives/storage" } sc-network = { version = "0.10.0-dev", path = "../network" } sc-chain-spec = { version = "4.0.0-dev", path = "../chain-spec" } sc-client-api = { version = "4.0.0-dev", path = "../api" } diff --git a/client/service/src/chain_ops/check_block.rs b/client/service/src/chain_ops/check_block.rs index e12766659d9a9..41a6c73c5f473 100644 --- a/client/service/src/chain_ops/check_block.rs +++ b/client/service/src/chain_ops/check_block.rs @@ -46,6 +46,6 @@ where import_blocks(client, import_queue, reader, true, true) }, Ok(None) => Box::pin(future::err("Unknown block".into())), - Err(e) => Box::pin(future::err(format!("Error reading block: {:?}", e).into())), + Err(e) => Box::pin(future::err(format!("Error reading block: {}", e).into())), } } diff --git a/client/service/src/chain_ops/import_blocks.rs b/client/service/src/chain_ops/import_blocks.rs index aa72b745c7cac..9d74fa1c276fa 100644 --- a/client/service/src/chain_ops/import_blocks.rs +++ b/client/service/src/chain_ops/import_blocks.rs @@ -322,7 +322,7 @@ where for result in results { if let (Err(err), hash) = result { - warn!("There was an error importing block with hash {:?}: {:?}", hash, err); + warn!("There was an error importing block with hash {:?}: {}", hash, err); self.has_error = true; break } diff --git a/client/service/src/client/call_executor.rs b/client/service/src/client/call_executor.rs index a806b2dbb6d49..f271b35a69ced 100644 --- a/client/service/src/client/call_executor.rs +++ b/client/service/src/client/call_executor.rs @@ -285,7 +285,7 @@ where state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?; self.executor .runtime_version(&mut ext, &runtime_code) - .map_err(|e| sp_blockchain::Error::VersionInvalid(format!("{:?}", e)).into()) + .map_err(|e| sp_blockchain::Error::VersionInvalid(e.to_string()).into()) } fn prove_execution( @@ -340,7 +340,7 @@ where Block: BlockT, { fn runtime_version(&self, at: &BlockId) -> Result { - CallExecutor::runtime_version(self, at).map_err(|e| format!("{:?}", e)) + CallExecutor::runtime_version(self, at).map_err(|e| e.to_string()) } } diff --git a/client/service/src/client/client.rs b/client/service/src/client/client.rs index 7673a7b4c5387..071af36a23f96 100644 --- a/client/service/src/client/client.rs +++ b/client/service/src/client/client.rs @@ -30,8 +30,8 @@ use rand::Rng; use sc_block_builder::{BlockBuilderApi, BlockBuilderProvider, RecordProof}; use sc_client_api::{ backend::{ - self, apply_aux, BlockImportOperation, ClientImportOperation, Finalizer, ImportSummary, - LockImportRun, NewBlockState, StorageProvider, + self, apply_aux, BlockImportOperation, ClientImportOperation, FinalizeSummary, Finalizer, + ImportSummary, LockImportRun, NewBlockState, StorageProvider, }, client::{ BadBlocks, BlockBackend, BlockImportNotification, BlockOf, BlockchainEvents, ClientInfo, @@ -274,7 +274,7 @@ where let mut op = ClientImportOperation { op: self.backend.begin_operation()?, notify_imported: None, - notify_finalized: Vec::new(), + notify_finalized: None, }; let r = f(&mut op)?; @@ -622,18 +622,6 @@ where None }, }; - // Ensure parent chain is finalized to maintain invariant that - // finality is called sequentially. This will also send finality - // notifications for top 250 newly finalized blocks. - if finalized && parent_exists { - self.apply_finality_with_block_hash( - operation, - parent_hash, - None, - info.best_hash, - make_notifications, - )?; - } operation.op.update_cache(new_cache); storage_changes @@ -641,6 +629,18 @@ where None => None, }; + // Ensure parent chain is finalized to maintain invariant that finality is called + // sequentially. + if finalized && parent_exists { + self.apply_finality_with_block_hash( + operation, + parent_hash, + None, + info.best_hash, + make_notifications, + )?; + } + let is_new_best = !gap_block && (finalized || match fork_choice { @@ -683,11 +683,36 @@ where operation.op.insert_aux(aux)?; - // we only notify when we are already synced to the tip of the chain + // We only notify when we are already synced to the tip of the chain // or if this import triggers a re-org if make_notifications || tree_route.is_some() { if finalized { - operation.notify_finalized.push(hash); + let mut summary = match operation.notify_finalized.take() { + Some(summary) => summary, + None => FinalizeSummary { finalized: Vec::new(), stale_heads: Vec::new() }, + }; + summary.finalized.push(hash); + if parent_exists { + // Add to the stale list all heads that are branching from parent besides our + // current `head`. + for head in self + .backend + .blockchain() + .leaves()? + .into_iter() + .filter(|h| *h != parent_hash) + { + let route_from_parent = sp_blockchain::tree_route( + self.backend.blockchain(), + parent_hash, + head, + )?; + if route_from_parent.retracted().is_empty() { + summary.stale_heads.push(head); + } + } + } + operation.notify_finalized = Some(summary); } operation.notify_imported = Some(ImportSummary { @@ -831,58 +856,82 @@ where operation.op.mark_finalized(BlockId::Hash(block), justification)?; if notify { - // sometimes when syncing, tons of blocks can be finalized at once. - // we'll send notifications spuriously in that case. - const MAX_TO_NOTIFY: usize = 256; - let enacted = route_from_finalized.enacted(); - let start = enacted.len() - std::cmp::min(enacted.len(), MAX_TO_NOTIFY); - for finalized in &enacted[start..] { - operation.notify_finalized.push(finalized.hash); + let finalized = + route_from_finalized.enacted().iter().map(|elem| elem.hash).collect::>(); + + let last_finalized_number = self + .backend + .blockchain() + .number(last_finalized)? + .expect("Finalized block expected to be onchain; qed"); + let mut stale_heads = Vec::new(); + for head in self.backend.blockchain().leaves()? { + let route_from_finalized = + sp_blockchain::tree_route(self.backend.blockchain(), block, head)?; + let retracted = route_from_finalized.retracted(); + let pivot = route_from_finalized.common_block(); + // It is not guaranteed that `backend.blockchain().leaves()` doesn't return + // heads that were in a stale state before this finalization and thus already + // included in previous notifications. We want to skip such heads. + // Given the "route" from the currently finalized block to the head under + // analysis, the condition for it to be added to the new stale heads list is: + // `!retracted.is_empty() && last_finalized_number <= pivot.number` + // 1. "route" has some "retractions". + // 2. previously finalized block number is not greater than the "route" pivot: + // - if `last_finalized_number <= pivot.number` then this is a new stale head; + // - else the stale head was already included by some previous finalization. + if !retracted.is_empty() && last_finalized_number <= pivot.number { + stale_heads.push(head); + } } + operation.notify_finalized = Some(FinalizeSummary { finalized, stale_heads }); } Ok(()) } - fn notify_finalized(&self, notify_finalized: Vec) -> sp_blockchain::Result<()> { + fn notify_finalized( + &self, + notify_finalized: Option>, + ) -> sp_blockchain::Result<()> { let mut sinks = self.finality_notification_sinks.lock(); - if notify_finalized.is_empty() { - // cleanup any closed finality notification sinks - // since we won't be running the loop below which - // would also remove any closed sinks. - sinks.retain(|sink| !sink.is_closed()); - - return Ok(()) - } + let mut notify_finalized = match notify_finalized { + Some(notify_finalized) => notify_finalized, + None => { + // Cleanup any closed finality notification sinks + // since we won't be running the loop below which + // would also remove any closed sinks. + sinks.retain(|sink| !sink.is_closed()); + return Ok(()) + }, + }; - // We assume the list is sorted and only want to inform the - // telemetry once about the finalized block. - if let Some(last) = notify_finalized.last() { - let header = self.header(&BlockId::Hash(*last))?.expect( - "Header already known to exist in DB because it is indicated in the tree route; \ - qed", - ); + let last = notify_finalized.finalized.pop().expect( + "At least one finalized block shall exist within a valid finalization summary; qed", + ); - telemetry!( - self.telemetry; - SUBSTRATE_INFO; - "notify.finalized"; - "height" => format!("{}", header.number()), - "best" => ?last, - ); - } + let header = self.header(&BlockId::Hash(last))?.expect( + "Header already known to exist in DB because it is indicated in the tree route; \ + qed", + ); - for finalized_hash in notify_finalized { - let header = self.header(&BlockId::Hash(finalized_hash))?.expect( - "Header already known to exist in DB because it is indicated in the tree route; \ - qed", - ); + telemetry!( + self.telemetry; + SUBSTRATE_INFO; + "notify.finalized"; + "height" => format!("{}", header.number()), + "best" => ?last, + ); - let notification = FinalityNotification { header, hash: finalized_hash }; + let notification = FinalityNotification { + hash: last, + header, + tree_route: Arc::new(notify_finalized.finalized), + stale_heads: Arc::new(notify_finalized.stale_heads), + }; - sinks.retain(|sink| sink.unbounded_send(notification.clone()).is_ok()); - } + sinks.retain(|sink| sink.unbounded_send(notification.clone()).is_ok()); Ok(()) } @@ -901,7 +950,6 @@ where // temporary leak of closed/discarded notification sinks (e.g. // from consensus code). self.import_notification_sinks.lock().retain(|sink| !sink.is_closed()); - return Ok(()) }, }; @@ -1068,7 +1116,7 @@ where }; let runtime_version = RuntimeVersionOf::runtime_version(executor, &mut ext, &runtime_code) - .map_err(|e| sp_blockchain::Error::VersionInvalid(format!("{:?}", e)))?; + .map_err(|e| sp_blockchain::Error::VersionInvalid(e.to_string()))?; Ok(runtime_version.state_version()) } else { Err(sp_blockchain::Error::VersionInvalid( @@ -1671,7 +1719,7 @@ where let storage_changes = match self.prepare_block_storage_changes(&mut import_block).map_err(|e| { - warn!("Block prepare storage changes error:\n{:?}", e); + warn!("Block prepare storage changes error: {}", e); ConsensusError::ClientImport(e.to_string()) })? { PrepareStorageChangesResult::Discard(res) => return Ok(res), @@ -1682,7 +1730,7 @@ where self.apply_block(operation, import_block, new_cache, storage_changes) }) .map_err(|e| { - warn!("Block import error:\n{:?}", e); + warn!("Block import error: {}", e); ConsensusError::ClientImport(e.to_string()).into() }) } diff --git a/client/service/src/client/wasm_override.rs b/client/service/src/client/wasm_override.rs index 86365f2d0cab4..267aea0709871 100644 --- a/client/service/src/client/wasm_override.rs +++ b/client/service/src/client/wasm_override.rs @@ -243,7 +243,7 @@ impl WasmOverride { hash: code_hash.into(), }, ) - .map_err(|e| WasmOverrideError::VersionInvalid(format!("{:?}", e)).into()) + .map_err(|e| WasmOverrideError::VersionInvalid(e.to_string()).into()) } } diff --git a/client/service/src/client/wasm_substitutes.rs b/client/service/src/client/wasm_substitutes.rs index a45eefb7b603c..3690672512675 100644 --- a/client/service/src/client/wasm_substitutes.rs +++ b/client/service/src/client/wasm_substitutes.rs @@ -151,6 +151,6 @@ where let mut ext = BasicExternalities::default(); executor .runtime_version(&mut ext, &code.runtime_code(None)) - .map_err(|e| WasmSubstituteError::VersionInvalid(format!("{:?}", e)).into()) + .map_err(|e| WasmSubstituteError::VersionInvalid(e.to_string()).into()) } } diff --git a/client/service/src/lib.rs b/client/service/src/lib.rs index 9710ba9e3d84f..d158bbc42e947 100644 --- a/client/service/src/lib.rs +++ b/client/service/src/lib.rs @@ -34,10 +34,10 @@ mod client; mod metrics; mod task_manager; -use std::{collections::HashMap, io, net::SocketAddr, pin::Pin, task::Poll}; +use std::{collections::HashMap, io, net::SocketAddr, pin::Pin}; use codec::{Decode, Encode}; -use futures::{stream, Future, FutureExt, Stream, StreamExt}; +use futures::{Future, FutureExt, StreamExt}; use log::{debug, error, warn}; use sc_network::PeerId; use sc_utils::mpsc::TracingUnboundedReceiver; @@ -152,26 +152,7 @@ async fn build_network_future< let starting_block = client.info().best_number; // Stream of finalized blocks reported by the client. - let mut finality_notification_stream = { - let mut finality_notification_stream = client.finality_notification_stream().fuse(); - - // We tweak the `Stream` in order to merge together multiple items if they happen to be - // ready. This way, we only get the latest finalized block. - stream::poll_fn(move |cx| { - let mut last = None; - while let Poll::Ready(Some(item)) = - Pin::new(&mut finality_notification_stream).poll_next(cx) - { - last = Some(item); - } - if let Some(last) = last { - Poll::Ready(Some(last)) - } else { - Poll::Pending - } - }) - .fuse() - }; + let mut finality_notification_stream = client.finality_notification_stream().fuse(); loop { futures::select! { @@ -528,7 +509,7 @@ where TransactionImport::Bad }, Err(e) => { - debug!("Error converting pool error: {:?}", e); + debug!("Error converting pool error: {}", e); // it is not bad at least, just some internal node logic error, so peer is // innocent. TransactionImport::KnownGood diff --git a/client/service/test/Cargo.toml b/client/service/test/Cargo.toml index 84b1d44e7bde6..6395f9d9877dc 100644 --- a/client/service/test/Cargo.toml +++ b/client/service/test/Cargo.toml @@ -21,18 +21,18 @@ fdlimit = "0.2.1" parking_lot = "0.11.2" sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } sp-api = { version = "4.0.0-dev", path = "../../../primitives/api" } -sp-state-machine = { version = "0.10.0", path = "../../../primitives/state-machine" } -sp-externalities = { version = "0.10.0", path = "../../../primitives/externalities" } -sp-trie = { version = "4.0.0", path = "../../../primitives/trie" } -sp-storage = { version = "4.0.0", path = "../../../primitives/storage" } +sp-state-machine = { version = "0.11.0", path = "../../../primitives/state-machine" } +sp-externalities = { version = "0.11.0", path = "../../../primitives/externalities" } +sp-trie = { version = "5.0.0", path = "../../../primitives/trie" } +sp-storage = { version = "5.0.0", path = "../../../primitives/storage" } sc-client-db = { version = "0.10.0-dev", default-features = false, path = "../../db" } futures = "0.3.16" sc-service = { version = "0.10.0-dev", features = ["test-helpers"], path = "../../service" } sc-network = { version = "0.10.0-dev", path = "../../network" } sp-consensus = { version = "0.10.0-dev", path = "../../../primitives/consensus/common" } sc-consensus = { version = "0.10.0-dev", path = "../../../client/consensus/common" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../../client/transaction-pool/api" } substrate-test-runtime = { version = "2.0.0", path = "../../../test-utils/runtime" } substrate-test-runtime-client = { version = "2.0.0", path = "../../../test-utils/runtime/client" } diff --git a/client/service/test/src/client/mod.rs b/client/service/test/src/client/mod.rs index 535edfadaf29d..2b0ea460c4dd3 100644 --- a/client/service/test/src/client/mod.rs +++ b/client/service/test/src/client/mod.rs @@ -20,7 +20,9 @@ use futures::executor::block_on; use hex_literal::hex; use parity_scale_codec::{Decode, Encode, Joiner}; use sc_block_builder::BlockBuilderProvider; -use sc_client_api::{in_mem, BlockBackend, BlockchainEvents, StorageProvider}; +use sc_client_api::{ + in_mem, BlockBackend, BlockchainEvents, FinalityNotifications, StorageProvider, +}; use sc_client_db::{ Backend, DatabaseSettings, DatabaseSource, KeepBlocks, PruningMode, TransactionStorageMode, }; @@ -165,6 +167,24 @@ fn block1(genesis_hash: Hash, backend: &InMemoryBackend) -> (Vec, + finalized: &[Hash], + stale_heads: &[Hash], +) { + match notifications.try_next() { + Ok(Some(notif)) => { + let stale_heads_expected: HashSet<_> = stale_heads.iter().collect(); + let stale_heads: HashSet<_> = notif.stale_heads.iter().collect(); + assert_eq!(notif.tree_route.as_ref(), &finalized[..finalized.len() - 1]); + assert_eq!(notif.hash, *finalized.last().unwrap()); + assert_eq!(stale_heads, stale_heads_expected); + }, + Ok(None) => panic!("unexpected notification result, client send channel was closed"), + Err(_) => assert!(finalized.is_empty()), + } +} + #[test] fn construct_genesis_should_work_with_native() { let mut storage = GenesisConfig::new( @@ -822,8 +842,12 @@ fn best_containing_on_longest_chain_with_max_depth_higher_than_best() { #[test] fn import_with_justification() { + // block tree: + // G -> A1 -> A2 -> A3 let mut client = substrate_test_runtime_client::new(); + let mut finality_notifications = client.finality_notification_stream(); + // G -> A1 let a1 = client.new_block(Default::default()).unwrap().build().unwrap().block; block_on(client.import(BlockOrigin::Own, a1.clone())).unwrap(); @@ -855,6 +879,10 @@ fn import_with_justification() { assert_eq!(client.justifications(&BlockId::Hash(a1.hash())).unwrap(), None); assert_eq!(client.justifications(&BlockId::Hash(a2.hash())).unwrap(), None); + + finality_notification_check(&mut finality_notifications, &[a1.hash(), a2.hash()], &[]); + finality_notification_check(&mut finality_notifications, &[a3.hash()], &[]); + assert!(finality_notifications.try_next().is_err()); } #[test] @@ -864,6 +892,9 @@ fn importing_diverged_finalized_block_should_trigger_reorg() { // G -> A1 -> A2 // \ // -> B1 + + let mut finality_notifications = client.finality_notification_stream(); + let a1 = client .new_block_at(&BlockId::Number(0), Default::default(), false) .unwrap() @@ -902,6 +933,9 @@ fn importing_diverged_finalized_block_should_trigger_reorg() { assert_eq!(client.chain_info().best_hash, b1.hash()); assert_eq!(client.chain_info().finalized_hash, b1.hash()); + + finality_notification_check(&mut finality_notifications, &[b1.hash()], &[a2.hash()]); + assert!(finality_notifications.try_next().is_err()); } #[test] @@ -911,6 +945,9 @@ fn finalizing_diverged_block_should_trigger_reorg() { // G -> A1 -> A2 // \ // -> B1 -> B2 + + let mut finality_notifications = client.finality_notification_stream(); + let a1 = client .new_block_at(&BlockId::Number(0), Default::default(), false) .unwrap() @@ -975,6 +1012,113 @@ fn finalizing_diverged_block_should_trigger_reorg() { block_on(client.import(BlockOrigin::Own, b3.clone())).unwrap(); assert_eq!(client.chain_info().best_hash, b3.hash()); + + finality_notification_check(&mut finality_notifications, &[b1.hash()], &[a2.hash()]); + assert!(finality_notifications.try_next().is_err()); +} + +#[test] +fn finality_notifications_content() { + let (mut client, _select_chain) = TestClientBuilder::new().build_with_longest_chain(); + + // -> D3 -> D4 + // G -> A1 -> A2 -> A3 + // -> B1 -> B2 + // -> C1 + + let mut finality_notifications = client.finality_notification_stream(); + + let a1 = client + .new_block_at(&BlockId::Number(0), Default::default(), false) + .unwrap() + .build() + .unwrap() + .block; + block_on(client.import(BlockOrigin::Own, a1.clone())).unwrap(); + + let a2 = client + .new_block_at(&BlockId::Hash(a1.hash()), Default::default(), false) + .unwrap() + .build() + .unwrap() + .block; + block_on(client.import(BlockOrigin::Own, a2.clone())).unwrap(); + + let a3 = client + .new_block_at(&BlockId::Hash(a2.hash()), Default::default(), false) + .unwrap() + .build() + .unwrap() + .block; + block_on(client.import(BlockOrigin::Own, a3.clone())).unwrap(); + + let mut b1 = client.new_block_at(&BlockId::Number(0), Default::default(), false).unwrap(); + // needed to make sure B1 gets a different hash from A1 + b1.push_transfer(Transfer { + from: AccountKeyring::Alice.into(), + to: AccountKeyring::Ferdie.into(), + amount: 1, + nonce: 0, + }) + .unwrap(); + let b1 = b1.build().unwrap().block; + block_on(client.import(BlockOrigin::Own, b1.clone())).unwrap(); + + let b2 = client + .new_block_at(&BlockId::Hash(b1.hash()), Default::default(), false) + .unwrap() + .build() + .unwrap() + .block; + block_on(client.import(BlockOrigin::Own, b2.clone())).unwrap(); + + let mut c1 = client.new_block_at(&BlockId::Number(0), Default::default(), false).unwrap(); + // needed to make sure B1 gets a different hash from A1 + c1.push_transfer(Transfer { + from: AccountKeyring::Alice.into(), + to: AccountKeyring::Ferdie.into(), + amount: 2, + nonce: 0, + }) + .unwrap(); + let c1 = c1.build().unwrap().block; + block_on(client.import(BlockOrigin::Own, c1.clone())).unwrap(); + + let mut d3 = client + .new_block_at(&BlockId::Hash(a2.hash()), Default::default(), false) + .unwrap(); + // needed to make sure D3 gets a different hash from A3 + d3.push_transfer(Transfer { + from: AccountKeyring::Alice.into(), + to: AccountKeyring::Ferdie.into(), + amount: 2, + nonce: 0, + }) + .unwrap(); + let d3 = d3.build().unwrap().block; + block_on(client.import(BlockOrigin::Own, d3.clone())).unwrap(); + + let d4 = client + .new_block_at(&BlockId::Hash(d3.hash()), Default::default(), false) + .unwrap() + .build() + .unwrap() + .block; + + // Postpone import to test behavior of import of finalized block. + + ClientExt::finalize_block(&client, BlockId::Hash(a2.hash()), None).unwrap(); + + // Import and finalize D4 + block_on(client.import_as_final(BlockOrigin::Own, d4.clone())).unwrap(); + + finality_notification_check( + &mut finality_notifications, + &[a1.hash(), a2.hash()], + &[c1.hash(), b2.hash()], + ); + finality_notification_check(&mut finality_notifications, &[d3.hash(), d4.hash()], &[a3.hash()]); + assert!(finality_notifications.try_next().is_err()); } #[test] @@ -1069,6 +1213,8 @@ fn doesnt_import_blocks_that_revert_finality() { let mut client = TestClientBuilder::with_backend(backend).build(); + let mut finality_notifications = client.finality_notification_stream(); + // -> C1 // / // G -> A1 -> A2 @@ -1150,6 +1296,9 @@ fn doesnt_import_blocks_that_revert_finality() { ConsensusError::ClientImport(sp_blockchain::Error::NotInFinalizedChain.to_string()); assert_eq!(import_err.to_string(), expected_err.to_string()); + + finality_notification_check(&mut finality_notifications, &[a1.hash(), a2.hash()], &[b2.hash()]); + assert!(finality_notifications.try_next().is_err()); } #[test] diff --git a/client/state-db/Cargo.toml b/client/state-db/Cargo.toml index fbde840fbb8e9..fa0c5ed9810c9 100644 --- a/client/state-db/Cargo.toml +++ b/client/state-db/Cargo.toml @@ -16,7 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"] parking_lot = "0.11.2" log = "0.4.11" sc-client-api = { version = "4.0.0-dev", path = "../api" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } codec = { package = "parity-scale-codec", version = "2.0.0", features = ["derive"] } parity-util-mem = { version = "0.10.2", default-features = false, features = ["primitive-types"] } parity-util-mem-derive = "0.1.0" diff --git a/client/sync-state-rpc/Cargo.toml b/client/sync-state-rpc/Cargo.toml index 0aae985319d43..b413446c321f2 100644 --- a/client/sync-state-rpc/Cargo.toml +++ b/client/sync-state-rpc/Cargo.toml @@ -24,7 +24,7 @@ sc-consensus-epochs = { version = "0.10.0-dev", path = "../consensus/epochs" } sc-finality-grandpa = { version = "0.10.0-dev", path = "../finality-grandpa" } sc-rpc-api = { version = "0.10.0-dev", path = "../rpc-api" } serde_json = "1.0.74" -serde = { version = "1.0.132", features = ["derive"] } +serde = { version = "1.0.136", features = ["derive"] } sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } codec = { package = "parity-scale-codec", version = "2.0.0" } diff --git a/client/telemetry/Cargo.toml b/client/telemetry/Cargo.toml index 2417f3c77b761..595a574021599 100644 --- a/client/telemetry/Cargo.toml +++ b/client/telemetry/Cargo.toml @@ -22,7 +22,7 @@ libp2p = { version = "0.40.0", default-features = false, features = ["dns-async- log = "0.4.8" pin-project = "1.0.10" rand = "0.7.2" -serde = { version = "1.0.132", features = ["derive"] } +serde = { version = "1.0.136", features = ["derive"] } serde_json = "1.0.74" chrono = "0.4.19" thiserror = "1.0.30" diff --git a/client/tracing/Cargo.toml b/client/tracing/Cargo.toml index 62c7f7a4becca..5f7e0831a536a 100644 --- a/client/tracing/Cargo.toml +++ b/client/tracing/Cargo.toml @@ -23,17 +23,17 @@ once_cell = "1.8.0" parking_lot = "0.11.2" regex = "1.5.4" rustc-hash = "1.1.0" -serde = "1.0.132" +serde = "1.0.136" thiserror = "1.0.30" tracing = "0.1.29" tracing-log = "0.1.2" tracing-subscriber = { version = "0.2.25", features = ["parking_lot"] } sp-tracing = { version = "4.0.0", path = "../../primitives/tracing" } -sp-rpc = { version = "4.0.0-dev", path = "../../primitives/rpc" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-rpc = { version = "5.0.0", path = "../../primitives/rpc" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } sp-api = { version = "4.0.0-dev", path = "../../primitives/api" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } sc-client-api = { version = "4.0.0-dev", path = "../api" } sc-tracing-proc-macro = { version = "4.0.0-dev", path = "./proc-macro" } sc-rpc-server = { version = "4.0.0-dev", path = "../rpc-servers" } diff --git a/client/tracing/src/block/mod.rs b/client/tracing/src/block/mod.rs index 067cdafa0ae30..259827e4b47d9 100644 --- a/client/tracing/src/block/mod.rs +++ b/client/tracing/src/block/mod.rs @@ -253,7 +253,7 @@ where self.client.runtime_api().execute_block(&parent_id, block) }) { return Err(Error::Dispatch( - format!("Failed to collect traces and execute block: {:?}", e).to_string(), + format!("Failed to collect traces and execute block: {}", e).to_string(), )) } } diff --git a/client/transaction-pool/Cargo.toml b/client/transaction-pool/Cargo.toml index 73ec7cfff7f3d..42172ce723e1c 100644 --- a/client/transaction-pool/Cargo.toml +++ b/client/transaction-pool/Cargo.toml @@ -23,14 +23,14 @@ parking_lot = "0.11.2" prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus", version = "0.10.0-dev"} sc-client-api = { version = "4.0.0-dev", path = "../api" } sp-api = { version = "4.0.0-dev", path = "../../primitives/api" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } sp-tracing = { version = "4.0.0", path = "../../primitives/tracing" } sp-transaction-pool = { version = "4.0.0-dev", path = "../../primitives/transaction-pool" } sc-transaction-pool-api = { version = "4.0.0-dev", path = "./api" } sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } sc-utils = { version = "4.0.0-dev", path = "../utils" } -serde = { version = "1.0.132", features = ["derive"] } +serde = { version = "1.0.136", features = ["derive"] } linked-hash-map = "0.5.4" retain_mut = "0.1.4" diff --git a/client/transaction-pool/api/Cargo.toml b/client/transaction-pool/api/Cargo.toml index 95b82e26fc5d7..70f18c345e050 100644 --- a/client/transaction-pool/api/Cargo.toml +++ b/client/transaction-pool/api/Cargo.toml @@ -9,11 +9,10 @@ repository = "https://github.com/paritytech/substrate/" description = "Transaction pool client facing API." [dependencies] -futures = { version = "0.3.1" } -log = { version = "0.4.8" } -serde = { version = "1.0.132", features = ["derive"] } -thiserror = { version = "1.0.30" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } +futures = "0.3.1" +log = "0.4.8" +serde = { version = "1.0.136", features = ["derive"] } +thiserror = "1.0.30" -derive_more = { version = "0.99.16" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } diff --git a/client/transaction-pool/api/src/error.rs b/client/transaction-pool/api/src/error.rs index f1ac2798e62d3..b093657f739b1 100644 --- a/client/transaction-pool/api/src/error.rs +++ b/client/transaction-pool/api/src/error.rs @@ -26,7 +26,7 @@ use sp_runtime::transaction_validity::{ pub type Result = std::result::Result; /// Transaction pool error type. -#[derive(Debug, thiserror::Error, derive_more::From)] +#[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error("Unknown transaction validity: {0:?}")] @@ -64,7 +64,6 @@ pub enum Error { #[error("Transaction cannot be propagated and the local node does not author blocks")] Unactionable, - #[from(ignore)] #[error("{0}")] InvalidBlockId(String), diff --git a/client/transaction-pool/api/src/lib.rs b/client/transaction-pool/api/src/lib.rs index f19a994b1b947..7c90cd79ccaed 100644 --- a/client/transaction-pool/api/src/lib.rs +++ b/client/transaction-pool/api/src/lib.rs @@ -278,7 +278,7 @@ impl ReadyTransactions for std::iter::Empty { /// Events that the transaction pool listens for. pub enum ChainEvent { - /// New best block have been added to the chain + /// New best block have been added to the chain. NewBestBlock { /// Hash of the block. hash: B::Hash, @@ -289,8 +289,10 @@ pub enum ChainEvent { }, /// An existing block has been finalized. Finalized { - /// Hash of just finalized block + /// Hash of just finalized block. hash: B::Hash, + /// Path from old finalized to new finalized parent. + tree_route: Arc>, }, } @@ -353,7 +355,7 @@ impl OffchainSubmitTransaction for TP result.map(|_| ()).map_err(|e| { log::warn!( target: "txpool", - "(offchain call) Error submitting a transaction to the pool: {:?}", + "(offchain call) Error submitting a transaction to the pool: {}", e ) }) diff --git a/client/transaction-pool/src/api.rs b/client/transaction-pool/src/api.rs index de1c79534b386..12909f313d100 100644 --- a/client/transaction-pool/src/api.rs +++ b/client/transaction-pool/src/api.rs @@ -167,18 +167,14 @@ where &self, at: &BlockId, ) -> error::Result>> { - self.client - .to_number(at) - .map_err(|e| Error::BlockIdConversion(format!("{:?}", e))) + self.client.to_number(at).map_err(|e| Error::BlockIdConversion(e.to_string())) } fn block_id_to_hash( &self, at: &BlockId, ) -> error::Result>> { - self.client - .to_hash(at) - .map_err(|e| Error::BlockIdConversion(format!("{:?}", e))) + self.client.to_hash(at).map_err(|e| Error::BlockIdConversion(e.to_string())) } fn hash_and_length( @@ -224,7 +220,7 @@ where }?; let block_hash = client.to_hash(at) - .map_err(|e| Error::RuntimeApi(format!("{:?}", e)))? + .map_err(|e| Error::RuntimeApi(e.to_string()))? .ok_or_else(|| Error::RuntimeApi(format!("Could not get hash for block `{:?}`.", at)))?; use sp_api::Core; @@ -237,7 +233,7 @@ where .map_err(|e| Error::RuntimeApi(e.to_string())) } else { let block_number = client.to_number(at) - .map_err(|e| Error::RuntimeApi(format!("{:?}", e)))? + .map_err(|e| Error::RuntimeApi(e.to_string()))? .ok_or_else(|| Error::RuntimeApi(format!("Could not get number for block `{:?}`.", at)) )?; diff --git a/client/transaction-pool/src/lib.rs b/client/transaction-pool/src/lib.rs index 2d07815e4baac..ec93d1f7c51fe 100644 --- a/client/transaction-pool/src/lib.rs +++ b/client/transaction-pool/src/lib.rs @@ -47,8 +47,8 @@ use std::{ use graph::{ExtrinsicHash, IsValidator}; use sc_transaction_pool_api::{ - ChainEvent, ImportNotificationStream, MaintainedTransactionPool, PoolFuture, PoolStatus, - ReadyTransactions, TransactionFor, TransactionPool, TransactionSource, + error::Error as TxPoolError, ChainEvent, ImportNotificationStream, MaintainedTransactionPool, + PoolFuture, PoolStatus, ReadyTransactions, TransactionFor, TransactionPool, TransactionSource, TransactionStatusStreamFor, TxHash, }; use sp_core::traits::SpawnEssentialNamed; @@ -418,8 +418,8 @@ where .validate_transaction_blocking(at, TransactionSource::Local, xt.clone())? .map_err(|e| { Self::Error::Pool(match e { - TransactionValidityError::Invalid(i) => i.into(), - TransactionValidityError::Unknown(u) => u.into(), + TransactionValidityError::Invalid(i) => TxPoolError::InvalidTransaction(i), + TransactionValidityError::Unknown(u) => TxPoolError::UnknownTransaction(u), }) })?; @@ -534,7 +534,7 @@ async fn prune_known_txs_for_block { - log::debug!(target: "txpool", "Error retrieving header for {:?}: {:?}", block_id, e); + log::debug!(target: "txpool", "Error retrieving header for {:?}: {}", block_id, e); return hashes }, }; if let Err(e) = pool.prune(&block_id, &BlockId::hash(*header.parent_hash()), &extrinsics).await { - log::error!("Cannot prune known in the pool {:?}!", e); + log::error!("Cannot prune known in the pool: {}", e); } hashes @@ -639,7 +639,7 @@ where .block_body(&BlockId::hash(hash)) .await .unwrap_or_else(|e| { - log::warn!("Failed to fetch block body {:?}!", e); + log::warn!("Failed to fetch block body: {}", e); None }) .unwrap_or_default() @@ -685,7 +685,7 @@ where { log::debug!( target: "txpool", - "[{:?}] Error re-submitting transactions: {:?}", + "[{:?}] Error re-submitting transactions: {}", id, e, ) @@ -709,15 +709,17 @@ where } .boxed() }, - ChainEvent::Finalized { hash } => { + ChainEvent::Finalized { hash, tree_route } => { let pool = self.pool.clone(); async move { - if let Err(e) = pool.validated_pool().on_block_finalized(hash).await { - log::warn!( - target: "txpool", - "Error [{}] occurred while attempting to notify watchers of finalization {}", - e, hash - ) + for hash in tree_route.iter().chain(&[hash]) { + if let Err(e) = pool.validated_pool().on_block_finalized(*hash).await { + log::warn!( + target: "txpool", + "Error [{}] occurred while attempting to notify watchers of finalization {}", + e, hash + ) + } } } .boxed() diff --git a/client/transaction-pool/src/revalidation.rs b/client/transaction-pool/src/revalidation.rs index 22b526e9dfc6d..e3641008a7061 100644 --- a/client/transaction-pool/src/revalidation.rs +++ b/client/transaction-pool/src/revalidation.rs @@ -106,7 +106,7 @@ async fn batch_revalidate( Err(validation_err) => { log::debug!( target: "txpool", - "[{:?}]: Error during revalidation: {:?}. Removing.", + "[{:?}]: Removing due to error during revalidation: {}", ext_hash, validation_err ); diff --git a/client/transaction-pool/tests/pool.rs b/client/transaction-pool/tests/pool.rs index 4aeaf79a61540..21a87f6e006ec 100644 --- a/client/transaction-pool/tests/pool.rs +++ b/client/transaction-pool/tests/pool.rs @@ -387,7 +387,7 @@ fn should_push_watchers_during_maintenance() { let header_hash = header.hash(); block_on(pool.maintain(block_event(header))); - let event = ChainEvent::Finalized { hash: header_hash.clone() }; + let event = ChainEvent::Finalized { hash: header_hash.clone(), tree_route: Arc::new(vec![]) }; block_on(pool.maintain(event)); // then @@ -445,7 +445,7 @@ fn finalization() { let event = ChainEvent::NewBestBlock { hash: header.hash(), tree_route: None }; block_on(pool.maintain(event)); - let event = ChainEvent::Finalized { hash: header.hash() }; + let event = ChainEvent::Finalized { hash: header.hash(), tree_route: Arc::new(vec![]) }; block_on(pool.maintain(event)); let mut stream = futures::executor::block_on_stream(watcher); @@ -493,7 +493,7 @@ fn fork_aware_finalization() { b1 = header.hash(); block_on(pool.maintain(event)); assert_eq!(pool.status().ready, 0); - let event = ChainEvent::Finalized { hash: b1 }; + let event = ChainEvent::Finalized { hash: b1, tree_route: Arc::new(vec![]) }; block_on(pool.maintain(event)); } @@ -537,7 +537,7 @@ fn fork_aware_finalization() { block_on(pool.maintain(event)); assert_eq!(pool.status().ready, 2); - let event = ChainEvent::Finalized { hash: header.hash() }; + let event = ChainEvent::Finalized { hash: header.hash(), tree_route: Arc::new(vec![]) }; block_on(pool.maintain(event)); } @@ -554,7 +554,7 @@ fn fork_aware_finalization() { d1 = header.hash(); block_on(pool.maintain(event)); assert_eq!(pool.status().ready, 2); - let event = ChainEvent::Finalized { hash: d1 }; + let event = ChainEvent::Finalized { hash: d1, tree_route: Arc::new(vec![]) }; block_on(pool.maintain(event)); } @@ -567,7 +567,7 @@ fn fork_aware_finalization() { let event = ChainEvent::NewBestBlock { hash: header.hash(), tree_route: None }; block_on(pool.maintain(event)); assert_eq!(pool.status().ready, 0); - block_on(pool.maintain(ChainEvent::Finalized { hash: e1 })); + block_on(pool.maintain(ChainEvent::Finalized { hash: e1, tree_route: Arc::new(vec![]) })); } for (canon_watcher, h) in canon_watchers { @@ -637,7 +637,7 @@ fn prune_and_retract_tx_at_same_time() { block_on(pool.maintain(event)); assert_eq!(pool.status().ready, 0); - let event = ChainEvent::Finalized { hash: header.hash() }; + let event = ChainEvent::Finalized { hash: header.hash(), tree_route: Arc::new(vec![]) }; block_on(pool.maintain(event)); header.hash() diff --git a/docs/rustdocs-release.md b/docs/rustdocs-release.md new file mode 100644 index 0000000000000..5c7e2db40a2cd --- /dev/null +++ b/docs/rustdocs-release.md @@ -0,0 +1,20 @@ +# Rustdocs Release Process + +There is [a script in place](../.maintain/rustdocs-release.sh) to manage the deployment of Substrate rustdocs at +https://paritytech.github.io/substrate, which is pushing the rustdocs file in `gh-pages` branch of +https://github.com/paritytech/substrate. + +The documentation at the top of the `rustdocs-release.sh` explains most of the mechanics of the script. + +Manage the rustdocs deployment with one of the following commands. + +```bash +# Deploy rustdocs of `monthly-2021-10` tag +.maintain/rustdocs-release.sh deploy monthly-2021-10 + +# In addition to the above, the `latest` symlink will point to this version of rustdocs +.maintain/rustdocs-release.sh deploy -l monthly-2021-10 + +# Remove the rustdocs of `monthly-2021-10` from `gh-pages`. +.maintain/rustdocs-release.sh remove monthly-2021-10 +``` diff --git a/frame/assets/Cargo.toml b/frame/assets/Cargo.toml index c250a75d4c2f0..c5d60291fc435 100644 --- a/frame/assets/Cargo.toml +++ b/frame/assets/Cargo.toml @@ -17,7 +17,7 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } # Needed for various traits. In our case, `OnFinalize`. -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } # Needed for type-safe access to storage DB. frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } # `system` module provides us with all sorts of useful stuff and macros depend on it being around. @@ -25,9 +25,9 @@ frame-system = { version = "4.0.0-dev", default-features = false, path = "../sys frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } sp-std = { version = "4.0.0", path = "../../primitives/std" } -sp-io = { version = "4.0.0", path = "../../primitives/io" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } [features] diff --git a/frame/assets/src/functions.rs b/frame/assets/src/functions.rs index e02cc7c8bb213..73804fc832c99 100644 --- a/frame/assets/src/functions.rs +++ b/frame/assets/src/functions.rs @@ -55,7 +55,12 @@ impl, I: 'static> Pallet { /// Get the total supply of an asset `id`. pub fn total_supply(id: T::AssetId) -> T::Balance { - Asset::::get(id).map(|x| x.supply).unwrap_or_else(Zero::zero) + Self::maybe_total_supply(id).unwrap_or_default() + } + + /// Get the total supply of an asset `id` if the asset exists. + pub fn maybe_total_supply(id: T::AssetId) -> Option { + Asset::::get(id).map(|x| x.supply) } pub(super) fn new_account( diff --git a/frame/assets/src/weights.rs b/frame/assets/src/weights.rs index 423677cf13808..a1cd77faee82e 100644 --- a/frame/assets/src/weights.rs +++ b/frame/assets/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_assets //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-30, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/assets/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -75,13 +76,13 @@ pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { // Storage: Assets Asset (r:1 w:1) fn create() -> Weight { - (41_651_000 as Weight) + (22_102_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:1) fn force_create() -> Weight { - (21_378_000 as Weight) + (12_124_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -92,12 +93,12 @@ impl WeightInfo for SubstrateWeight { // Storage: Assets Approvals (r:501 w:500) fn destroy(c: u32, s: u32, a: u32, ) -> Weight { (0 as Weight) - // Standard Error: 32_000 - .saturating_add((21_163_000 as Weight).saturating_mul(c as Weight)) - // Standard Error: 32_000 - .saturating_add((26_932_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 329_000 - .saturating_add((29_714_000 as Weight).saturating_mul(a as Weight)) + // Standard Error: 34_000 + .saturating_add((14_683_000 as Weight).saturating_mul(c as Weight)) + // Standard Error: 34_000 + .saturating_add((17_080_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 342_000 + .saturating_add((16_533_000 as Weight).saturating_mul(a as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) @@ -110,14 +111,14 @@ impl WeightInfo for SubstrateWeight { // Storage: Assets Asset (r:1 w:1) // Storage: Assets Account (r:1 w:1) fn mint() -> Weight { - (47_913_000 as Weight) + (26_632_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Assets Asset (r:1 w:1) // Storage: Assets Account (r:1 w:1) fn burn() -> Weight { - (55_759_000 as Weight) + (30_048_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -125,7 +126,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Assets Account (r:2 w:2) // Storage: System Account (r:1 w:1) fn transfer() -> Weight { - (83_205_000 as Weight) + (44_000_000 as Weight) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } @@ -133,7 +134,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Assets Account (r:2 w:2) // Storage: System Account (r:1 w:1) fn transfer_keep_alive() -> Weight { - (70_665_000 as Weight) + (37_286_000 as Weight) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } @@ -141,93 +142,95 @@ impl WeightInfo for SubstrateWeight { // Storage: Assets Account (r:2 w:2) // Storage: System Account (r:1 w:1) fn force_transfer() -> Weight { - (81_458_000 as Weight) + (44_120_000 as Weight) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } // Storage: Assets Asset (r:1 w:0) // Storage: Assets Account (r:1 w:1) fn freeze() -> Weight { - (32_845_000 as Weight) + (18_309_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:0) // Storage: Assets Account (r:1 w:1) fn thaw() -> Weight { - (33_303_000 as Weight) + (18_290_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:1) fn freeze_asset() -> Weight { - (23_434_000 as Weight) + (14_744_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:1) fn thaw_asset() -> Weight { - (24_173_000 as Weight) + (14_833_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:1) // Storage: Assets Metadata (r:1 w:0) fn transfer_ownership() -> Weight { - (27_466_000 as Weight) + (16_654_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:1) fn set_team() -> Weight { - (24_608_000 as Weight) + (15_351_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:0) // Storage: Assets Metadata (r:1 w:1) fn set_metadata(n: u32, s: u32, ) -> Weight { - (49_515_000 as Weight) - // Standard Error: 1_000 - .saturating_add((1_000 as Weight).saturating_mul(n as Weight)) - // Standard Error: 1_000 - .saturating_add((6_000 as Weight).saturating_mul(s as Weight)) + (27_588_000 as Weight) + // Standard Error: 0 + .saturating_add((6_000 as Weight).saturating_mul(n as Weight)) + // Standard Error: 0 + .saturating_add((3_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:0) // Storage: Assets Metadata (r:1 w:1) fn clear_metadata() -> Weight { - (48_163_000 as Weight) + (27_710_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:0) // Storage: Assets Metadata (r:1 w:1) - fn force_set_metadata(_n: u32, s: u32, ) -> Weight { - (26_722_000 as Weight) + fn force_set_metadata(n: u32, s: u32, ) -> Weight { + (15_345_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(n as Weight)) // Standard Error: 0 - .saturating_add((5_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:0) // Storage: Assets Metadata (r:1 w:1) fn force_clear_metadata() -> Weight { - (47_923_000 as Weight) + (27_552_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:1) fn force_asset_status() -> Weight { - (23_081_000 as Weight) + (13_755_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:1) // Storage: Assets Approvals (r:1 w:1) fn approve_transfer() -> Weight { - (56_998_000 as Weight) + (30_831_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -236,21 +239,21 @@ impl WeightInfo for SubstrateWeight { // Storage: Assets Account (r:2 w:2) // Storage: System Account (r:1 w:1) fn transfer_approved() -> Weight { - (107_171_000 as Weight) + (56_267_000 as Weight) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(5 as Weight)) } // Storage: Assets Asset (r:1 w:1) // Storage: Assets Approvals (r:1 w:1) fn cancel_approval() -> Weight { - (57_358_000 as Weight) + (31_964_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Assets Asset (r:1 w:1) // Storage: Assets Approvals (r:1 w:1) fn force_cancel_approval() -> Weight { - (58_330_000 as Weight) + (31_806_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -260,13 +263,13 @@ impl WeightInfo for SubstrateWeight { impl WeightInfo for () { // Storage: Assets Asset (r:1 w:1) fn create() -> Weight { - (41_651_000 as Weight) + (22_102_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:1) fn force_create() -> Weight { - (21_378_000 as Weight) + (12_124_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -277,12 +280,12 @@ impl WeightInfo for () { // Storage: Assets Approvals (r:501 w:500) fn destroy(c: u32, s: u32, a: u32, ) -> Weight { (0 as Weight) - // Standard Error: 32_000 - .saturating_add((21_163_000 as Weight).saturating_mul(c as Weight)) - // Standard Error: 32_000 - .saturating_add((26_932_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 329_000 - .saturating_add((29_714_000 as Weight).saturating_mul(a as Weight)) + // Standard Error: 34_000 + .saturating_add((14_683_000 as Weight).saturating_mul(c as Weight)) + // Standard Error: 34_000 + .saturating_add((17_080_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 342_000 + .saturating_add((16_533_000 as Weight).saturating_mul(a as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) @@ -295,14 +298,14 @@ impl WeightInfo for () { // Storage: Assets Asset (r:1 w:1) // Storage: Assets Account (r:1 w:1) fn mint() -> Weight { - (47_913_000 as Weight) + (26_632_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Assets Asset (r:1 w:1) // Storage: Assets Account (r:1 w:1) fn burn() -> Weight { - (55_759_000 as Weight) + (30_048_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -310,7 +313,7 @@ impl WeightInfo for () { // Storage: Assets Account (r:2 w:2) // Storage: System Account (r:1 w:1) fn transfer() -> Weight { - (83_205_000 as Weight) + (44_000_000 as Weight) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } @@ -318,7 +321,7 @@ impl WeightInfo for () { // Storage: Assets Account (r:2 w:2) // Storage: System Account (r:1 w:1) fn transfer_keep_alive() -> Weight { - (70_665_000 as Weight) + (37_286_000 as Weight) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } @@ -326,93 +329,95 @@ impl WeightInfo for () { // Storage: Assets Account (r:2 w:2) // Storage: System Account (r:1 w:1) fn force_transfer() -> Weight { - (81_458_000 as Weight) + (44_120_000 as Weight) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } // Storage: Assets Asset (r:1 w:0) // Storage: Assets Account (r:1 w:1) fn freeze() -> Weight { - (32_845_000 as Weight) + (18_309_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:0) // Storage: Assets Account (r:1 w:1) fn thaw() -> Weight { - (33_303_000 as Weight) + (18_290_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:1) fn freeze_asset() -> Weight { - (23_434_000 as Weight) + (14_744_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:1) fn thaw_asset() -> Weight { - (24_173_000 as Weight) + (14_833_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:1) // Storage: Assets Metadata (r:1 w:0) fn transfer_ownership() -> Weight { - (27_466_000 as Weight) + (16_654_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:1) fn set_team() -> Weight { - (24_608_000 as Weight) + (15_351_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:0) // Storage: Assets Metadata (r:1 w:1) fn set_metadata(n: u32, s: u32, ) -> Weight { - (49_515_000 as Weight) - // Standard Error: 1_000 - .saturating_add((1_000 as Weight).saturating_mul(n as Weight)) - // Standard Error: 1_000 - .saturating_add((6_000 as Weight).saturating_mul(s as Weight)) + (27_588_000 as Weight) + // Standard Error: 0 + .saturating_add((6_000 as Weight).saturating_mul(n as Weight)) + // Standard Error: 0 + .saturating_add((3_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:0) // Storage: Assets Metadata (r:1 w:1) fn clear_metadata() -> Weight { - (48_163_000 as Weight) + (27_710_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:0) // Storage: Assets Metadata (r:1 w:1) - fn force_set_metadata(_n: u32, s: u32, ) -> Weight { - (26_722_000 as Weight) + fn force_set_metadata(n: u32, s: u32, ) -> Weight { + (15_345_000 as Weight) + // Standard Error: 0 + .saturating_add((2_000 as Weight).saturating_mul(n as Weight)) // Standard Error: 0 - .saturating_add((5_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((2_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:0) // Storage: Assets Metadata (r:1 w:1) fn force_clear_metadata() -> Weight { - (47_923_000 as Weight) + (27_552_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:1) fn force_asset_status() -> Weight { - (23_081_000 as Weight) + (13_755_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Assets Asset (r:1 w:1) // Storage: Assets Approvals (r:1 w:1) fn approve_transfer() -> Weight { - (56_998_000 as Weight) + (30_831_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -421,21 +426,21 @@ impl WeightInfo for () { // Storage: Assets Account (r:2 w:2) // Storage: System Account (r:1 w:1) fn transfer_approved() -> Weight { - (107_171_000 as Weight) + (56_267_000 as Weight) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(5 as Weight)) } // Storage: Assets Asset (r:1 w:1) // Storage: Assets Approvals (r:1 w:1) fn cancel_approval() -> Weight { - (57_358_000 as Weight) + (31_964_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Assets Asset (r:1 w:1) // Storage: Assets Approvals (r:1 w:1) fn force_cancel_approval() -> Weight { - (58_330_000 as Weight) + (31_806_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } diff --git a/frame/atomic-swap/Cargo.toml b/frame/atomic-swap/Cargo.toml index 0f478ab5602f9..1dcd6154d0beb 100644 --- a/frame/atomic-swap/Cargo.toml +++ b/frame/atomic-swap/Cargo.toml @@ -17,10 +17,10 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } [dev-dependencies] pallet-balances = { version = "4.0.0-dev", path = "../balances" } diff --git a/frame/atomic-swap/src/lib.rs b/frame/atomic-swap/src/lib.rs index e83055b4d283e..e57496954a574 100644 --- a/frame/atomic-swap/src/lib.rs +++ b/frame/atomic-swap/src/lib.rs @@ -45,6 +45,7 @@ mod tests; use codec::{Decode, Encode}; use frame_support::{ dispatch::DispatchResult, + pallet_prelude::MaxEncodedLen, traits::{BalanceStatus, Currency, Get, ReservableCurrency}, weights::Weight, RuntimeDebugNoBound, @@ -59,8 +60,9 @@ use sp_std::{ }; /// Pending atomic swap operation. -#[derive(Clone, Eq, PartialEq, RuntimeDebugNoBound, Encode, Decode, TypeInfo)] +#[derive(Clone, Eq, PartialEq, RuntimeDebugNoBound, Encode, Decode, TypeInfo, MaxEncodedLen)] #[scale_info(skip_type_params(T))] +#[codec(mel_bound())] pub struct PendingSwap { /// Source of the swap. pub source: T::AccountId, @@ -93,8 +95,9 @@ pub trait SwapAction { } /// A swap action that only allows transferring balances. -#[derive(Clone, RuntimeDebug, Eq, PartialEq, Encode, Decode, TypeInfo)] +#[derive(Clone, RuntimeDebug, Eq, PartialEq, Encode, Decode, TypeInfo, MaxEncodedLen)] #[scale_info(skip_type_params(C))] +#[codec(mel_bound())] pub struct BalanceSwapAction> { value: >::Balance, _marker: PhantomData, @@ -165,7 +168,7 @@ pub mod pallet { /// The overarching event type. type Event: From> + IsType<::Event>; /// Swap action. - type SwapAction: SwapAction + Parameter; + type SwapAction: SwapAction + Parameter + MaxEncodedLen; /// Limit of proof size. /// /// Atomic swap is only atomic if once the proof is revealed, both parties can submit the @@ -182,7 +185,6 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] pub struct Pallet(PhantomData); #[pallet::storage] @@ -193,6 +195,9 @@ pub mod pallet { Blake2_128Concat, HashedProof, PendingSwap, + OptionQuery, + GetDefault, + ConstU32<300_000>, >; #[pallet::error] diff --git a/frame/aura/Cargo.toml b/frame/aura/Cargo.toml index f5c71a3088585..f869ddb417029 100644 --- a/frame/aura/Cargo.toml +++ b/frame/aura/Cargo.toml @@ -13,19 +13,19 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-application-crypto = { version = "4.0.0", default-features = false, path = "../../primitives/application-crypto" } +sp-application-crypto = { version = "5.0.0", default-features = false, path = "../../primitives/application-crypto" } codec = { package = "parity-scale-codec", version = "2.2.0", default-features = false, features = ["derive", "max-encoded-len"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } sp-consensus-aura = { version = "0.10.0-dev", path = "../../primitives/consensus/aura", default-features = false } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } pallet-timestamp = { version = "4.0.0-dev", default-features = false, path = "../timestamp" } [dev-dependencies] -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } [features] default = ["std"] diff --git a/frame/authority-discovery/Cargo.toml b/frame/authority-discovery/Cargo.toml index c1233028df4e2..b6e8a400f8652 100644 --- a/frame/authority-discovery/Cargo.toml +++ b/frame/authority-discovery/Cargo.toml @@ -14,7 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] sp-authority-discovery = { version = "4.0.0-dev", default-features = false, path = "../../primitives/authority-discovery" } -sp-application-crypto = { version = "4.0.0", default-features = false, path = "../../primitives/application-crypto" } +sp-application-crypto = { version = "5.0.0", default-features = false, path = "../../primitives/application-crypto" } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [ "derive", ] } @@ -23,13 +23,13 @@ sp-std = { version = "4.0.0", default-features = false, path = "../../primitives pallet-session = { version = "4.0.0-dev", features = [ "historical", ], path = "../session", default-features = false } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } [features] default = ["std"] diff --git a/frame/authorship/Cargo.toml b/frame/authorship/Cargo.toml index c17fc49ecdcc1..31daa74553c23 100644 --- a/frame/authorship/Cargo.toml +++ b/frame/authorship/Cargo.toml @@ -19,14 +19,14 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-authorship = { version = "4.0.0-dev", default-features = false, path = "../../primitives/authorship" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } impl-trait-for-tuples = "0.2.1" [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } [features] default = ["std"] diff --git a/frame/babe/Cargo.toml b/frame/babe/Cargo.toml index 673af5c30ed6d..f48877746b888 100644 --- a/frame/babe/Cargo.toml +++ b/frame/babe/Cargo.toml @@ -21,11 +21,11 @@ frame-system = { version = "4.0.0-dev", default-features = false, path = "../sys pallet-authorship = { version = "4.0.0-dev", default-features = false, path = "../authorship" } pallet-session = { version = "4.0.0-dev", default-features = false, path = "../session" } pallet-timestamp = { version = "4.0.0-dev", default-features = false, path = "../timestamp" } -sp-application-crypto = { version = "4.0.0", default-features = false, path = "../../primitives/application-crypto" } +sp-application-crypto = { version = "5.0.0", default-features = false, path = "../../primitives/application-crypto" } sp-consensus-babe = { version = "0.10.0-dev", default-features = false, path = "../../primitives/consensus/babe" } sp-consensus-vrf = { version = "0.10.0-dev", default-features = false, path = "../../primitives/consensus/vrf" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-session = { version = "4.0.0-dev", default-features = false, path = "../../primitives/session" } sp-staking = { version = "4.0.0-dev", default-features = false, path = "../../primitives/staking" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } @@ -36,7 +36,7 @@ pallet-balances = { version = "4.0.0-dev", path = "../balances" } pallet-offences = { version = "4.0.0-dev", path = "../offences" } pallet-staking = { version = "4.0.0-dev", path = "../staking" } pallet-staking-reward-curve = { version = "4.0.0-dev", path = "../staking/reward-curve" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } frame-election-provider-support = { version = "4.0.0-dev", path = "../election-provider-support" } [features] diff --git a/frame/babe/src/mock.rs b/frame/babe/src/mock.rs index fa7a7b185b342..2e4b6023f1e5f 100644 --- a/frame/babe/src/mock.rs +++ b/frame/babe/src/mock.rs @@ -178,7 +178,7 @@ impl onchain::Config for Test { } impl pallet_staking::Config for Test { - const MAX_NOMINATIONS: u32 = 16; + type MaxNominations = ConstU32<16>; type RewardRemainder = (); type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; type Event = Event; diff --git a/frame/bags-list/Cargo.toml b/frame/bags-list/Cargo.toml index 9e802527f18d4..c35ff6fc6c39d 100644 --- a/frame/bags-list/Cargo.toml +++ b/frame/bags-list/Cargo.toml @@ -18,7 +18,7 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } # primitives -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } # FRAME @@ -32,13 +32,13 @@ log = { version = "0.4.14", default-features = false } # Optional imports for benchmarking frame-benchmarking = { version = "4.0.0-dev", path = "../benchmarking", optional = true, default-features = false } pallet-balances = { version = "4.0.0-dev", path = "../balances", optional = true, default-features = false } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core", optional = true, default-features = false } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io", optional = true, default-features = false } +sp-core = { version = "5.0.0", path = "../../primitives/core", optional = true, default-features = false } +sp-io = { version = "5.0.0", path = "../../primitives/io", optional = true, default-features = false } sp-tracing = { version = "4.0.0", path = "../../primitives/tracing", optional = true, default-features = false } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core"} -sp-io = { version = "4.0.0-dev", path = "../../primitives/io"} +sp-core = { version = "5.0.0", path = "../../primitives/core"} +sp-io = { version = "5.0.0", path = "../../primitives/io"} sp-tracing = { version = "4.0.0", path = "../../primitives/tracing" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } frame-election-provider-support = { version = "4.0.0-dev", path = "../election-provider-support", features = ["runtime-benchmarks"] } diff --git a/frame/bags-list/remote-tests/Cargo.toml b/frame/bags-list/remote-tests/Cargo.toml index d8797ad360ba4..8f3ce53f8ebb3 100644 --- a/frame/bags-list/remote-tests/Cargo.toml +++ b/frame/bags-list/remote-tests/Cargo.toml @@ -21,17 +21,15 @@ frame-system = { path = "../../system", version = "4.0.0-dev" } frame-support = { path = "../../support", version = "4.0.0-dev" } # core -sp-storage = { path = "../../../primitives/storage", version = "4.0.0" } -sp-core = { path = "../../../primitives/core", version = "4.1.0-dev" } +sp-storage = { path = "../../../primitives/storage", version = "5.0.0"} +sp-core = { path = "../../../primitives/core", version = "5.0.0"} sp-tracing = { path = "../../../primitives/tracing", version = "4.0.0" } -sp-runtime = { path = "../../../primitives/runtime", version = "4.1.0-dev" } +sp-runtime = { path = "../../../primitives/runtime", version = "5.0.0"} sp-std = { path = "../../../primitives/std", version = "4.0.0" } # utils remote-externalities = { path = "../../../utils/frame/remote-externalities", version = "0.10.0-dev" } # others -tokio = { version = "1", features = ["macros"] } log = "0.4.14" -structopt = "0.3.25" -clap = "2.34.0" +tokio = { version = "1", features = ["macros"] } diff --git a/frame/bags-list/src/list/mod.rs b/frame/bags-list/src/list/mod.rs index aba31b67b2863..8cd89b8fff1cc 100644 --- a/frame/bags-list/src/list/mod.rs +++ b/frame/bags-list/src/list/mod.rs @@ -545,7 +545,7 @@ impl List { /// iteration so that there's no incentive to churn ids positioning to improve the chances of /// appearing within the ids set. #[derive(DefaultNoBound, Encode, Decode, MaxEncodedLen, TypeInfo)] -#[codec(mel_bound(T: Config))] +#[codec(mel_bound())] #[scale_info(skip_type_params(T))] #[cfg_attr(feature = "std", derive(frame_support::DebugNoBound, Clone, PartialEq))] pub struct Bag { @@ -748,7 +748,7 @@ impl Bag { /// A Node is the fundamental element comprising the doubly-linked list described by `Bag`. #[derive(Encode, Decode, MaxEncodedLen, TypeInfo)] -#[codec(mel_bound(T: Config))] +#[codec(mel_bound())] #[scale_info(skip_type_params(T))] #[cfg_attr(feature = "std", derive(frame_support::DebugNoBound, Clone, PartialEq))] pub struct Node { diff --git a/frame/bags-list/src/weights.rs b/frame/bags-list/src/weights.rs index 5a8f51cc07c76..f35c0aaee6d6a 100644 --- a/frame/bags-list/src/weights.rs +++ b/frame/bags-list/src/weights.rs @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_bags_list //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2022-01-05, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-30, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,7 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/bags-list/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -57,7 +59,7 @@ impl WeightInfo for SubstrateWeight { // Storage: BagsList ListNodes (r:4 w:4) // Storage: BagsList ListBags (r:1 w:1) fn rebag_non_terminal() -> Weight { - (62_060_000 as Weight) + (46_965_000 as Weight) .saturating_add(T::DbWeight::get().reads(7 as Weight)) .saturating_add(T::DbWeight::get().writes(5 as Weight)) } @@ -66,7 +68,7 @@ impl WeightInfo for SubstrateWeight { // Storage: BagsList ListNodes (r:3 w:3) // Storage: BagsList ListBags (r:2 w:2) fn rebag_terminal() -> Weight { - (60_585_000 as Weight) + (45_952_000 as Weight) .saturating_add(T::DbWeight::get().reads(7 as Weight)) .saturating_add(T::DbWeight::get().writes(5 as Weight)) } @@ -76,7 +78,7 @@ impl WeightInfo for SubstrateWeight { // Storage: BagsList CounterForListNodes (r:1 w:1) // Storage: BagsList ListBags (r:1 w:1) fn put_in_front_of() -> Weight { - (69_779_000 as Weight) + (52_928_000 as Weight) .saturating_add(T::DbWeight::get().reads(10 as Weight)) .saturating_add(T::DbWeight::get().writes(6 as Weight)) } @@ -89,7 +91,7 @@ impl WeightInfo for () { // Storage: BagsList ListNodes (r:4 w:4) // Storage: BagsList ListBags (r:1 w:1) fn rebag_non_terminal() -> Weight { - (62_060_000 as Weight) + (46_965_000 as Weight) .saturating_add(RocksDbWeight::get().reads(7 as Weight)) .saturating_add(RocksDbWeight::get().writes(5 as Weight)) } @@ -98,7 +100,7 @@ impl WeightInfo for () { // Storage: BagsList ListNodes (r:3 w:3) // Storage: BagsList ListBags (r:2 w:2) fn rebag_terminal() -> Weight { - (60_585_000 as Weight) + (45_952_000 as Weight) .saturating_add(RocksDbWeight::get().reads(7 as Weight)) .saturating_add(RocksDbWeight::get().writes(5 as Weight)) } @@ -108,7 +110,7 @@ impl WeightInfo for () { // Storage: BagsList CounterForListNodes (r:1 w:1) // Storage: BagsList ListBags (r:1 w:1) fn put_in_front_of() -> Weight { - (69_779_000 as Weight) + (52_928_000 as Weight) .saturating_add(RocksDbWeight::get().reads(10 as Weight)) .saturating_add(RocksDbWeight::get().writes(6 as Weight)) } diff --git a/frame/balances/Cargo.toml b/frame/balances/Cargo.toml index 02b94fe606c49..f594e67ab861d 100644 --- a/frame/balances/Cargo.toml +++ b/frame/balances/Cargo.toml @@ -16,15 +16,15 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "2.2.0", default-features = false, features = ["derive", "max-encoded-len"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } log = { version = "0.4.14", default-features = false } [dev-dependencies] -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } pallet-transaction-payment = { version = "4.0.0-dev", path = "../transaction-payment" } [features] diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index f94afec069422..6bf37dfda037b 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -170,7 +170,7 @@ use frame_support::{ pallet_prelude::DispatchResult, traits::{ tokens::{fungible, BalanceStatus as Status, DepositConsequence, WithdrawConsequence}, - Currency, ExistenceRequirement, + Currency, DefensiveSaturating, ExistenceRequirement, ExistenceRequirement::{AllowDeath, KeepAlive}, Get, Imbalance, LockIdentifier, LockableCurrency, NamedReservableCurrency, OnUnbalanced, ReservableCurrency, SignedImbalance, StoredMap, TryDrop, WithdrawReasons, @@ -314,25 +314,32 @@ pub mod pallet { let new_free = if wipeout { Zero::zero() } else { new_free }; let new_reserved = if wipeout { Zero::zero() } else { new_reserved }; - let (free, reserved) = Self::mutate_account(&who, |account| { - if new_free > account.free { - mem::drop(PositiveImbalance::::new(new_free - account.free)); - } else if new_free < account.free { - mem::drop(NegativeImbalance::::new(account.free - new_free)); - } - - if new_reserved > account.reserved { - mem::drop(PositiveImbalance::::new(new_reserved - account.reserved)); - } else if new_reserved < account.reserved { - mem::drop(NegativeImbalance::::new(account.reserved - new_reserved)); - } + // First we try to modify the account's balance to the forced balance. + let (old_free, old_reserved) = Self::mutate_account(&who, |account| { + let old_free = account.free; + let old_reserved = account.reserved; account.free = new_free; account.reserved = new_reserved; - (account.free, account.reserved) + (old_free, old_reserved) })?; - Self::deposit_event(Event::BalanceSet { who, free, reserved }); + + // This will adjust the total issuance, which was not done by the `mutate_account` + // above. + if new_free > old_free { + mem::drop(PositiveImbalance::::new(new_free - old_free)); + } else if new_free < old_free { + mem::drop(NegativeImbalance::::new(old_free - new_free)); + } + + if new_reserved > old_reserved { + mem::drop(PositiveImbalance::::new(new_reserved - old_reserved)); + } else if new_reserved < old_reserved { + mem::drop(NegativeImbalance::::new(old_reserved - new_reserved)); + } + + Self::deposit_event(Event::BalanceSet { who, free: new_free, reserved: new_reserved }); Ok(().into()) } @@ -488,8 +495,29 @@ pub mod pallet { #[pallet::getter(fn total_issuance)] pub type TotalIssuance, I: 'static = ()> = StorageValue<_, T::Balance, ValueQuery>; - /// The balance of an account. + /// The Balances pallet example of storing the balance of an account. /// + /// # Example + /// + /// ```nocompile + /// impl pallet_balances::Config for Runtime { + /// type AccountStore = StorageMapShim, frame_system::Provider, AccountId, Self::AccountData> + /// } + /// ``` + /// + /// You can also store the balance of an account in the `System` pallet. + /// + /// # Example + /// + /// ```nocompile + /// impl pallet_balances::Config for Runtime { + /// type AccountStore = System + /// } + /// ``` + /// + /// But this comes with tradeoffs, storing account balances in the system pallet stores + /// `frame_system` data alongside the account data contrary to storing account balances in the + /// `Balances` pallet, which uses a `StorageMap` to store balances data only. /// NOTE: This is only used in the case that this pallet is used to store balances. #[pallet::storage] pub type Account, I: 'static = ()> = StorageMap< @@ -1496,7 +1524,7 @@ where .map_err(|_| Error::::LiquidityRestrictions)?; // TODO: This is over-conservative. There may now be other providers, and - // this pallet may not even be a provider. + // this pallet may not even be a provider. let allow_death = existence_requirement == ExistenceRequirement::AllowDeath; let allow_death = allow_death && system::Pallet::::can_dec_provider(transactor); @@ -1783,7 +1811,7 @@ where account.reserved -= actual; // defensive only: this can never fail since total issuance which is at least // free+reserved fits into the same data type. - account.free = account.free.saturating_add(actual); + account.free = account.free.defensive_saturating_add(actual); actual }) { Ok(x) => x, @@ -1896,7 +1924,7 @@ where match reserves.binary_search_by_key(id, |data| data.id) { Ok(index) => { // this add can't overflow but just to be defensive. - reserves[index].amount = reserves[index].amount.saturating_add(value); + reserves[index].amount = reserves[index].amount.defensive_saturating_add(value); }, Err(index) => { reserves @@ -1929,8 +1957,8 @@ where let remain = >::unreserve(who, to_change); - // remain should always be zero but just to be defensive here - let actual = to_change.saturating_sub(remain); + // remain should always be zero but just to be defensive here. + let actual = to_change.defensive_saturating_sub(remain); // `actual <= to_change` and `to_change <= amount`; qed; reserves[index].amount -= actual; @@ -1976,8 +2004,8 @@ where let (imb, remain) = >::slash_reserved(who, to_change); - // remain should always be zero but just to be defensive here - let actual = to_change.saturating_sub(remain); + // remain should always be zero but just to be defensive here. + let actual = to_change.defensive_saturating_sub(remain); // `actual <= to_change` and `to_change <= amount`; qed; reserves[index].amount -= actual; @@ -2036,12 +2064,12 @@ where )?; // remain should always be zero but just to be defensive - // here - let actual = to_change.saturating_sub(remain); + // here. + let actual = to_change.defensive_saturating_sub(remain); // this add can't overflow but just to be defensive. reserves[index].amount = - reserves[index].amount.saturating_add(actual); + reserves[index].amount.defensive_saturating_add(actual); Ok(actual) }, @@ -2056,7 +2084,7 @@ where // remain should always be zero but just to be defensive // here - let actual = to_change.saturating_sub(remain); + let actual = to_change.defensive_saturating_sub(remain); reserves .try_insert( @@ -2079,7 +2107,7 @@ where )?; // remain should always be zero but just to be defensive here - to_change.saturating_sub(remain) + to_change.defensive_saturating_sub(remain) }; // `actual <= to_change` and `to_change <= amount`; qed; diff --git a/frame/balances/src/tests.rs b/frame/balances/src/tests.rs index 638034d80cd52..8f5470ae3cac2 100644 --- a/frame/balances/src/tests.rs +++ b/frame/balances/src/tests.rs @@ -1239,5 +1239,29 @@ macro_rules! decl_tests { assert_eq!(Balances::free_balance(&3), 25); }); } + + #[test] + fn set_balance_handles_killing_account() { + <$ext_builder>::default().build().execute_with(|| { + let _ = Balances::deposit_creating(&1, 111); + assert_ok!(frame_system::Pallet::::inc_consumers(&1)); + assert_noop!( + Balances::set_balance(Origin::root(), 1, 0, 0), + DispatchError::ConsumerRemaining, + ); + }); + } + + #[test] + fn set_balance_handles_total_issuance() { + <$ext_builder>::default().build().execute_with(|| { + let old_total_issuance = Balances::total_issuance(); + assert_ok!(Balances::set_balance(Origin::root(), 1337, 69, 42)); + assert_eq!(Balances::total_issuance(), old_total_issuance + 69 + 42); + assert_eq!(Balances::total_balance(&1337), 69 + 42); + assert_eq!(Balances::free_balance(&1337), 69); + assert_eq!(Balances::reserved_balance(&1337), 42); + }); + } } } diff --git a/frame/balances/src/weights.rs b/frame/balances/src/weights.rs index a272753b73466..435438055b333 100644 --- a/frame/balances/src/weights.rs +++ b/frame/balances/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_balances //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-09-13, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-30, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/balances/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -59,43 +60,43 @@ pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { // Storage: System Account (r:1 w:1) fn transfer() -> Weight { - (70_952_000 as Weight) + (34_200_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: System Account (r:1 w:1) fn transfer_keep_alive() -> Weight { - (54_410_000 as Weight) + (27_263_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: System Account (r:1 w:1) fn set_balance_creating() -> Weight { - (29_176_000 as Weight) + (17_425_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: System Account (r:1 w:1) fn set_balance_killing() -> Weight { - (35_214_000 as Weight) + (19_979_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: System Account (r:2 w:2) fn force_transfer() -> Weight { - (71_780_000 as Weight) + (34_783_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: System Account (r:1 w:1) fn transfer_all() -> Weight { - (66_475_000 as Weight) + (31_620_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: System Account (r:1 w:1) fn force_unreserve() -> Weight { - (27_766_000 as Weight) + (15_750_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -105,43 +106,43 @@ impl WeightInfo for SubstrateWeight { impl WeightInfo for () { // Storage: System Account (r:1 w:1) fn transfer() -> Weight { - (70_952_000 as Weight) + (34_200_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: System Account (r:1 w:1) fn transfer_keep_alive() -> Weight { - (54_410_000 as Weight) + (27_263_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: System Account (r:1 w:1) fn set_balance_creating() -> Weight { - (29_176_000 as Weight) + (17_425_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: System Account (r:1 w:1) fn set_balance_killing() -> Weight { - (35_214_000 as Weight) + (19_979_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: System Account (r:2 w:2) fn force_transfer() -> Weight { - (71_780_000 as Weight) + (34_783_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: System Account (r:1 w:1) fn transfer_all() -> Weight { - (66_475_000 as Weight) + (31_620_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: System Account (r:1 w:1) fn force_unreserve() -> Weight { - (27_766_000 as Weight) + (15_750_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } diff --git a/frame/beefy-mmr/Cargo.toml b/frame/beefy-mmr/Cargo.toml index c793173cc22d8..f381d4c975776 100644 --- a/frame/beefy-mmr/Cargo.toml +++ b/frame/beefy-mmr/Cargo.toml @@ -13,7 +13,7 @@ codec = { version = "2.2.0", package = "parity-scale-codec", default-features = libsecp256k1 = { version = "0.7.0", default-features = false } log = { version = "0.4.13", default-features = false } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.132", optional = true } +serde = { version = "1.0.136", optional = true } frame-support = { version = "4.0.0-dev", path = "../support", default-features = false } frame-system = { version = "4.0.0-dev", path = "../system", default-features = false } @@ -21,9 +21,9 @@ pallet-mmr = { version = "4.0.0-dev", path = "../merkle-mountain-range", default pallet-mmr-primitives = { version = "4.0.0-dev", path = "../merkle-mountain-range/primitives", default-features = false } pallet-session = { version = "4.0.0-dev", path = "../session", default-features = false } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core", default-features = false } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io", default-features = false } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime", default-features = false } +sp-core = { version = "5.0.0", path = "../../primitives/core", default-features = false } +sp-io = { version = "5.0.0", path = "../../primitives/io", default-features = false } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime", default-features = false } sp-std = { version = "4.0.0", path = "../../primitives/std", default-features = false } beefy-merkle-tree = { version = "4.0.0-dev", path = "./primitives", default-features = false } diff --git a/frame/beefy-mmr/src/lib.rs b/frame/beefy-mmr/src/lib.rs index d66de51d9af21..38d0a6ac9a7f8 100644 --- a/frame/beefy-mmr/src/lib.rs +++ b/frame/beefy-mmr/src/lib.rs @@ -119,7 +119,6 @@ pub mod pallet { /// BEEFY-MMR pallet. #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] pub struct Pallet(_); /// The module's configuration trait. diff --git a/frame/beefy/Cargo.toml b/frame/beefy/Cargo.toml index 52471a332dd76..5844657dd50c4 100644 --- a/frame/beefy/Cargo.toml +++ b/frame/beefy/Cargo.toml @@ -10,12 +10,12 @@ description = "BEEFY FRAME pallet" [dependencies] codec = { version = "2.2.0", package = "parity-scale-codec", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.132", optional = true } +serde = { version = "1.0.136", optional = true } frame-support = { version = "4.0.0-dev", path = "../support", default-features = false } frame-system = { version = "4.0.0-dev", path = "../system", default-features = false } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime", default-features = false } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime", default-features = false } sp-std = { version = "4.0.0", path = "../../primitives/std", default-features = false } pallet-session = { version = "4.0.0-dev", path = "../session", default-features = false } @@ -23,8 +23,8 @@ pallet-session = { version = "4.0.0-dev", path = "../session", default-features beefy-primitives = { version = "4.0.0-dev", path = "../../primitives/beefy", default-features = false } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } sp-staking = { version = "4.0.0-dev", path = "../../primitives/staking" } [features] diff --git a/frame/benchmarking/Cargo.toml b/frame/benchmarking/Cargo.toml index ce110d8ba511f..ad6f99c645173 100644 --- a/frame/benchmarking/Cargo.toml +++ b/frame/benchmarking/Cargo.toml @@ -18,25 +18,27 @@ paste = "1.0" codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-api = { version = "4.0.0-dev", path = "../../primitives/api", default-features = false } -sp-runtime-interface = { version = "4.1.0-dev", path = "../../primitives/runtime-interface", default-features = false } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime", default-features = false } +sp-runtime-interface = { version = "5.0.0", path = "../../primitives/runtime-interface", default-features = false } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime", default-features = false } sp-std = { version = "4.0.0", path = "../../primitives/std", default-features = false } -sp-io = { version = "4.0.0", path = "../../primitives/io", default-features = false } -sp-application-crypto = { version = "4.0.0", path = "../../primitives/application-crypto", default-features = false } -sp-storage = { version = "4.0.0", path = "../../primitives/storage", default-features = false } +sp-io = { version = "5.0.0", path = "../../primitives/io", default-features = false } +sp-application-crypto = { version = "5.0.0", path = "../../primitives/application-crypto", default-features = false } +sp-storage = { version = "5.0.0", path = "../../primitives/storage", default-features = false } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } log = { version = "0.4.14", default-features = false } +serde = { version = "1.0.136", optional = true } [dev-dependencies] hex-literal = "0.3.4" -sp-keystore = { version = "0.10.0", path = "../../primitives/keystore" } +sp-keystore = { version = "0.11.0", path = "../../primitives/keystore" } [features] default = ["std"] std = [ "codec/std", "scale-info/std", + "serde", "sp-runtime-interface/std", "sp-runtime/std", "sp-api/std", diff --git a/frame/benchmarking/src/lib.rs b/frame/benchmarking/src/lib.rs index dcb6b0702995c..4b5c0534221ca 100644 --- a/frame/benchmarking/src/lib.rs +++ b/frame/benchmarking/src/lib.rs @@ -908,7 +908,7 @@ macro_rules! impl_bench_name_tests { // Every variant must implement [`BenchmarkingSetup`]. // // ```nocompile -// +// // struct Transfer; // impl BenchmarkingSetup for Transfer { ... } // @@ -1080,7 +1080,7 @@ macro_rules! impl_benchmark { // Time the storage root recalculation. let start_storage_root = $crate::benchmarking::current_time(); - $crate::storage_root(); + $crate::storage_root($crate::StateVersion::V1); let finish_storage_root = $crate::benchmarking::current_time(); let elapsed_storage_root = finish_storage_root - start_storage_root; diff --git a/frame/benchmarking/src/utils.rs b/frame/benchmarking/src/utils.rs index bb0b8d36a752e..8c642f74358db 100644 --- a/frame/benchmarking/src/utils.rs +++ b/frame/benchmarking/src/utils.rs @@ -22,12 +22,15 @@ use frame_support::{ pallet_prelude::*, traits::StorageInfo, }; +#[cfg(feature = "std")] +use serde::Serialize; use sp_io::hashing::blake2_256; use sp_runtime::traits::TrailingZeroInput; use sp_std::{prelude::Box, vec::Vec}; use sp_storage::TrackedStorageKey; /// An alphabet of possible parameters to use for benchmarking. +#[cfg_attr(feature = "std", derive(Serialize))] #[derive(Encode, Decode, Clone, Copy, PartialEq, Debug)] #[allow(missing_docs)] #[allow(non_camel_case_types)] @@ -68,13 +71,17 @@ impl std::fmt::Display for BenchmarkParameter { } /// The results of a single of benchmark. +#[cfg_attr(feature = "std", derive(Serialize))] #[derive(Encode, Decode, Clone, PartialEq, Debug)] pub struct BenchmarkBatch { /// The pallet containing this benchmark. + #[cfg_attr(feature = "std", serde(with = "serde_as_str"))] pub pallet: Vec, /// The instance of this pallet being benchmarked. + #[cfg_attr(feature = "std", serde(with = "serde_as_str"))] pub instance: Vec, /// The extrinsic (or benchmark name) of this benchmark. + #[cfg_attr(feature = "std", serde(with = "serde_as_str"))] pub benchmark: Vec, /// The results from this benchmark. pub results: Vec, @@ -82,13 +89,17 @@ pub struct BenchmarkBatch { // TODO: could probably make API cleaner here. /// The results of a single of benchmark, where time and db results are separated. +#[cfg_attr(feature = "std", derive(Serialize))] #[derive(Encode, Decode, Clone, PartialEq, Debug)] pub struct BenchmarkBatchSplitResults { /// The pallet containing this benchmark. + #[cfg_attr(feature = "std", serde(with = "serde_as_str"))] pub pallet: Vec, /// The instance of this pallet being benchmarked. + #[cfg_attr(feature = "std", serde(with = "serde_as_str"))] pub instance: Vec, /// The extrinsic (or benchmark name) of this benchmark. + #[cfg_attr(feature = "std", serde(with = "serde_as_str"))] pub benchmark: Vec, /// The extrinsic timing results from this benchmark. pub time_results: Vec, @@ -99,6 +110,7 @@ pub struct BenchmarkBatchSplitResults { /// Result from running benchmarks on a FRAME pallet. /// Contains duration of the function call in nanoseconds along with the benchmark parameters /// used for that benchmark result. +#[cfg_attr(feature = "std", derive(Serialize))] #[derive(Encode, Decode, Default, Clone, PartialEq, Debug)] pub struct BenchmarkResult { pub components: Vec<(BenchmarkParameter, u32)>, @@ -109,6 +121,7 @@ pub struct BenchmarkResult { pub writes: u32, pub repeat_writes: u32, pub proof_size: u32, + #[cfg_attr(feature = "std", serde(skip_serializing))] pub keys: Vec<(Vec, u32, u32, bool)>, } @@ -118,6 +131,18 @@ impl BenchmarkResult { } } +/// Helper module to make serde serialize `Vec` as strings. +#[cfg(feature = "std")] +mod serde_as_str { + pub fn serialize(value: &Vec, serializer: S) -> Result + where + S: serde::Serializer, + { + let s = std::str::from_utf8(value).map_err(serde::ser::Error::custom)?; + serializer.collect_str(s) + } +} + /// Possible errors returned from the benchmarking pipeline. #[derive(Clone, PartialEq, Debug)] pub enum BenchmarkError { diff --git a/frame/benchmarking/src/weights.rs b/frame/benchmarking/src/weights.rs index a4d46d24b6e3a..a49204fbf0b90 100644 --- a/frame/benchmarking/src/weights.rs +++ b/frame/benchmarking/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for frame_benchmarking //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-12-02, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-30, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,7 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/benchmarking/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -58,39 +60,37 @@ pub trait WeightInfo { pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { fn addition(_i: u32, ) -> Weight { - (284_000 as Weight) + (106_000 as Weight) } fn subtraction(_i: u32, ) -> Weight { - (279_000 as Weight) + (111_000 as Weight) } fn multiplication(_i: u32, ) -> Weight { - (278_000 as Weight) + (119_000 as Weight) } fn division(_i: u32, ) -> Weight { - (274_000 as Weight) + (111_000 as Weight) } - fn hashing(i: u32, ) -> Weight { - (33_441_957_000 as Weight) - // Standard Error: 535_000 - .saturating_add((363_000 as Weight).saturating_mul(i as Weight)) + fn hashing(_i: u32, ) -> Weight { + (21_203_386_000 as Weight) } fn sr25519_verification(i: u32, ) -> Weight { - (26_000 as Weight) - // Standard Error: 14_000 - .saturating_add((48_151_000 as Weight).saturating_mul(i as Weight)) + (0 as Weight) + // Standard Error: 6_000 + .saturating_add((47_077_000 as Weight).saturating_mul(i as Weight)) } // Storage: Skipped Metadata (r:0 w:0) fn storage_read(i: u32, ) -> Weight { (0 as Weight) - // Standard Error: 4_000 - .saturating_add((2_694_000 as Weight).saturating_mul(i as Weight)) + // Standard Error: 3_000 + .saturating_add((1_963_000 as Weight).saturating_mul(i as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(i as Weight))) } // Storage: Skipped Metadata (r:0 w:0) fn storage_write(i: u32, ) -> Weight { (0 as Weight) // Standard Error: 0 - .saturating_add((606_000 as Weight).saturating_mul(i as Weight)) + .saturating_add((364_000 as Weight).saturating_mul(i as Weight)) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) } } @@ -98,39 +98,37 @@ impl WeightInfo for SubstrateWeight { // For backwards compatibility and tests impl WeightInfo for () { fn addition(_i: u32, ) -> Weight { - (284_000 as Weight) + (106_000 as Weight) } fn subtraction(_i: u32, ) -> Weight { - (279_000 as Weight) + (111_000 as Weight) } fn multiplication(_i: u32, ) -> Weight { - (278_000 as Weight) + (119_000 as Weight) } fn division(_i: u32, ) -> Weight { - (274_000 as Weight) + (111_000 as Weight) } - fn hashing(i: u32, ) -> Weight { - (33_441_957_000 as Weight) - // Standard Error: 535_000 - .saturating_add((363_000 as Weight).saturating_mul(i as Weight)) + fn hashing(_i: u32, ) -> Weight { + (21_203_386_000 as Weight) } fn sr25519_verification(i: u32, ) -> Weight { - (26_000 as Weight) - // Standard Error: 14_000 - .saturating_add((48_151_000 as Weight).saturating_mul(i as Weight)) + (0 as Weight) + // Standard Error: 6_000 + .saturating_add((47_077_000 as Weight).saturating_mul(i as Weight)) } // Storage: Skipped Metadata (r:0 w:0) fn storage_read(i: u32, ) -> Weight { (0 as Weight) - // Standard Error: 4_000 - .saturating_add((2_694_000 as Weight).saturating_mul(i as Weight)) + // Standard Error: 3_000 + .saturating_add((1_963_000 as Weight).saturating_mul(i as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(i as Weight))) } // Storage: Skipped Metadata (r:0 w:0) fn storage_write(i: u32, ) -> Weight { (0 as Weight) // Standard Error: 0 - .saturating_add((606_000 as Weight).saturating_mul(i as Weight)) + .saturating_add((364_000 as Weight).saturating_mul(i as Weight)) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) } } diff --git a/frame/bounties/Cargo.toml b/frame/bounties/Cargo.toml index 73973ab18caaa..477815a306f3c 100644 --- a/frame/bounties/Cargo.toml +++ b/frame/bounties/Cargo.toml @@ -18,12 +18,12 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = ] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } pallet-treasury = { version = "4.0.0-dev", default-features = false, path = "../treasury" } -sp-io = { version = "4.0.0", path = "../../primitives/io", default-features = false } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core", default-features = false } +sp-io = { version = "5.0.0", path = "../../primitives/io", default-features = false } +sp-core = { version = "5.0.0", path = "../../primitives/core", default-features = false } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } log = { version = "0.4.14", default-features = false } diff --git a/frame/bounties/src/lib.rs b/frame/bounties/src/lib.rs index d46180f6bbe19..988b15c58a13f 100644 --- a/frame/bounties/src/lib.rs +++ b/frame/bounties/src/lib.rs @@ -107,7 +107,7 @@ type PositiveImbalanceOf = pallet_treasury::PositiveImbalanceOf; pub type BountyIndex = u32; /// A bounty proposal. -#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct Bounty { /// The account proposing it. proposer: AccountId, @@ -133,7 +133,7 @@ impl } /// The status of a bounty proposal. -#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub enum BountyStatus { /// The bounty is proposed and waiting for approval. Proposed, @@ -180,7 +180,6 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] pub struct Pallet(_); #[pallet::config] @@ -249,6 +248,8 @@ pub mod pallet { Premature, /// The bounty cannot be closed because it has active child-bounties. HasActiveChildBounty, + /// Too many approvals are already queued. + TooManyQueued, } #[pallet::event] @@ -288,12 +289,14 @@ pub mod pallet { /// The description of each bounty. #[pallet::storage] #[pallet::getter(fn bounty_descriptions)] - pub type BountyDescriptions = StorageMap<_, Twox64Concat, BountyIndex, Vec>; + pub type BountyDescriptions = + StorageMap<_, Twox64Concat, BountyIndex, BoundedVec>; /// Bounty indices that have been approved but not yet funded. #[pallet::storage] #[pallet::getter(fn bounty_approvals)] - pub type BountyApprovals = StorageValue<_, Vec, ValueQuery>; + pub type BountyApprovals = + StorageValue<_, BoundedVec, ValueQuery>; #[pallet::call] impl Pallet { @@ -341,7 +344,8 @@ pub mod pallet { bounty.status = BountyStatus::Approved; - BountyApprovals::::append(bounty_id); + BountyApprovals::::try_append(bounty_id) + .map_err(|()| Error::::TooManyQueued)?; Ok(()) })?; @@ -780,17 +784,15 @@ impl Pallet { description: Vec, value: BalanceOf, ) -> DispatchResult { - ensure!( - description.len() <= T::MaximumReasonLength::get() as usize, - Error::::ReasonTooBig - ); + let bounded_description: BoundedVec<_, _> = + description.try_into().map_err(|()| Error::::ReasonTooBig)?; ensure!(value >= T::BountyValueMinimum::get(), Error::::InvalidValue); let index = Self::bounty_count(); // reserve deposit for new bounty let bond = T::BountyDepositBase::get() + - T::DataDepositPerByte::get() * (description.len() as u32).into(); + T::DataDepositPerByte::get() * (bounded_description.len() as u32).into(); T::Currency::reserve(&proposer, bond) .map_err(|_| Error::::InsufficientProposersBalance)?; @@ -806,7 +808,7 @@ impl Pallet { }; Bounties::::insert(index, &bounty); - BountyDescriptions::::insert(index, description); + BountyDescriptions::::insert(index, bounded_description); Self::deposit_event(Event::::BountyProposed { index }); diff --git a/frame/bounties/src/weights.rs b/frame/bounties/src/weights.rs index 4cff3180ca795..405e11acea5aa 100644 --- a/frame/bounties/src/weights.rs +++ b/frame/bounties/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,23 +18,24 @@ //! Autogenerated weights for pallet_bounties //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-11-19, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-30, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// ./target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 // --repeat=20 -// --pallet -// pallet_bounties +// --pallet=pallet_bounties // --extrinsic=* // --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --output=./frame/bounties/src/ -// --template=./.maintain/frame-weight-template.hbs +// --output=./frame/bounties/src/weights.rs +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -66,43 +67,43 @@ impl WeightInfo for SubstrateWeight { // Storage: Bounties BountyDescriptions (r:0 w:1) // Storage: Bounties Bounties (r:0 w:1) fn propose_bounty(d: u32, ) -> Weight { - (58_161_000 as Weight) + (23_620_000 as Weight) // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(d as Weight)) + .saturating_add((2_000 as Weight).saturating_mul(d as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } // Storage: Bounties Bounties (r:1 w:1) // Storage: Bounties BountyApprovals (r:1 w:1) fn approve_bounty() -> Weight { - (20_000_000 as Weight) + (6_655_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Bounties Bounties (r:1 w:1) fn propose_curator() -> Weight { - (14_000_000 as Weight) + (5_720_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Bounties Bounties (r:1 w:1) // Storage: System Account (r:1 w:1) fn unassign_curator() -> Weight { - (62_000_000 as Weight) + (26_958_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Bounties Bounties (r:1 w:1) // Storage: System Account (r:1 w:1) fn accept_curator() -> Weight { - (55_000_000 as Weight) + (21_457_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Bounties Bounties (r:1 w:1) // Storage: ChildBounties ParentChildBounties (r:1 w:0) fn award_bounty() -> Weight { - (46_000_000 as Weight) + (17_483_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -111,7 +112,7 @@ impl WeightInfo for SubstrateWeight { // Storage: ChildBounties ChildrenCuratorFees (r:1 w:1) // Storage: Bounties BountyDescriptions (r:0 w:1) fn claim_bounty() -> Weight { - (185_000_000 as Weight) + (61_763_000 as Weight) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(6 as Weight)) } @@ -120,7 +121,7 @@ impl WeightInfo for SubstrateWeight { // Storage: System Account (r:1 w:1) // Storage: Bounties BountyDescriptions (r:0 w:1) fn close_bounty_proposed() -> Weight { - (82_000_000 as Weight) + (28_862_000 as Weight) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -129,13 +130,13 @@ impl WeightInfo for SubstrateWeight { // Storage: System Account (r:2 w:2) // Storage: Bounties BountyDescriptions (r:0 w:1) fn close_bounty_active() -> Weight { - (137_000_000 as Weight) + (45_129_000 as Weight) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } // Storage: Bounties Bounties (r:1 w:1) fn extend_bounty_expiry() -> Weight { - (33_000_000 as Weight) + (15_169_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -144,8 +145,8 @@ impl WeightInfo for SubstrateWeight { // Storage: System Account (r:2 w:2) fn spend_funds(b: u32, ) -> Weight { (0 as Weight) - // Standard Error: 191_000 - .saturating_add((81_116_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 14_000 + .saturating_add((28_850_000 as Weight).saturating_mul(b as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(b as Weight))) .saturating_add(T::DbWeight::get().writes(1 as Weight)) @@ -160,43 +161,43 @@ impl WeightInfo for () { // Storage: Bounties BountyDescriptions (r:0 w:1) // Storage: Bounties Bounties (r:0 w:1) fn propose_bounty(d: u32, ) -> Weight { - (58_161_000 as Weight) + (23_620_000 as Weight) // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(d as Weight)) + .saturating_add((2_000 as Weight).saturating_mul(d as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } // Storage: Bounties Bounties (r:1 w:1) // Storage: Bounties BountyApprovals (r:1 w:1) fn approve_bounty() -> Weight { - (20_000_000 as Weight) + (6_655_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Bounties Bounties (r:1 w:1) fn propose_curator() -> Weight { - (14_000_000 as Weight) + (5_720_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Bounties Bounties (r:1 w:1) // Storage: System Account (r:1 w:1) fn unassign_curator() -> Weight { - (62_000_000 as Weight) + (26_958_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Bounties Bounties (r:1 w:1) // Storage: System Account (r:1 w:1) fn accept_curator() -> Weight { - (55_000_000 as Weight) + (21_457_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Bounties Bounties (r:1 w:1) // Storage: ChildBounties ParentChildBounties (r:1 w:0) fn award_bounty() -> Weight { - (46_000_000 as Weight) + (17_483_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -205,7 +206,7 @@ impl WeightInfo for () { // Storage: ChildBounties ChildrenCuratorFees (r:1 w:1) // Storage: Bounties BountyDescriptions (r:0 w:1) fn claim_bounty() -> Weight { - (185_000_000 as Weight) + (61_763_000 as Weight) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(6 as Weight)) } @@ -214,7 +215,7 @@ impl WeightInfo for () { // Storage: System Account (r:1 w:1) // Storage: Bounties BountyDescriptions (r:0 w:1) fn close_bounty_proposed() -> Weight { - (82_000_000 as Weight) + (28_862_000 as Weight) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } @@ -223,13 +224,13 @@ impl WeightInfo for () { // Storage: System Account (r:2 w:2) // Storage: Bounties BountyDescriptions (r:0 w:1) fn close_bounty_active() -> Weight { - (137_000_000 as Weight) + (45_129_000 as Weight) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } // Storage: Bounties Bounties (r:1 w:1) fn extend_bounty_expiry() -> Weight { - (33_000_000 as Weight) + (15_169_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -238,8 +239,8 @@ impl WeightInfo for () { // Storage: System Account (r:2 w:2) fn spend_funds(b: u32, ) -> Weight { (0 as Weight) - // Standard Error: 191_000 - .saturating_add((81_116_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 14_000 + .saturating_add((28_850_000 as Weight).saturating_mul(b as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(b as Weight))) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) diff --git a/frame/child-bounties/Cargo.toml b/frame/child-bounties/Cargo.toml index 742110a58bff7..0eeefd4de4595 100644 --- a/frame/child-bounties/Cargo.toml +++ b/frame/child-bounties/Cargo.toml @@ -18,13 +18,13 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = ] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } pallet-treasury = { version = "4.0.0-dev", default-features = false, path = "../treasury" } pallet-bounties = { version = "4.0.0-dev", default-features = false, path = "../bounties" } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io", default-features = false } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core", default-features = false } +sp-io = { version = "5.0.0", path = "../../primitives/io", default-features = false } +sp-core = { version = "5.0.0", path = "../../primitives/core", default-features = false } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } log = { version = "0.4.14", default-features = false } diff --git a/frame/child-bounties/src/weights.rs b/frame/child-bounties/src/weights.rs index 1662984aa7a3a..002388810b8a0 100644 --- a/frame/child-bounties/src/weights.rs +++ b/frame/child-bounties/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,23 +18,24 @@ //! Autogenerated weights for pallet_child_bounties //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-12-03, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-30, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// ./target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 // --repeat=20 -// --pallet -// pallet_child_bounties +// --pallet=pallet_child_bounties // --extrinsic=* // --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --output=./frame/child-bounties/src/ -// --template=./.maintain/frame-weight-template.hbs +// --output=./frame/child-bounties/src/weights.rs +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -65,9 +66,9 @@ impl WeightInfo for SubstrateWeight { // Storage: ChildBounties ChildBountyDescriptions (r:0 w:1) // Storage: ChildBounties ChildBounties (r:0 w:1) fn add_child_bounty(d: u32, ) -> Weight { - (113_579_000 as Weight) - // Standard Error: 1_000 - .saturating_add((4_000 as Weight).saturating_mul(d as Weight)) + (44_503_000 as Weight) + // Standard Error: 0 + .saturating_add((3_000 as Weight).saturating_mul(d as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(6 as Weight)) } @@ -75,7 +76,7 @@ impl WeightInfo for SubstrateWeight { // Storage: ChildBounties ChildBounties (r:1 w:1) // Storage: ChildBounties ChildrenCuratorFees (r:1 w:1) fn propose_curator() -> Weight { - (24_000_000 as Weight) + (11_661_000 as Weight) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -83,7 +84,7 @@ impl WeightInfo for SubstrateWeight { // Storage: ChildBounties ChildBounties (r:1 w:1) // Storage: System Account (r:1 w:1) fn accept_curator() -> Weight { - (55_000_000 as Weight) + (24_162_000 as Weight) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -91,14 +92,14 @@ impl WeightInfo for SubstrateWeight { // Storage: Bounties Bounties (r:1 w:0) // Storage: System Account (r:1 w:1) fn unassign_curator() -> Weight { - (61_000_000 as Weight) + (27_924_000 as Weight) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Bounties Bounties (r:1 w:0) // Storage: ChildBounties ChildBounties (r:1 w:1) fn award_child_bounty() -> Weight { - (42_000_000 as Weight) + (19_332_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -107,7 +108,7 @@ impl WeightInfo for SubstrateWeight { // Storage: ChildBounties ParentChildBounties (r:1 w:1) // Storage: ChildBounties ChildBountyDescriptions (r:0 w:1) fn claim_child_bounty() -> Weight { - (153_000_000 as Weight) + (60_363_000 as Weight) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(6 as Weight)) } @@ -118,7 +119,7 @@ impl WeightInfo for SubstrateWeight { // Storage: System Account (r:2 w:2) // Storage: ChildBounties ChildBountyDescriptions (r:0 w:1) fn close_child_bounty_added() -> Weight { - (101_000_000 as Weight) + (42_415_000 as Weight) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(6 as Weight)) } @@ -129,7 +130,7 @@ impl WeightInfo for SubstrateWeight { // Storage: ChildBounties ParentChildBounties (r:1 w:1) // Storage: ChildBounties ChildBountyDescriptions (r:0 w:1) fn close_child_bounty_active() -> Weight { - (130_000_000 as Weight) + (52_743_000 as Weight) .saturating_add(T::DbWeight::get().reads(7 as Weight)) .saturating_add(T::DbWeight::get().writes(7 as Weight)) } @@ -144,9 +145,9 @@ impl WeightInfo for () { // Storage: ChildBounties ChildBountyDescriptions (r:0 w:1) // Storage: ChildBounties ChildBounties (r:0 w:1) fn add_child_bounty(d: u32, ) -> Weight { - (113_579_000 as Weight) - // Standard Error: 1_000 - .saturating_add((4_000 as Weight).saturating_mul(d as Weight)) + (44_503_000 as Weight) + // Standard Error: 0 + .saturating_add((3_000 as Weight).saturating_mul(d as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(6 as Weight)) } @@ -154,7 +155,7 @@ impl WeightInfo for () { // Storage: ChildBounties ChildBounties (r:1 w:1) // Storage: ChildBounties ChildrenCuratorFees (r:1 w:1) fn propose_curator() -> Weight { - (24_000_000 as Weight) + (11_661_000 as Weight) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -162,7 +163,7 @@ impl WeightInfo for () { // Storage: ChildBounties ChildBounties (r:1 w:1) // Storage: System Account (r:1 w:1) fn accept_curator() -> Weight { - (55_000_000 as Weight) + (24_162_000 as Weight) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -170,14 +171,14 @@ impl WeightInfo for () { // Storage: Bounties Bounties (r:1 w:0) // Storage: System Account (r:1 w:1) fn unassign_curator() -> Weight { - (61_000_000 as Weight) + (27_924_000 as Weight) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Bounties Bounties (r:1 w:0) // Storage: ChildBounties ChildBounties (r:1 w:1) fn award_child_bounty() -> Weight { - (42_000_000 as Weight) + (19_332_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -186,7 +187,7 @@ impl WeightInfo for () { // Storage: ChildBounties ParentChildBounties (r:1 w:1) // Storage: ChildBounties ChildBountyDescriptions (r:0 w:1) fn claim_child_bounty() -> Weight { - (153_000_000 as Weight) + (60_363_000 as Weight) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(6 as Weight)) } @@ -197,7 +198,7 @@ impl WeightInfo for () { // Storage: System Account (r:2 w:2) // Storage: ChildBounties ChildBountyDescriptions (r:0 w:1) fn close_child_bounty_added() -> Weight { - (101_000_000 as Weight) + (42_415_000 as Weight) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(6 as Weight)) } @@ -208,7 +209,7 @@ impl WeightInfo for () { // Storage: ChildBounties ParentChildBounties (r:1 w:1) // Storage: ChildBounties ChildBountyDescriptions (r:0 w:1) fn close_child_bounty_active() -> Weight { - (130_000_000 as Weight) + (52_743_000 as Weight) .saturating_add(RocksDbWeight::get().reads(7 as Weight)) .saturating_add(RocksDbWeight::get().writes(7 as Weight)) } diff --git a/frame/collective/Cargo.toml b/frame/collective/Cargo.toml index bd0573bace666..334b4945afa2b 100644 --- a/frame/collective/Cargo.toml +++ b/frame/collective/Cargo.toml @@ -17,9 +17,9 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = log = { version = "0.4.14", default-features = false } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 3e3b923d6ee37..49328aa0bdc68 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -990,8 +990,8 @@ where pub struct EnsureMember(PhantomData<(AccountId, I)>); impl< O: Into, O>> + From>, - AccountId: Default, I, + AccountId: Decode, > EnsureOrigin for EnsureMember { type Success = AccountId; @@ -1004,7 +1004,10 @@ impl< #[cfg(feature = "runtime-benchmarks")] fn successful_origin() -> O { - O::from(RawOrigin::Member(Default::default())) + let zero_account_id = + AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()) + .expect("infinite length input; no invalid inputs for type; qed"); + O::from(RawOrigin::Member(zero_account_id)) } } diff --git a/frame/collective/src/tests.rs b/frame/collective/src/tests.rs index 4f40e02732b4c..f77e52a9b6fe9 100644 --- a/frame/collective/src/tests.rs +++ b/frame/collective/src/tests.rs @@ -175,7 +175,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { } fn make_proposal(value: u64) -> Call { - Call::System(frame_system::Call::remark { remark: value.encode() }) + Call::System(frame_system::Call::remark_with_event { remark: value.to_be_bytes().to_vec() }) } fn record(event: Event) -> EventRecord { diff --git a/frame/collective/src/weights.rs b/frame/collective/src/weights.rs index bdb07834a66c9..1280ced89eeea 100644 --- a/frame/collective/src/weights.rs +++ b/frame/collective/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_collective //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-30, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/collective/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -60,132 +61,132 @@ pub trait WeightInfo { /// Weights for pallet_collective using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - // Storage: Instance1Collective Members (r:1 w:1) - // Storage: Instance1Collective Proposals (r:1 w:0) - // Storage: Instance1Collective Voting (r:100 w:100) - // Storage: Instance1Collective Prime (r:0 w:1) + // Storage: Council Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: Council Voting (r:100 w:100) + // Storage: Council Prime (r:0 w:1) fn set_members(m: u32, n: u32, p: u32, ) -> Weight { (0 as Weight) - // Standard Error: 4_000 - .saturating_add((14_084_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 4_000 - .saturating_add((161_000 as Weight).saturating_mul(n as Weight)) - // Standard Error: 4_000 - .saturating_add((19_201_000 as Weight).saturating_mul(p as Weight)) + // Standard Error: 10_000 + .saturating_add((14_493_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 10_000 + .saturating_add((23_000 as Weight).saturating_mul(n as Weight)) + // Standard Error: 10_000 + .saturating_add((16_909_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(p as Weight))) .saturating_add(T::DbWeight::get().writes(2 as Weight)) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) } - // Storage: Instance1Collective Members (r:1 w:0) + // Storage: Council Members (r:1 w:0) fn execute(b: u32, m: u32, ) -> Weight { - (22_748_000 as Weight) + (12_790_000 as Weight) // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(b as Weight)) + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) // Standard Error: 0 - .saturating_add((92_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((73_000 as Weight).saturating_mul(m as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) } - // Storage: Instance1Collective Members (r:1 w:0) - // Storage: Instance1Collective ProposalOf (r:1 w:0) + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:0) fn propose_execute(b: u32, m: u32, ) -> Weight { - (27_465_000 as Weight) + (15_087_000 as Weight) // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(b as Weight)) + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) // Standard Error: 0 - .saturating_add((178_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((135_000 as Weight).saturating_mul(m as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) } - // Storage: Instance1Collective Members (r:1 w:0) - // Storage: Instance1Collective ProposalOf (r:1 w:1) - // Storage: Instance1Collective Proposals (r:1 w:1) - // Storage: Instance1Collective ProposalCount (r:1 w:1) - // Storage: Instance1Collective Voting (r:0 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalCount (r:1 w:1) + // Storage: Council Voting (r:0 w:1) fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { - (39_869_000 as Weight) + (18_269_000 as Weight) // Standard Error: 0 .saturating_add((8_000 as Weight).saturating_mul(b as Weight)) // Standard Error: 1_000 - .saturating_add((107_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((77_000 as Weight).saturating_mul(m as Weight)) // Standard Error: 1_000 - .saturating_add((406_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((203_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } - // Storage: Instance1Collective Members (r:1 w:0) - // Storage: Instance1Collective Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Voting (r:1 w:1) fn vote(m: u32, ) -> Weight { - (37_387_000 as Weight) + (26_624_000 as Weight) // Standard Error: 2_000 - .saturating_add((223_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((161_000 as Weight).saturating_mul(m as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } - // Storage: Instance1Collective Voting (r:1 w:1) - // Storage: Instance1Collective Members (r:1 w:0) - // Storage: Instance1Collective Proposals (r:1 w:1) - // Storage: Instance1Collective ProposalOf (r:0 w:1) + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalOf (r:0 w:1) fn close_early_disapproved(m: u32, p: u32, ) -> Weight { - (45_670_000 as Weight) + (26_527_000 as Weight) // Standard Error: 1_000 - .saturating_add((170_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((127_000 as Weight).saturating_mul(m as Weight)) // Standard Error: 1_000 - .saturating_add((358_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((155_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Collective Voting (r:1 w:1) - // Storage: Instance1Collective Members (r:1 w:0) - // Storage: Instance1Collective ProposalOf (r:1 w:1) - // Storage: Instance1Collective Proposals (r:1 w:1) + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { - (52_529_000 as Weight) + (26_352_000 as Weight) // Standard Error: 0 - .saturating_add((7_000 as Weight).saturating_mul(b as Weight)) + .saturating_add((6_000 as Weight).saturating_mul(b as Weight)) // Standard Error: 1_000 - .saturating_add((206_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((154_000 as Weight).saturating_mul(m as Weight)) // Standard Error: 1_000 - .saturating_add((412_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((203_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Collective Voting (r:1 w:1) - // Storage: Instance1Collective Members (r:1 w:0) - // Storage: Instance1Collective Prime (r:1 w:0) - // Storage: Instance1Collective Proposals (r:1 w:1) - // Storage: Instance1Collective ProposalOf (r:0 w:1) + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Prime (r:1 w:0) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalOf (r:0 w:1) fn close_disapproved(m: u32, p: u32, ) -> Weight { - (50_427_000 as Weight) + (28_638_000 as Weight) // Standard Error: 1_000 - .saturating_add((170_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((133_000 as Weight).saturating_mul(m as Weight)) // Standard Error: 1_000 - .saturating_add((354_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((162_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Collective Voting (r:1 w:1) - // Storage: Instance1Collective Members (r:1 w:0) - // Storage: Instance1Collective Prime (r:1 w:0) - // Storage: Instance1Collective ProposalOf (r:1 w:1) - // Storage: Instance1Collective Proposals (r:1 w:1) + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Prime (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { - (57_031_000 as Weight) + (29_946_000 as Weight) // Standard Error: 0 - .saturating_add((7_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 1_000 - .saturating_add((208_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((408_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((5_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 2_000 + .saturating_add((151_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 2_000 + .saturating_add((201_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Collective Proposals (r:1 w:1) - // Storage: Instance1Collective Voting (r:0 w:1) - // Storage: Instance1Collective ProposalOf (r:0 w:1) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council Voting (r:0 w:1) + // Storage: Council ProposalOf (r:0 w:1) fn disapprove_proposal(p: u32, ) -> Weight { - (27_458_000 as Weight) + (15_778_000 as Weight) // Standard Error: 1_000 - .saturating_add((402_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((206_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -193,132 +194,132 @@ impl WeightInfo for SubstrateWeight { // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Instance1Collective Members (r:1 w:1) - // Storage: Instance1Collective Proposals (r:1 w:0) - // Storage: Instance1Collective Voting (r:100 w:100) - // Storage: Instance1Collective Prime (r:0 w:1) + // Storage: Council Members (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: Council Voting (r:100 w:100) + // Storage: Council Prime (r:0 w:1) fn set_members(m: u32, n: u32, p: u32, ) -> Weight { (0 as Weight) - // Standard Error: 4_000 - .saturating_add((14_084_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 4_000 - .saturating_add((161_000 as Weight).saturating_mul(n as Weight)) - // Standard Error: 4_000 - .saturating_add((19_201_000 as Weight).saturating_mul(p as Weight)) + // Standard Error: 10_000 + .saturating_add((14_493_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 10_000 + .saturating_add((23_000 as Weight).saturating_mul(n as Weight)) + // Standard Error: 10_000 + .saturating_add((16_909_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(p as Weight))) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) } - // Storage: Instance1Collective Members (r:1 w:0) + // Storage: Council Members (r:1 w:0) fn execute(b: u32, m: u32, ) -> Weight { - (22_748_000 as Weight) + (12_790_000 as Weight) // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(b as Weight)) + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) // Standard Error: 0 - .saturating_add((92_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((73_000 as Weight).saturating_mul(m as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) } - // Storage: Instance1Collective Members (r:1 w:0) - // Storage: Instance1Collective ProposalOf (r:1 w:0) + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:0) fn propose_execute(b: u32, m: u32, ) -> Weight { - (27_465_000 as Weight) + (15_087_000 as Weight) // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(b as Weight)) + .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) // Standard Error: 0 - .saturating_add((178_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((135_000 as Weight).saturating_mul(m as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) } - // Storage: Instance1Collective Members (r:1 w:0) - // Storage: Instance1Collective ProposalOf (r:1 w:1) - // Storage: Instance1Collective Proposals (r:1 w:1) - // Storage: Instance1Collective ProposalCount (r:1 w:1) - // Storage: Instance1Collective Voting (r:0 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalCount (r:1 w:1) + // Storage: Council Voting (r:0 w:1) fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { - (39_869_000 as Weight) + (18_269_000 as Weight) // Standard Error: 0 .saturating_add((8_000 as Weight).saturating_mul(b as Weight)) // Standard Error: 1_000 - .saturating_add((107_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((77_000 as Weight).saturating_mul(m as Weight)) // Standard Error: 1_000 - .saturating_add((406_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((203_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } - // Storage: Instance1Collective Members (r:1 w:0) - // Storage: Instance1Collective Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Voting (r:1 w:1) fn vote(m: u32, ) -> Weight { - (37_387_000 as Weight) + (26_624_000 as Weight) // Standard Error: 2_000 - .saturating_add((223_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((161_000 as Weight).saturating_mul(m as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } - // Storage: Instance1Collective Voting (r:1 w:1) - // Storage: Instance1Collective Members (r:1 w:0) - // Storage: Instance1Collective Proposals (r:1 w:1) - // Storage: Instance1Collective ProposalOf (r:0 w:1) + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalOf (r:0 w:1) fn close_early_disapproved(m: u32, p: u32, ) -> Weight { - (45_670_000 as Weight) + (26_527_000 as Weight) // Standard Error: 1_000 - .saturating_add((170_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((127_000 as Weight).saturating_mul(m as Weight)) // Standard Error: 1_000 - .saturating_add((358_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((155_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Collective Voting (r:1 w:1) - // Storage: Instance1Collective Members (r:1 w:0) - // Storage: Instance1Collective ProposalOf (r:1 w:1) - // Storage: Instance1Collective Proposals (r:1 w:1) + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { - (52_529_000 as Weight) + (26_352_000 as Weight) // Standard Error: 0 - .saturating_add((7_000 as Weight).saturating_mul(b as Weight)) + .saturating_add((6_000 as Weight).saturating_mul(b as Weight)) // Standard Error: 1_000 - .saturating_add((206_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((154_000 as Weight).saturating_mul(m as Weight)) // Standard Error: 1_000 - .saturating_add((412_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((203_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Collective Voting (r:1 w:1) - // Storage: Instance1Collective Members (r:1 w:0) - // Storage: Instance1Collective Prime (r:1 w:0) - // Storage: Instance1Collective Proposals (r:1 w:1) - // Storage: Instance1Collective ProposalOf (r:0 w:1) + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Prime (r:1 w:0) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council ProposalOf (r:0 w:1) fn close_disapproved(m: u32, p: u32, ) -> Weight { - (50_427_000 as Weight) + (28_638_000 as Weight) // Standard Error: 1_000 - .saturating_add((170_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((133_000 as Weight).saturating_mul(m as Weight)) // Standard Error: 1_000 - .saturating_add((354_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((162_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Collective Voting (r:1 w:1) - // Storage: Instance1Collective Members (r:1 w:0) - // Storage: Instance1Collective Prime (r:1 w:0) - // Storage: Instance1Collective ProposalOf (r:1 w:1) - // Storage: Instance1Collective Proposals (r:1 w:1) + // Storage: Council Voting (r:1 w:1) + // Storage: Council Members (r:1 w:0) + // Storage: Council Prime (r:1 w:0) + // Storage: Council ProposalOf (r:1 w:1) + // Storage: Council Proposals (r:1 w:1) fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { - (57_031_000 as Weight) + (29_946_000 as Weight) // Standard Error: 0 - .saturating_add((7_000 as Weight).saturating_mul(b as Weight)) - // Standard Error: 1_000 - .saturating_add((208_000 as Weight).saturating_mul(m as Weight)) - // Standard Error: 1_000 - .saturating_add((408_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((5_000 as Weight).saturating_mul(b as Weight)) + // Standard Error: 2_000 + .saturating_add((151_000 as Weight).saturating_mul(m as Weight)) + // Standard Error: 2_000 + .saturating_add((201_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Collective Proposals (r:1 w:1) - // Storage: Instance1Collective Voting (r:0 w:1) - // Storage: Instance1Collective ProposalOf (r:0 w:1) + // Storage: Council Proposals (r:1 w:1) + // Storage: Council Voting (r:0 w:1) + // Storage: Council ProposalOf (r:0 w:1) fn disapprove_proposal(p: u32, ) -> Weight { - (27_458_000 as Weight) + (15_778_000 as Weight) // Standard Error: 1_000 - .saturating_add((402_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((206_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } diff --git a/frame/contracts/Cargo.toml b/frame/contracts/Cargo.toml index f0d2833c61fd2..f24e393daa2ee 100644 --- a/frame/contracts/Cargo.toml +++ b/frame/contracts/Cargo.toml @@ -36,11 +36,11 @@ rand_pcg = { version = "0.3", optional = true } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } -pallet-contracts-primitives = { version = "4.0.0-dev", default-features = false, path = "common" } +pallet-contracts-primitives = { version = "5.0.0", default-features = false, path = "common" } pallet-contracts-proc-macro = { version = "4.0.0-dev", path = "proc-macro" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-sandbox = { version = "0.10.0-dev", default-features = false, path = "../../primitives/sandbox" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } diff --git a/frame/contracts/README.md b/frame/contracts/README.md index 50e43ddb998a7..8a8e4918f2e41 100644 --- a/frame/contracts/README.md +++ b/frame/contracts/README.md @@ -101,7 +101,7 @@ by block production. A good starting point for observing them on the console is command line in the root directory of the substrate repository: ```bash -cargo run --release -- --dev --tmp -lerror,runtime::contracts=debug +cargo run --release -- --dev -lerror,runtime::contracts=debug ``` This raises the log level of `runtime::contracts` to `debug` and all other targets diff --git a/frame/contracts/common/Cargo.toml b/frame/contracts/common/Cargo.toml index 05bfc212e3058..ad934c41a71fc 100644 --- a/frame/contracts/common/Cargo.toml +++ b/frame/contracts/common/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pallet-contracts-primitives" -version = "4.0.0-dev" +version = "5.0.0" authors = ["Parity Technologies "] edition = "2021" license = "Apache-2.0" @@ -19,10 +19,10 @@ scale-info = { version = "1.0", default-features = false, features = ["derive"] serde = { version = "1", features = ["derive"], optional = true } # Substrate Dependencies (This crate should not rely on frame) -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core", default-features = false } +sp-core = { version = "5.0.0", path = "../../../primitives/core", default-features = false } sp-std = { version = "4.0.0", default-features = false, path = "../../../primitives/std" } -sp-rpc = { version = "4.0.0-dev", path = "../../../primitives/rpc", optional = true } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } +sp-rpc = { version = "5.0.0", path = "../../../primitives/rpc", optional = true } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } [features] default = ["std"] diff --git a/frame/contracts/fixtures/delegate_call.wat b/frame/contracts/fixtures/delegate_call.wat new file mode 100644 index 0000000000000..e1c5fa813e590 --- /dev/null +++ b/frame/contracts/fixtures/delegate_call.wat @@ -0,0 +1,111 @@ +(module + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_get_storage" (func $seal_get_storage (param i32 i32 i32) (result i32))) + (import "seal0" "seal_set_storage" (func $seal_set_storage (param i32 i32 i32))) + (import "__unstable__" "seal_delegate_call" (func $seal_delegate_call (param i32 i32 i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 3 3)) + + ;; [0, 32) storage key + (data (i32.const 0) "\01") + + ;; [32, 64) storage key + (data (i32.const 32) "\02") + + ;; [64, 96) buffer where input is copied + + ;; [96, 100) size of the input buffer + (data (i32.const 96) "\20") + + ;; [100, 104) size of buffer for seal_get_storage + (data (i32.const 100) "\20") + + ;; [104, 136) seal_get_storage buffer + + (func $assert (param i32) + (block $ok + (br_if $ok + (get_local 0) + ) + (unreachable) + ) + ) + + (func (export "call") + (local $exit_code i32) + + ;; Reading "callee" code_hash + (call $seal_input (i32.const 64) (i32.const 96)) + + ;; assert input size == 32 + (call $assert + (i32.eq + (i32.load (i32.const 96)) + (i32.const 32) + ) + ) + + ;; place a value in storage, the size of which is specified by the call input. + (call $seal_set_storage + (i32.const 0) ;; Pointer to storage key + (i32.const 32) ;; Pointer to initial value + (i32.load (i32.const 100)) ;; Size of value + ) + + (call $assert + (i32.eq + (call $seal_get_storage + (i32.const 0) ;; Pointer to storage key + (i32.const 104) ;; buffer where to copy result + (i32.const 100) ;; pointer to size of buffer + ) + (i32.const 0) ;; ReturnCode::Success + ) + ) + + (call $assert + (i32.eq + (i32.load (i32.const 104)) ;; value received from storage + (i32.load (i32.const 32)) ;; initial value + ) + ) + + ;; Call deployed library contract code. + (set_local $exit_code + (call $seal_delegate_call + (i32.const 0) ;; Set no call flags + (i32.const 64) ;; Pointer to "callee" code_hash. + (i32.const 0) ;; Input is ignored + (i32.const 0) ;; Length of the input + (i32.const 4294967295) ;; u32 max sentinel value: do not copy output + (i32.const 0) ;; Length is ignored in this case + ) + ) + + ;; Check for success exit status. + (call $assert + (i32.eq (get_local $exit_code) (i32.const 0)) ;; ReturnCode::Success + ) + + (call $assert + (i32.eq + (call $seal_get_storage + (i32.const 0) ;; Pointer to storage key + (i32.const 104) ;; buffer where to copy result + (i32.const 100) ;; pointer to size of buffer + ) + (i32.const 0) ;; ReturnCode::Success + ) + ) + + ;; Make sure that 'callee' code changed the value + (call $assert + (i32.eq + (i32.load (i32.const 104)) + (i32.const 1) + ) + ) + ) + + (func (export "deploy")) + +) diff --git a/frame/contracts/fixtures/delegate_call_lib.wat b/frame/contracts/fixtures/delegate_call_lib.wat new file mode 100644 index 0000000000000..340b9699f8755 --- /dev/null +++ b/frame/contracts/fixtures/delegate_call_lib.wat @@ -0,0 +1,79 @@ +(module + (import "seal0" "seal_set_storage" (func $seal_set_storage (param i32 i32 i32))) + (import "seal0" "seal_caller" (func $seal_caller (param i32 i32))) + (import "seal0" "seal_value_transferred" (func $seal_value_transferred (param i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 32) storage key + (data (i32.const 0) "\01") + + ;; [32, 64) buffer for transferred value + + ;; [64, 96) size of the buffer for transferred value + (data (i32.const 64) "\20") + + ;; [96, 128) buffer for the caller + + ;; [128, 160) size of the buffer for caller + (data (i32.const 128) "\20") + + (func $assert (param i32) + (block $ok + (br_if $ok + (get_local 0) + ) + (unreachable) + ) + ) + + (func (export "call") + ;; place a value in storage + (call $seal_set_storage + (i32.const 0) ;; Pointer to storage key + (i32.const 0) ;; Pointer to value + (i32.const 32) ;; Size of value + ) + + ;; This stores the value transferred in the buffer + (call $seal_value_transferred (i32.const 32) (i32.const 64)) + + ;; assert len == 8 + (call $assert + (i32.eq + (i32.load (i32.const 64)) + (i32.const 8) + ) + ) + + ;; assert that contents of the buffer is equal to the value + ;; passed to the `caller` contract: 1337 + (call $assert + (i64.eq + (i64.load (i32.const 32)) + (i64.const 1337) + ) + ) + + ;; fill the buffer with the caller. + (call $seal_caller (i32.const 96) (i32.const 128)) + + ;; assert len == 32 + (call $assert + (i32.eq + (i32.load (i32.const 128)) + (i32.const 32) + ) + ) + + ;; assert that the first 64 byte are the beginning of "ALICE", + ;; who is the caller of the `caller` contract + (call $assert + (i64.eq + (i64.load (i32.const 96)) + (i64.const 0x0101010101010101) + ) + ) + ) + + (func (export "deploy")) +) diff --git a/frame/contracts/rpc/Cargo.toml b/frame/contracts/rpc/Cargo.toml index 9a88013c34083..52ca0e6d83454 100644 --- a/frame/contracts/rpc/Cargo.toml +++ b/frame/contracts/rpc/Cargo.toml @@ -20,13 +20,13 @@ jsonrpc-derive = "18.0.0" serde = { version = "1", features = ["derive"] } # Substrate Dependencies -pallet-contracts-primitives = { version = "4.0.0-dev", path = "../common" } +pallet-contracts-primitives = { version = "5.0.0", path = "../common" } pallet-contracts-rpc-runtime-api = { version = "4.0.0-dev", path = "./runtime-api" } sp-api = { version = "4.0.0-dev", path = "../../../primitives/api" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } -sp-rpc = { version = "4.0.0-dev", path = "../../../primitives/rpc" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } +sp-rpc = { version = "5.0.0", path = "../../../primitives/rpc" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } [dev-dependencies] serde_json = "1" diff --git a/frame/contracts/rpc/runtime-api/Cargo.toml b/frame/contracts/rpc/runtime-api/Cargo.toml index bb70d0835d268..8ecdff5175372 100644 --- a/frame/contracts/rpc/runtime-api/Cargo.toml +++ b/frame/contracts/rpc/runtime-api/Cargo.toml @@ -17,9 +17,9 @@ codec = { package = "parity-scale-codec", version = "2", default-features = fals scale-info = { version = "1.0", default-features = false, features = ["derive"] } # Substrate Dependencies -pallet-contracts-primitives = { version = "4.0.0-dev", default-features = false, path = "../../common" } +pallet-contracts-primitives = { version = "5.0.0", default-features = false, path = "../../common" } sp-api = { version = "4.0.0-dev", default-features = false, path = "../../../../primitives/api" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../../../primitives/std" } [features] diff --git a/frame/contracts/rpc/src/lib.rs b/frame/contracts/rpc/src/lib.rs index 580b74b5ca46d..e83e4e6249b92 100644 --- a/frame/contracts/rpc/src/lib.rs +++ b/frame/contracts/rpc/src/lib.rs @@ -302,11 +302,11 @@ where } /// Converts a runtime trap into an RPC error. -fn runtime_error_into_rpc_err(err: impl std::fmt::Debug) -> Error { +fn runtime_error_into_rpc_err(err: impl std::fmt::Display) -> Error { Error { code: ErrorCode::ServerError(RUNTIME_ERROR), message: "Runtime error".into(), - data: Some(format!("{:?}", err).into()), + data: Some(err.to_string().into()), } } diff --git a/frame/contracts/src/benchmarking/mod.rs b/frame/contracts/src/benchmarking/mod.rs index 6d4ae959f31e8..88405eba44205 100644 --- a/frame/contracts/src/benchmarking/mod.rs +++ b/frame/contracts/src/benchmarking/mod.rs @@ -35,7 +35,7 @@ use crate::{ storage::Storage, Pallet as Contracts, *, }; -use codec::Encode; +use codec::{Encode, MaxEncodedLen}; use frame_benchmarking::{account, benchmarks, whitelisted_caller}; use frame_support::weights::Weight; use frame_system::RawOrigin; @@ -270,7 +270,7 @@ benchmarks! { // We cannot let `c` grow to the maximum code size because the code is not allowed // to be larger than the maximum size **after instrumentation**. instantiate_with_code { - let c in 0 .. Perbill::from_percent(50).mul_ceil(T::Schedule::get().limits.code_len / 1024); + let c in 0 .. Perbill::from_percent(49).mul_ceil(T::Schedule::get().limits.code_len) / 1024; let s in 0 .. code::max_pages::() * 64; let salt = vec![42u8; (s * 1024) as usize]; let value = T::Currency::minimum_balance(); @@ -398,6 +398,63 @@ benchmarks! { let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) + seal_is_contract { + let r in 0 .. API_BENCHMARK_BATCHES; + let accounts = (0 .. r * API_BENCHMARK_BATCH_SIZE) + .map(|n| account::("account", n, 0)) + .collect::>(); + let account_len = accounts.get(0).map(|i| i.encode().len()).unwrap_or(0); + let accounts_bytes = accounts.iter().map(|a| a.encode()).flatten().collect::>(); + let code = WasmModule::::from(ModuleDefinition { + memory: Some(ImportedMemory::max::()), + imported_functions: vec![ImportedFunction { + module: "__unstable__", + name: "seal_is_contract", + params: vec![ValueType::I32], + return_type: Some(ValueType::I32), + }], + data_segments: vec![ + DataSegment { + offset: 0, + value: accounts_bytes + }, + ], + call_body: Some(body::repeated_dyn(r * API_BENCHMARK_BATCH_SIZE, vec![ + Counter(0, account_len as u32), // address_ptr + Regular(Instruction::Call(0)), + Regular(Instruction::Drop), + ])), + .. Default::default() + }); + let instance = Contract::::new(code, vec![])?; + let info = instance.info()?; + // every account would be a contract (worst case) + for acc in accounts.iter() { + >::insert(acc, info.clone()); + } + let origin = RawOrigin::Signed(instance.caller.clone()); + }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) + + seal_caller_is_origin { + let r in 0 .. API_BENCHMARK_BATCHES; + let code = WasmModule::::from(ModuleDefinition { + memory: Some(ImportedMemory::max::()), + imported_functions: vec![ImportedFunction { + module: "__unstable__", + name: "seal_caller_is_origin", + params: vec![], + return_type: Some(ValueType::I32), + }], + call_body: Some(body::repeated(r * API_BENCHMARK_BATCH_SIZE, &[ + Instruction::Call(0), + Instruction::Drop, + ])), + .. Default::default() + }); + let instance = Contract::::new(code, vec![])?; + let origin = RawOrigin::Signed(instance.caller.clone()); + }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) + seal_address { let r in 0 .. API_BENCHMARK_BATCHES; let instance = Contract::::new(WasmModule::getter( @@ -778,9 +835,10 @@ benchmarks! { seal_set_storage { let r in 0 .. API_BENCHMARK_BATCHES; let keys = (0 .. r * API_BENCHMARK_BATCH_SIZE) - .flat_map(|n| T::Hashing::hash_of(&n).as_ref().to_vec()) + .map(|n| T::Hashing::hash_of(&n).as_ref().to_vec()) .collect::>(); - let key_len = sp_std::mem::size_of::<::Output>(); + let key_len = keys.get(0).map(|i| i.len() as u32).unwrap_or(0); + let key_bytes = keys.iter().flatten().cloned().collect::>(); let code = WasmModule::::from(ModuleDefinition { memory: Some(ImportedMemory::max::()), imported_functions: vec![ImportedFunction { @@ -792,7 +850,7 @@ benchmarks! { data_segments: vec![ DataSegment { offset: 0, - value: keys, + value: key_bytes, }, ], call_body: Some(body::repeated_dyn(r * API_BENCHMARK_BATCH_SIZE, vec![ @@ -805,13 +863,28 @@ benchmarks! { .. Default::default() }); let instance = Contract::::new(code, vec![])?; + let info = instance.info()?; + for key in keys { + Storage::::write( + &info.trie_id, + key.as_slice().try_into().map_err(|e| "Key has wrong length")?, + Some(vec![]), + None, + false, + ) + .map_err(|_| "Failed to write to storage during setup.")?; + } let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) - seal_set_storage_per_kb { + #[skip_meta] + seal_set_storage_per_new_kb { let n in 0 .. T::Schedule::get().limits.payload_len / 1024; - let key = T::Hashing::hash_of(&1u32).as_ref().to_vec(); - let key_len = key.len(); + let keys = (0 .. API_BENCHMARK_BATCH_SIZE) + .map(|n| T::Hashing::hash_of(&n).as_ref().to_vec()) + .collect::>(); + let key_len = keys.get(0).map(|i| i.len() as u32).unwrap_or(0); + let key_bytes = keys.iter().flatten().cloned().collect::>(); let code = WasmModule::::from(ModuleDefinition { memory: Some(ImportedMemory::max::()), imported_functions: vec![ImportedFunction { @@ -823,19 +896,76 @@ benchmarks! { data_segments: vec![ DataSegment { offset: 0, - value: key, + value: key_bytes, }, ], - call_body: Some(body::repeated(API_BENCHMARK_BATCH_SIZE, &[ - Instruction::I32Const(0), // key_ptr - Instruction::I32Const(0), // value_ptr - Instruction::I32Const((n * 1024) as i32), // value_len - Instruction::Call(0), - Instruction::Drop, + call_body: Some(body::repeated_dyn(API_BENCHMARK_BATCH_SIZE, vec![ + Counter(0, key_len as u32), // key_ptr + Regular(Instruction::I32Const(0)), // value_ptr + Regular(Instruction::I32Const((n * 1024) as i32)), // value_len + Regular(Instruction::Call(0)), + Regular(Instruction::Drop), ])), .. Default::default() }); let instance = Contract::::new(code, vec![])?; + let info = instance.info()?; + for key in keys { + Storage::::write( + &info.trie_id, + key.as_slice().try_into().map_err(|e| "Key has wrong length")?, + Some(vec![]), + None, + false, + ) + .map_err(|_| "Failed to write to storage during setup.")?; + } + let origin = RawOrigin::Signed(instance.caller.clone()); + }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) + + #[skip_meta] + seal_set_storage_per_old_kb { + let n in 0 .. T::Schedule::get().limits.payload_len / 1024; + let keys = (0 .. API_BENCHMARK_BATCH_SIZE) + .map(|n| T::Hashing::hash_of(&n).as_ref().to_vec()) + .collect::>(); + let key_len = keys.get(0).map(|i| i.len() as u32).unwrap_or(0); + let key_bytes = keys.iter().flatten().cloned().collect::>(); + let code = WasmModule::::from(ModuleDefinition { + memory: Some(ImportedMemory::max::()), + imported_functions: vec![ImportedFunction { + module: "__unstable__", + name: "seal_set_storage", + params: vec![ValueType::I32, ValueType::I32, ValueType::I32], + return_type: Some(ValueType::I32), + }], + data_segments: vec![ + DataSegment { + offset: 0, + value: key_bytes, + }, + ], + call_body: Some(body::repeated_dyn(API_BENCHMARK_BATCH_SIZE, vec![ + Counter(0, key_len as u32), // key_ptr + Regular(Instruction::I32Const(0)), // value_ptr + Regular(Instruction::I32Const(0)), // value_len + Regular(Instruction::Call(0)), + Regular(Instruction::Drop), + ])), + .. Default::default() + }); + let instance = Contract::::new(code, vec![])?; + let info = instance.info()?; + for key in keys { + Storage::::write( + &info.trie_id, + key.as_slice().try_into().map_err(|e| "Key has wrong length")?, + Some(vec![42u8; (n * 1024) as usize]), + None, + false, + ) + .map_err(|_| "Failed to write to storage during setup.")?; + } let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) @@ -849,7 +979,7 @@ benchmarks! { .map(|n| T::Hashing::hash_of(&n).as_ref().to_vec()) .collect::>(); let key_bytes = keys.iter().flatten().cloned().collect::>(); - let key_len = sp_std::mem::size_of::<::Output>(); + let key_len = keys.get(0).map(|i| i.len() as u32).unwrap_or(0); let code = WasmModule::::from(ModuleDefinition { memory: Some(ImportedMemory::max::()), imported_functions: vec![ImportedFunction { @@ -877,7 +1007,7 @@ benchmarks! { Storage::::write( &info.trie_id, key.as_slice().try_into().map_err(|e| "Key has wrong length")?, - Some(vec![42; T::Schedule::get().limits.payload_len as usize]), + Some(vec![]), None, false, ) @@ -887,6 +1017,50 @@ benchmarks! { let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) + #[skip_meta] + seal_clear_storage_per_kb { + let n in 0 .. T::Schedule::get().limits.payload_len / 1024; + let keys = (0 .. API_BENCHMARK_BATCH_SIZE) + .map(|n| T::Hashing::hash_of(&n).as_ref().to_vec()) + .collect::>(); + let key_len = keys.get(0).map(|i| i.len() as u32).unwrap_or(0); + let key_bytes = keys.iter().flatten().cloned().collect::>(); + let code = WasmModule::::from(ModuleDefinition { + memory: Some(ImportedMemory::max::()), + imported_functions: vec![ImportedFunction { + module: "__unstable__", + name: "seal_clear_storage", + params: vec![ValueType::I32], + return_type: Some(ValueType::I32), + }], + data_segments: vec![ + DataSegment { + offset: 0, + value: key_bytes, + }, + ], + call_body: Some(body::repeated_dyn(API_BENCHMARK_BATCH_SIZE, vec![ + Counter(0, key_len as u32), // key_ptr + Regular(Instruction::Call(0)), + Regular(Instruction::Drop), + ])), + .. Default::default() + }); + let instance = Contract::::new(code, vec![])?; + let info = instance.info()?; + for key in keys { + Storage::::write( + &info.trie_id, + key.as_slice().try_into().map_err(|e| "Key has wrong length")?, + Some(vec![42u8; (n * 1024) as usize]), + None, + false, + ) + .map_err(|_| "Failed to write to storage during setup.")?; + } + let origin = RawOrigin::Signed(instance.caller.clone()); + }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) + // We make sure that all storage accesses are to unique keys. #[skip_meta] seal_get_storage { @@ -894,7 +1068,7 @@ benchmarks! { let keys = (0 .. r * API_BENCHMARK_BATCH_SIZE) .map(|n| T::Hashing::hash_of(&n).as_ref().to_vec()) .collect::>(); - let key_len = sp_std::mem::size_of::<::Output>(); + let key_len = keys.get(0).map(|i| i.len() as u32).unwrap_or(0); let key_bytes = keys.iter().flatten().cloned().collect::>(); let key_bytes_len = key_bytes.len(); let code = WasmModule::::from(ModuleDefinition { @@ -940,6 +1114,58 @@ benchmarks! { let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) + #[skip_meta] + seal_get_storage_per_kb { + let n in 0 .. T::Schedule::get().limits.payload_len / 1024; + let keys = (0 .. API_BENCHMARK_BATCH_SIZE) + .map(|n| T::Hashing::hash_of(&n).as_ref().to_vec()) + .collect::>(); + let key_len = keys.get(0).map(|i| i.len() as u32).unwrap_or(0); + let key_bytes = keys.iter().flatten().cloned().collect::>(); + let key_bytes_len = key_bytes.len(); + let code = WasmModule::::from(ModuleDefinition { + memory: Some(ImportedMemory::max::()), + imported_functions: vec![ImportedFunction { + module: "seal0", + name: "seal_get_storage", + params: vec![ValueType::I32, ValueType::I32, ValueType::I32], + return_type: Some(ValueType::I32), + }], + data_segments: vec![ + DataSegment { + offset: 0, + value: key_bytes, + }, + DataSegment { + offset: key_bytes_len as u32, + value: T::Schedule::get().limits.payload_len.to_le_bytes().into(), + }, + ], + call_body: Some(body::repeated_dyn(API_BENCHMARK_BATCH_SIZE, vec![ + Counter(0, key_len as u32), // key_ptr + Regular(Instruction::I32Const((key_bytes_len + 4) as i32)), // out_ptr + Regular(Instruction::I32Const(key_bytes_len as i32)), // out_len_ptr + Regular(Instruction::Call(0)), + Regular(Instruction::Drop), + ])), + .. Default::default() + }); + let instance = Contract::::new(code, vec![])?; + let info = instance.info()?; + for key in keys { + Storage::::write( + &info.trie_id, + key.as_slice().try_into().map_err(|e| "Key has wrong length")?, + Some(vec![42u8; (n * 1024) as usize]), + None, + false, + ) + .map_err(|_| "Failed to write to storage during setup.")?; + } + >::insert(&instance.account_id, info.clone()); + let origin = RawOrigin::Signed(instance.caller.clone()); + }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) + // We make sure that all storage accesses are to unique keys. #[skip_meta] seal_contains_storage { @@ -947,7 +1173,7 @@ benchmarks! { let keys = (0 .. r * API_BENCHMARK_BATCH_SIZE) .map(|n| T::Hashing::hash_of(&n).as_ref().to_vec()) .collect::>(); - let key_len = sp_std::mem::size_of::<::Output>(); + let key_len = keys.get(0).map(|i| i.len() as u32).unwrap_or(0); let key_bytes = keys.iter().flatten().cloned().collect::>(); let key_bytes_len = key_bytes.len(); let code = WasmModule::::from(ModuleDefinition { @@ -977,7 +1203,7 @@ benchmarks! { Storage::::write( &info.trie_id, key.as_slice().try_into().map_err(|e| "Key has wrong length")?, - Some(vec![42; T::Schedule::get().limits.payload_len as usize]), + Some(vec![]), None, false, ) @@ -987,48 +1213,47 @@ benchmarks! { let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) - seal_get_storage_per_kb { + #[skip_meta] + seal_contains_storage_per_kb { let n in 0 .. T::Schedule::get().limits.payload_len / 1024; - let key = T::Hashing::hash_of(&1u32).as_ref().to_vec(); - let key_len = key.len(); + let keys = (0 .. API_BENCHMARK_BATCH_SIZE) + .map(|n| T::Hashing::hash_of(&n).as_ref().to_vec()) + .collect::>(); + let key_len = keys.get(0).map(|i| i.len() as u32).unwrap_or(0); + let key_bytes = keys.iter().flatten().cloned().collect::>(); let code = WasmModule::::from(ModuleDefinition { memory: Some(ImportedMemory::max::()), imported_functions: vec![ImportedFunction { - module: "seal0", - name: "seal_get_storage", - params: vec![ValueType::I32, ValueType::I32, ValueType::I32], + module: "__unstable__", + name: "seal_contains_storage", + params: vec![ValueType::I32], return_type: Some(ValueType::I32), }], data_segments: vec![ DataSegment { offset: 0, - value: key.clone(), - }, - DataSegment { - offset: key_len as u32, - value: T::Schedule::get().limits.payload_len.to_le_bytes().into(), + value: key_bytes, }, ], - call_body: Some(body::repeated(API_BENCHMARK_BATCH_SIZE, &[ - // call at key_ptr - Instruction::I32Const(0), // key_ptr - Instruction::I32Const((key_len + 4) as i32), // out_ptr - Instruction::I32Const(key_len as i32), // out_len_ptr - Instruction::Call(0), - Instruction::Drop, + call_body: Some(body::repeated_dyn(API_BENCHMARK_BATCH_SIZE, vec![ + Counter(0, key_len as u32), // key_ptr + Regular(Instruction::Call(0)), + Regular(Instruction::Drop), ])), .. Default::default() }); let instance = Contract::::new(code, vec![])?; let info = instance.info()?; - Storage::::write( - &info.trie_id, - key.as_slice().try_into().map_err(|e| "Key has wrong length")?, - Some(vec![42u8; (n * 1024) as usize]), - None, - false, - ) - .map_err(|_| "Failed to write to storage during setup.")?; + for key in keys { + Storage::::write( + &info.trie_id, + key.as_slice().try_into().map_err(|e| "Key has wrong length")?, + Some(vec![42u8; (n * 1024) as usize]), + None, + false, + ) + .map_err(|_| "Failed to write to storage during setup.")?; + } >::insert(&instance.account_id, info.clone()); let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) @@ -1039,7 +1264,7 @@ benchmarks! { let keys = (0 .. r * API_BENCHMARK_BATCH_SIZE) .map(|n| T::Hashing::hash_of(&n).as_ref().to_vec()) .collect::>(); - let key_len = sp_std::mem::size_of::<::Output>(); + let key_len = keys.get(0).map(|i| i.len() as u32).unwrap_or(0); let key_bytes = keys.iter().flatten().cloned().collect::>(); let key_bytes_len = key_bytes.len(); let code = WasmModule::::from(ModuleDefinition { @@ -1091,7 +1316,7 @@ benchmarks! { let keys = (0 .. API_BENCHMARK_BATCH_SIZE) .map(|n| T::Hashing::hash_of(&n).as_ref().to_vec()) .collect::>(); - let key_len = sp_std::mem::size_of::<::Output>(); + let key_len = keys.get(0).map(|i| i.len() as u32).unwrap_or(0); let key_bytes = keys.iter().flatten().cloned().collect::>(); let key_bytes_len = key_bytes.len(); let code = WasmModule::::from(ModuleDefinition { @@ -1238,7 +1463,7 @@ benchmarks! { Regular(Instruction::I32Const(value_len as i32)), // value_len Regular(Instruction::I32Const(0)), // input_data_ptr Regular(Instruction::I32Const(0)), // input_data_len - Regular(Instruction::I32Const(u32::max_value() as i32)), // output_ptr + Regular(Instruction::I32Const(SENTINEL as i32)), // output_ptr Regular(Instruction::I32Const(0)), // output_len_ptr Regular(Instruction::Call(0)), Regular(Instruction::Drop), @@ -1249,6 +1474,58 @@ benchmarks! { let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) + seal_delegate_call { + let r in 0 .. API_BENCHMARK_BATCHES; + let hashes = (0..r * API_BENCHMARK_BATCH_SIZE) + .map(|i| { + let code = WasmModule::::dummy_with_bytes(i); + Contracts::::store_code_raw(code.code, whitelisted_caller())?; + Ok(code.hash) + }) + .collect::, &'static str>>()?; + let hash_len = hashes.get(0).map(|x| x.encode().len()).unwrap_or(0); + let hashes_bytes = hashes.iter().flat_map(|x| x.encode()).collect::>(); + let hashes_len = hashes_bytes.len(); + let hashes_offset = 0; + + let code = WasmModule::::from(ModuleDefinition { + memory: Some(ImportedMemory::max::()), + imported_functions: vec![ImportedFunction { + module: "__unstable__", + name: "seal_delegate_call", + params: vec![ + ValueType::I32, + ValueType::I32, + ValueType::I32, + ValueType::I32, + ValueType::I32, + ValueType::I32, + ], + return_type: Some(ValueType::I32), + }], + data_segments: vec![ + DataSegment { + offset: hashes_offset as u32, + value: hashes_bytes, + }, + ], + call_body: Some(body::repeated_dyn(r * API_BENCHMARK_BATCH_SIZE, vec![ + Regular(Instruction::I32Const(0)), // flags + Counter(hashes_offset as u32, hash_len as u32), // code_hash_ptr + Regular(Instruction::I32Const(0)), // input_data_ptr + Regular(Instruction::I32Const(0)), // input_data_len + Regular(Instruction::I32Const(u32::max_value() as i32)), // output_ptr + Regular(Instruction::I32Const(0)), // output_len_ptr + Regular(Instruction::Call(0)), + Regular(Instruction::Drop), + ])), + .. Default::default() + }); + let instance = Contract::::new(code, vec![])?; + let callee = instance.addr.clone(); + let origin = RawOrigin::Signed(instance.caller.clone()); + }: call(origin, callee, 0u32.into(), Weight::MAX, None, vec![]) + seal_call_per_transfer_input_output_kb { let t in 0 .. 1; let i in 0 .. code::max_pages::() * 64; @@ -1361,7 +1638,7 @@ benchmarks! { assert!(value > 0u32.into()); let value_bytes = value.encode(); let value_len = value_bytes.len(); - let addr_len = sp_std::mem::size_of::(); + let addr_len = T::AccountId::max_encoded_len(); // offsets where to place static data in contract memory let value_offset = 0; @@ -1415,7 +1692,7 @@ benchmarks! { Regular(Instruction::I32Const(0)), // input_data_len Regular(Instruction::I32Const(addr_offset as i32)), // address_ptr Regular(Instruction::I32Const(addr_len_offset as i32)), // address_len_ptr - Regular(Instruction::I32Const(u32::max_value() as i32)), // output_ptr + Regular(Instruction::I32Const(SENTINEL as i32)), // output_ptr Regular(Instruction::I32Const(0)), // output_len_ptr Regular(Instruction::I32Const(0)), // salt_ptr Regular(Instruction::I32Const(0)), // salt_ptr_len @@ -1485,7 +1762,7 @@ benchmarks! { assert!(value > 0u32.into()); let value_bytes = value.encode(); let value_len = value_bytes.len(); - let addr_len = sp_std::mem::size_of::(); + let addr_len = T::AccountId::max_encoded_len(); // offsets where to place static data in contract memory let input_offset = 0; diff --git a/frame/contracts/src/chain_extension.rs b/frame/contracts/src/chain_extension.rs index b0e08df3adbb0..ed447719933be 100644 --- a/frame/contracts/src/chain_extension.rs +++ b/frame/contracts/src/chain_extension.rs @@ -329,7 +329,7 @@ where /// /// If the contract supplied buffer is smaller than the passed `buffer` an `Err` is returned. /// If `allow_skip` is set to true the contract is allowed to skip the copying of the buffer - /// by supplying the guard value of `u32::MAX` as `out_ptr`. The + /// by supplying the guard value of `pallet-contracts::SENTINEL` as `out_ptr`. The /// `weight_per_byte` is only charged when the write actually happens and is not skipped or /// failed due to a too small output buffer. pub fn write( diff --git a/frame/contracts/src/exec.rs b/frame/contracts/src/exec.rs index 679a6adde9221..c6e647e0c8d96 100644 --- a/frame/contracts/src/exec.rs +++ b/frame/contracts/src/exec.rs @@ -24,7 +24,7 @@ use crate::{ use frame_support::{ dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo, Dispatchable}, storage::{with_transaction, TransactionOutcome}, - traits::{Contains, Currency, ExistenceRequirement, Get, OriginTrait, Randomness, Time}, + traits::{Contains, Currency, ExistenceRequirement, OriginTrait, Randomness, Time}, weights::Weight, }; use frame_system::RawOrigin; @@ -104,6 +104,19 @@ pub trait Ext: sealing::Sealed { allows_reentry: bool, ) -> Result; + /// Execute code in the current frame. + /// + /// Returns the original code size of the called contract. + /// + /// # Return Value + /// + /// Result + fn delegate_call( + &mut self, + code: CodeHash, + input_data: Vec, + ) -> Result; + /// Instantiate a contract from the given code. /// /// Returns the original code size of the called contract. @@ -140,11 +153,11 @@ pub trait Ext: sealing::Sealed { /// was deleted. fn get_storage(&mut self, key: &StorageKey) -> Option>; - /// Returns true iff some storage entry exists under the supplied `key` + /// Returns `Some(len)` (in bytes) if a storage item exists at `key`. /// - /// Returns `false` if the `key` wasn't previously set by `set_storage` or + /// Returns `None` if the `key` wasn't previously set by `set_storage` or /// was deleted. - fn contains_storage(&mut self, key: &StorageKey) -> bool; + fn get_storage_size(&mut self, key: &StorageKey) -> Option; /// Sets the storage entry by the given key to the specified value. If `value` is `None` then /// the storage entry is deleted. @@ -158,6 +171,15 @@ pub trait Ext: sealing::Sealed { /// Returns a reference to the account id of the caller. fn caller(&self) -> &AccountIdOf; + /// Check if a contract lives at the specified `address`. + fn is_contract(&self, address: &AccountIdOf) -> bool; + + /// Check if the caller of the current contract is the origin of the whole call stack. + /// + /// This can be checked with `is_contract(self.caller())` as well. + /// However, this function does not require any storage lookup and therefore uses less weight. + fn caller_is_origin(&self) -> bool; + /// Returns a reference to the account id of the current contract. fn address(&self) -> &AccountIdOf; @@ -338,6 +360,16 @@ pub struct Frame { nested_storage: storage::meter::NestedMeter, /// If `false` the contract enabled its defense against reentrance attacks. allows_reentry: bool, + /// The caller of the currently executing frame which was spawned by `delegate_call`. + delegate_caller: Option, +} + +/// Used in a delegate call frame arguments in order to override the executable and caller. +struct DelegatedCall { + /// The executable which is run instead of the contracts own `executable`. + executable: E, + /// The account id of the caller contract. + caller: T::AccountId, } /// Parameter passed in when creating a new `Frame`. @@ -349,6 +381,10 @@ enum FrameArgs<'a, T: Config, E> { dest: T::AccountId, /// If `None` the contract info needs to be reloaded from storage. cached_info: Option>, + /// This frame was created by `seal_delegate_call` and hence uses different code than + /// what is stored at [`Self::dest`]. Its caller ([`Frame::delegated_caller`]) is the + /// account which called the caller contract + delegated_call: Option>, }, Instantiate { /// The contract or signed origin which instantiates the new contract. @@ -483,7 +519,7 @@ where T::AccountId: UncheckedFrom + AsRef<[u8]>, E: Executable, { - /// Create an run a new call stack by calling into `dest`. + /// Create and run a new call stack by calling into `dest`. /// /// # Note /// @@ -504,7 +540,7 @@ where debug_message: Option<&'a mut Vec>, ) -> Result { let (mut stack, executable) = Self::new( - FrameArgs::Call { dest, cached_info: None }, + FrameArgs::Call { dest, cached_info: None, delegated_call: None }, origin, gas_meter, storage_meter, @@ -595,33 +631,46 @@ where gas_limit: Weight, schedule: &Schedule, ) -> Result<(Frame, E, Option), ExecError> { - let (account_id, contract_info, executable, entry_point, account_counter) = match frame_args - { - FrameArgs::Call { dest, cached_info } => { - let contract = if let Some(contract) = cached_info { - contract - } else { - >::get(&dest).ok_or(>::ContractNotFound)? - }; - - let executable = E::from_storage(contract.code_hash, schedule, gas_meter)?; - - (dest, contract, executable, ExportedFunction::Call, None) - }, - FrameArgs::Instantiate { sender, trie_seed, executable, salt } => { - let account_id = - >::contract_address(&sender, executable.code_hash(), &salt); - let trie_id = Storage::::generate_trie_id(&account_id, trie_seed); - let contract = Storage::::new_contract( - &account_id, - trie_id, - executable.code_hash().clone(), - )?; - (account_id, contract, executable, ExportedFunction::Constructor, Some(trie_seed)) - }, - }; + let (account_id, contract_info, executable, delegate_caller, entry_point, account_counter) = + match frame_args { + FrameArgs::Call { dest, cached_info, delegated_call } => { + let contract = if let Some(contract) = cached_info { + contract + } else { + >::get(&dest).ok_or(>::ContractNotFound)? + }; + + let (executable, delegate_caller) = + if let Some(DelegatedCall { executable, caller }) = delegated_call { + (executable, Some(caller)) + } else { + (E::from_storage(contract.code_hash, schedule, gas_meter)?, None) + }; + + (dest, contract, executable, delegate_caller, ExportedFunction::Call, None) + }, + FrameArgs::Instantiate { sender, trie_seed, executable, salt } => { + let account_id = + >::contract_address(&sender, executable.code_hash(), &salt); + let trie_id = Storage::::generate_trie_id(&account_id, trie_seed); + let contract = Storage::::new_contract( + &account_id, + trie_id, + executable.code_hash().clone(), + )?; + ( + account_id, + contract, + executable, + None, + ExportedFunction::Constructor, + Some(trie_seed), + ) + }, + }; let frame = Frame { + delegate_caller, value_transferred, contract_info: CachedContract::Cached(contract_info), account_id, @@ -927,8 +976,11 @@ where CachedContract::Cached(contract) => Some(contract.clone()), _ => None, }); - let executable = - self.push_frame(FrameArgs::Call { dest: to, cached_info }, value, gas_limit)?; + let executable = self.push_frame( + FrameArgs::Call { dest: to, cached_info, delegated_call: None }, + value, + gas_limit, + )?; self.run(executable, input_data) }; @@ -941,6 +993,28 @@ where result } + fn delegate_call( + &mut self, + code_hash: CodeHash, + input_data: Vec, + ) -> Result { + let executable = E::from_storage(code_hash, &self.schedule, self.gas_meter())?; + let top_frame = self.top_frame_mut(); + let contract_info = top_frame.contract_info().clone(); + let account_id = top_frame.account_id.clone(); + let value = top_frame.value_transferred.clone(); + let executable = self.push_frame( + FrameArgs::Call { + dest: account_id, + cached_info: Some(contract_info), + delegated_call: Some(DelegatedCall { executable, caller: self.caller().clone() }), + }, + value, + 0, + )?; + self.run(executable, input_data) + } + fn instantiate( &mut self, gas_limit: Weight, @@ -996,8 +1070,8 @@ where Storage::::read(&self.top_frame_mut().contract_info().trie_id, key) } - fn contains_storage(&mut self, key: &StorageKey) -> bool { - Storage::::contains(&self.top_frame_mut().contract_info().trie_id, key) + fn get_storage_size(&mut self, key: &StorageKey) -> Option { + Storage::::size(&self.top_frame_mut().contract_info().trie_id, key) } fn set_storage( @@ -1021,7 +1095,19 @@ where } fn caller(&self) -> &T::AccountId { - self.frames().nth(1).map(|f| &f.account_id).unwrap_or(&self.origin) + if let Some(caller) = &self.top_frame().delegate_caller { + &caller + } else { + self.frames().nth(1).map(|f| &f.account_id).unwrap_or(&self.origin) + } + } + + fn is_contract(&self, address: &T::AccountId) -> bool { + ContractInfoOf::::contains_key(&address) + } + + fn caller_is_origin(&self) -> bool { + self.caller() == &self.origin } fn balance(&self) -> BalanceOf { @@ -1056,7 +1142,7 @@ where } fn max_value_size(&self) -> u32 { - T::Schedule::get().limits.payload_len + self.schedule.limits.payload_len } fn get_weight_price(&self, weight: Weight) -> BalanceOf { @@ -1620,6 +1706,70 @@ mod tests { WITNESSED_CALLER_CHARLIE.with(|caller| assert_eq!(*caller.borrow(), Some(dest))); } + #[test] + fn is_contract_returns_proper_values() { + let bob_ch = MockLoader::insert(Call, |ctx, _| { + // Verify that BOB is a contract + assert!(ctx.ext.is_contract(&BOB)); + // Verify that ALICE is not a contract + assert!(!ctx.ext.is_contract(&ALICE)); + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, bob_ch); + + let mut storage_meter = storage::meter::Meter::new(&ALICE, Some(0), 0).unwrap(); + let result = MockStack::run_call( + ALICE, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![], + None, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn caller_is_origin_returns_proper_values() { + let code_charlie = MockLoader::insert(Call, |ctx, _| { + // BOB is not the origin of the stack call + assert!(!ctx.ext.caller_is_origin()); + exec_success() + }); + + let code_bob = MockLoader::insert(Call, |ctx, _| { + // ALICE is the origin of the call stack + assert!(ctx.ext.caller_is_origin()); + // BOB calls CHARLIE + ctx.ext.call(0, CHARLIE, 0, vec![], true) + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_bob); + place_contract(&CHARLIE, code_charlie); + let mut storage_meter = storage::meter::Meter::new(&ALICE, Some(0), 0).unwrap(); + // ALICE -> BOB (caller is origin) -> CHARLIE (caller is not origin) + let result = MockStack::run_call( + ALICE, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![0], + None, + ); + assert_matches!(result, Ok(_)); + }); + } + #[test] fn address_returns_proper_values() { let bob_ch = MockLoader::insert(Call, |ctx, _| { @@ -2432,16 +2582,16 @@ mod tests { } #[test] - fn contains_storage_works() { + fn get_storage_size_works() { let code_hash = MockLoader::insert(Call, |ctx, _| { assert_eq!( ctx.ext.set_storage([1; 32], Some(vec![1, 2, 3]), false), Ok(WriteOutcome::New) ); assert_eq!(ctx.ext.set_storage([2; 32], Some(vec![]), false), Ok(WriteOutcome::New)); - assert_eq!(ctx.ext.contains_storage(&[1; 32]), true); - assert_eq!(ctx.ext.contains_storage(&[1; 32]), true); - assert_eq!(ctx.ext.contains_storage(&[3; 32]), false); + assert_eq!(ctx.ext.get_storage_size(&[1; 32]), Some(3)); + assert_eq!(ctx.ext.get_storage_size(&[2; 32]), Some(0)); + assert_eq!(ctx.ext.get_storage_size(&[3; 32]), None); exec_success() }); diff --git a/frame/contracts/src/lib.rs b/frame/contracts/src/lib.rs index e57b88c5d0389..7e4515868b745 100644 --- a/frame/contracts/src/lib.rs +++ b/frame/contracts/src/lib.rs @@ -136,6 +136,14 @@ type BalanceOf = /// The current storage version. const STORAGE_VERSION: StorageVersion = StorageVersion::new(6); +/// Used as a sentinel value when reading and writing contract memory. +/// +/// It is usually used to signal `None` to a contract when only a primitive is allowed +/// and we don't want to go through encoding a full Rust type. Using `u32::Max` is a safe +/// sentinel because contracts are never allowed to use such a large amount of resources +/// that this value makes sense for a memory location or length. +const SENTINEL: u32 = u32::MAX; + /// Provides the contract address generation method. /// /// See [`DefaultAddressGenerator`] for the default implementation. @@ -562,6 +570,8 @@ pub mod pallet { pub enum Error { /// A new schedule must have a greater version than the current one. InvalidScheduleVersion, + /// Invalid combination of flags supplied to `seal_call` or `seal_delegate_call`. + InvalidCallFlags, /// The executed contract exhausted its gas limit. OutOfGas, /// The output buffer supplied to a contract API call was too small. @@ -831,7 +841,7 @@ where module: &mut PrefabWasmModule, schedule: &Schedule, ) -> frame_support::dispatch::DispatchResult { - self::wasm::reinstrument(module, schedule) + self::wasm::reinstrument(module, schedule).map(|_| ()) } /// Internal function that does the actual call. diff --git a/frame/contracts/src/schedule.rs b/frame/contracts/src/schedule.rs index d3c445b11292f..a2f6161b5bbed 100644 --- a/frame/contracts/src/schedule.rs +++ b/frame/contracts/src/schedule.rs @@ -256,6 +256,12 @@ pub struct HostFnWeights { /// Weight of calling `seal_caller`. pub caller: Weight, + /// Weight of calling `seal_is_contract`. + pub is_contract: Weight, + + /// Weight of calling `seal_caller_is_origin`. + pub caller_is_origin: Weight, + /// Weight of calling `seal_address`. pub address: Weight, @@ -316,15 +322,24 @@ pub struct HostFnWeights { /// Weight of calling `seal_set_storage`. pub set_storage: Weight, - /// Weight per byte of an item stored with `seal_set_storage`. - pub set_storage_per_byte: Weight, + /// Weight per written byten of an item stored with `seal_set_storage`. + pub set_storage_per_new_byte: Weight, + + /// Weight per overwritten byte of an item stored with `seal_set_storage`. + pub set_storage_per_old_byte: Weight, /// Weight of calling `seal_clear_storage`. pub clear_storage: Weight, + /// Weight of calling `seal_clear_storage` per byte of the stored item. + pub clear_storage_per_byte: Weight, + /// Weight of calling `seal_contains_storage`. pub contains_storage: Weight, + /// Weight of calling `seal_contains_storage` per byte of the stored item. + pub contains_storage_per_byte: Weight, + /// Weight of calling `seal_get_storage`. pub get_storage: Weight, @@ -343,6 +358,9 @@ pub struct HostFnWeights { /// Weight of calling `seal_call`. pub call: Weight, + /// Weight of calling `seal_delegate_call`. + pub delegate_call: Weight, + /// Weight surcharge that is claimed if `seal_call` does a balance transfer. pub call_transfer_surcharge: Weight, @@ -562,6 +580,8 @@ impl Default for HostFnWeights { fn default() -> Self { Self { caller: cost_batched!(seal_caller), + is_contract: cost_batched!(seal_is_contract), + caller_is_origin: cost_batched!(seal_caller_is_origin), address: cost_batched!(seal_address), gas_left: cost_batched!(seal_gas_left), balance: cost_batched!(seal_balance), @@ -586,15 +606,19 @@ impl Default for HostFnWeights { ), debug_message: cost_batched!(seal_debug_message), set_storage: cost_batched!(seal_set_storage), - set_storage_per_byte: cost_byte_batched!(seal_set_storage_per_kb), + set_storage_per_new_byte: cost_byte_batched!(seal_set_storage_per_new_kb), + set_storage_per_old_byte: cost_byte_batched!(seal_set_storage_per_old_kb), clear_storage: cost_batched!(seal_clear_storage), + clear_storage_per_byte: cost_byte_batched!(seal_clear_storage_per_kb), contains_storage: cost_batched!(seal_contains_storage), + contains_storage_per_byte: cost_byte_batched!(seal_contains_storage_per_kb), get_storage: cost_batched!(seal_get_storage), get_storage_per_byte: cost_byte_batched!(seal_get_storage_per_kb), take_storage: cost_batched!(seal_take_storage), take_storage_per_byte: cost_byte_batched!(seal_take_storage_per_kb), transfer: cost_batched!(seal_transfer), call: cost_batched!(seal_call), + delegate_call: cost_batched!(seal_delegate_call), call_transfer_surcharge: cost_batched_args!( seal_call_per_transfer_input_output_kb, 1, diff --git a/frame/contracts/src/storage.rs b/frame/contracts/src/storage.rs index b84cd1d2538e1..51a43a1782425 100644 --- a/frame/contracts/src/storage.rs +++ b/frame/contracts/src/storage.rs @@ -22,7 +22,7 @@ pub mod meter; use crate::{ exec::{AccountIdOf, StorageKey}, weights::WeightInfo, - BalanceOf, CodeHash, Config, ContractInfoOf, DeletionQueue, Error, TrieId, + BalanceOf, CodeHash, Config, ContractInfoOf, DeletionQueue, Error, TrieId, SENTINEL, }; use codec::{Decode, Encode}; use frame_support::{ @@ -87,6 +87,33 @@ pub enum WriteOutcome { Taken(Vec), } +impl WriteOutcome { + /// Extracts the size of the overwritten value or `0` if there + /// was no value in storage. + pub fn old_len(&self) -> u32 { + match self { + Self::New => 0, + Self::Overwritten(len) => *len, + Self::Taken(value) => value.len() as u32, + } + } + + /// Extracts the size of the overwritten value or `SENTINEL` if there + /// was no value in storage. + /// + /// # Note + /// + /// We cannot use `0` as sentinel value because there could be a zero sized + /// storage entry which is different from a non existing one. + pub fn old_len_with_sentinel(&self) -> u32 { + match self { + Self::New => SENTINEL, + Self::Overwritten(len) => *len, + Self::Taken(value) => value.len() as u32, + } + } +} + pub struct Storage(PhantomData); impl Storage @@ -102,9 +129,12 @@ where child::get_raw(&child_trie_info(trie_id), &blake2_256(key)) } - /// Returns `true` iff the `key` exists in storage. - pub fn contains(trie_id: &TrieId, key: &StorageKey) -> bool { - child::exists(&child_trie_info(trie_id), &blake2_256(key)) + /// Returns `Some(len)` (in bytes) if a storage item exists at `key`. + /// + /// Returns `None` if the `key` wasn't previously set by `set_storage` or + /// was deleted. + pub fn size(trie_id: &TrieId, key: &StorageKey) -> Option { + child::len(&child_trie_info(trie_id), &blake2_256(key)) } /// Update a storage entry into a contract's kv storage. @@ -238,7 +268,9 @@ where let mut queue = >::get(); - if let (Some(trie), true) = (queue.get(0), remaining_key_budget > 0) { + while !queue.is_empty() && remaining_key_budget > 0 { + // Cannot panic due to loop condition + let trie = &mut queue[0]; let outcome = child::kill_storage(&child_trie_info(&trie.trie_id), Some(remaining_key_budget)); let keys_removed = match outcome { @@ -246,7 +278,7 @@ where KillStorageResult::SomeRemaining(count) => count, KillStorageResult::AllRemoved(count) => { // We do not care to preserve order. The contract is deleted already and - // noone waits for the trie to be deleted. + // no one waits for the trie to be deleted. queue.swap_remove(0); count }, diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index fd5c8cfd34ec9..6919705206d4a 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -294,7 +294,7 @@ pub const BOB: AccountId32 = AccountId32::new([2u8; 32]); pub const CHARLIE: AccountId32 = AccountId32::new([3u8; 32]); pub const DJANGO: AccountId32 = AccountId32::new([4u8; 32]); -pub const GAS_LIMIT: Weight = 10_000_000_000; +pub const GAS_LIMIT: Weight = 100_000_000_000; pub struct ExtBuilder { existential_deposit: u64, @@ -692,6 +692,44 @@ fn deploy_and_call_other_contract() { }); } +#[test] +#[cfg(feature = "unstable-interface")] +fn delegate_call() { + let (caller_wasm, caller_code_hash) = compile_module::("delegate_call").unwrap(); + let (callee_wasm, callee_code_hash) = compile_module::("delegate_call_lib").unwrap(); + let caller_addr = Contracts::contract_address(&ALICE, &caller_code_hash, &[]); + + ExtBuilder::default().existential_deposit(500).build().execute_with(|| { + let _ = Balances::deposit_creating(&ALICE, 1_000_000); + + // Instantiate the 'caller' + assert_ok!(Contracts::instantiate_with_code( + Origin::signed(ALICE), + 300_000, + GAS_LIMIT, + None, + caller_wasm, + vec![], + vec![], + )); + // Only upload 'callee' code + assert_ok!(Contracts::upload_code( + Origin::signed(ALICE), + callee_wasm, + Some(codec::Compact(100_000)), + )); + + assert_ok!(Contracts::call( + Origin::signed(ALICE), + caller_addr.clone(), + 1337, + GAS_LIMIT, + None, + callee_code_hash.as_ref().to_vec(), + )); + }); +} + #[test] fn cannot_self_destruct_through_draning() { let (wasm, code_hash) = compile_module::("drain").unwrap(); @@ -1513,6 +1551,59 @@ fn lazy_removal_works() { }); } +#[test] +fn lazy_batch_removal_works() { + let (code, hash) = compile_module::("self_destruct").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = ::Currency::minimum_balance(); + let _ = Balances::deposit_creating(&ALICE, 1000 * min_balance); + let mut tries: Vec = vec![]; + + for i in 0..3u8 { + assert_ok!(Contracts::instantiate_with_code( + Origin::signed(ALICE), + min_balance * 100, + GAS_LIMIT, + None, + code.clone(), + vec![], + vec![i], + ),); + + let addr = Contracts::contract_address(&ALICE, &hash, &[i]); + let info = >::get(&addr).unwrap(); + let trie = &info.child_trie_info(); + + // Put value into the contracts child trie + child::put(trie, &[99], &42); + + // Terminate the contract. Contract info should be gone, but value should be still there + // as the lazy removal did not run, yet. + assert_ok!(Contracts::call( + Origin::signed(ALICE), + addr.clone(), + 0, + GAS_LIMIT, + None, + vec![] + )); + + assert!(!>::contains_key(&addr)); + assert_matches!(child::get(trie, &[99]), Some(42)); + + tries.push(trie.clone()) + } + + // Run single lazy removal + Contracts::on_initialize(Weight::max_value()); + + // The single lazy removal should have removed all queued tries + for trie in tries.iter() { + assert_matches!(child::get::(trie, &[99]), None); + } + }); +} + #[test] fn lazy_removal_partial_remove_works() { let (code, hash) = compile_module::("self_destruct").unwrap(); @@ -2196,7 +2287,7 @@ fn upload_code_works() { phase: Phase::Initialization, event: Event::Balances(pallet_balances::Event::Reserved { who: ALICE, - amount: 180, + amount: 240, }), topics: vec![], }, @@ -2275,7 +2366,7 @@ fn remove_code_works() { phase: Phase::Initialization, event: Event::Balances(pallet_balances::Event::Reserved { who: ALICE, - amount: 180, + amount: 240, }), topics: vec![], }, @@ -2288,7 +2379,7 @@ fn remove_code_works() { phase: Phase::Initialization, event: Event::Balances(pallet_balances::Event::Unreserved { who: ALICE, - amount: 180, + amount: 240, }), topics: vec![], }, @@ -2330,7 +2421,7 @@ fn remove_code_wrong_origin() { phase: Phase::Initialization, event: Event::Balances(pallet_balances::Event::Reserved { who: ALICE, - amount: 180, + amount: 240, }), topics: vec![], }, @@ -2461,7 +2552,7 @@ fn instantiate_with_zero_balance_works() { phase: Phase::Initialization, event: Event::Balances(pallet_balances::Event::Reserved { who: ALICE, - amount: 180, + amount: 240, }), topics: vec![], }, @@ -2561,7 +2652,7 @@ fn instantiate_with_below_existential_deposit_works() { phase: Phase::Initialization, event: Event::Balances(pallet_balances::Event::Reserved { who: ALICE, - amount: 180, + amount: 240, }), topics: vec![], }, diff --git a/frame/contracts/src/wasm/code_cache.rs b/frame/contracts/src/wasm/code_cache.rs index e3fe48ac12c24..a48f9838837c9 100644 --- a/frame/contracts/src/wasm/code_cache.rs +++ b/frame/contracts/src/wasm/code_cache.rs @@ -38,7 +38,6 @@ use crate::{ use frame_support::{ dispatch::{DispatchError, DispatchResult}, ensure, - storage::StorageMap, traits::ReservableCurrency, }; use sp_core::crypto::UncheckedFrom; @@ -149,52 +148,38 @@ pub fn load( where T::AccountId: UncheckedFrom + AsRef<[u8]>, { - gas_meter.charge(CodeToken::Load(estimate_code_size::, _>(&code_hash)?))?; + let charged = gas_meter.charge(CodeToken::Load(schedule.limits.code_len))?; let mut prefab_module = >::get(code_hash).ok_or_else(|| Error::::CodeNotFound)?; + gas_meter.adjust_gas(charged, CodeToken::Load(prefab_module.code.len() as u32)); prefab_module.code_hash = code_hash; if prefab_module.instruction_weights_version < schedule.instruction_weights.version { // The instruction weights have changed. // We need to re-instrument the code with the new instruction weights. - gas_meter.charge(CodeToken::Reinstrument(estimate_code_size::, _>( - &code_hash, - )?))?; - reinstrument(&mut prefab_module, schedule)?; + let charged = gas_meter.charge(CodeToken::Reinstrument(schedule.limits.code_len))?; + let code_size = reinstrument(&mut prefab_module, schedule)?; + gas_meter.adjust_gas(charged, CodeToken::Reinstrument(code_size)); } Ok(prefab_module) } /// Instruments the passed prefab wasm module with the supplied schedule. +/// +/// Returns the size in bytes of the uninstrumented code. pub fn reinstrument( prefab_module: &mut PrefabWasmModule, schedule: &Schedule, -) -> Result<(), DispatchError> { +) -> Result { let original_code = >::get(&prefab_module.code_hash).ok_or_else(|| Error::::CodeNotFound)?; + let original_code_len = original_code.len(); prefab_module.code = prepare::reinstrument_contract::(original_code, schedule)?; prefab_module.instruction_weights_version = schedule.instruction_weights.version; >::insert(&prefab_module.code_hash, &*prefab_module); - Ok(()) -} - -/// Get the size of the code stored at `code_hash` without loading it. -/// -/// The returned value is slightly too large when using it for the [`PrefabWasmModule`] -/// because it has other fields in addition to the code itself. However, those are negligible -/// when compared to the code size. Additionally, charging too much weight is completely safe. -fn estimate_code_size(code_hash: &CodeHash) -> Result -where - T: Config, - M: StorageMap, V>, - V: codec::FullCodec, -{ - let key = M::hashed_key_for(code_hash); - let mut data = [0u8; 0]; - let len = sp_io::storage::read(&key, &mut data, 0).ok_or_else(|| Error::::CodeNotFound)?; - Ok(len) + Ok(original_code_len as u32) } /// Costs for operations that are related to code handling. diff --git a/frame/contracts/src/wasm/mod.rs b/frame/contracts/src/wasm/mod.rs index ee778982cdbd4..491daa58523e6 100644 --- a/frame/contracts/src/wasm/mod.rs +++ b/frame/contracts/src/wasm/mod.rs @@ -87,7 +87,7 @@ pub struct PrefabWasmModule { /// /// It is stored in a separate storage entry to avoid loading the code when not necessary. #[derive(Clone, Encode, Decode, scale_info::TypeInfo, MaxEncodedLen)] -#[codec(mel_bound(T: Config))] +#[codec(mel_bound())] #[scale_info(skip_type_params(T))] pub struct OwnerInfo { /// The account that has deployed the contract and hence is allowed to remove it. @@ -302,11 +302,18 @@ mod tests { allows_reentry: bool, } + #[derive(Debug, PartialEq, Eq)] + struct CallCodeEntry { + code_hash: H256, + data: Vec, + } + pub struct MockExt { storage: HashMap>, instantiates: Vec, terminations: Vec, calls: Vec, + code_calls: Vec, transfers: Vec, // (topics, data) events: Vec<(Vec, Vec)>, @@ -329,6 +336,7 @@ mod tests { instantiates: Default::default(), terminations: Default::default(), calls: Default::default(), + code_calls: Default::default(), transfers: Default::default(), events: Default::default(), runtime_calls: Default::default(), @@ -354,6 +362,14 @@ mod tests { self.calls.push(CallEntry { to, value, data, allows_reentry }); Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: call_return_data() }) } + fn delegate_call( + &mut self, + code_hash: CodeHash, + data: Vec, + ) -> Result { + self.code_calls.push(CallCodeEntry { code_hash, data }); + Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: call_return_data() }) + } fn instantiate( &mut self, gas_limit: Weight, @@ -385,8 +401,8 @@ mod tests { fn get_storage(&mut self, key: &StorageKey) -> Option> { self.storage.get(key).cloned() } - fn contains_storage(&mut self, key: &StorageKey) -> bool { - self.storage.contains_key(key) + fn get_storage_size(&mut self, key: &StorageKey) -> Option { + self.storage.get(key).map(|val| val.len() as u32) } fn set_storage( &mut self, @@ -409,6 +425,12 @@ mod tests { fn caller(&self) -> &AccountIdOf { &ALICE } + fn is_contract(&self, _address: &AccountIdOf) -> bool { + true + } + fn caller_is_origin(&self) -> bool { + false + } fn address(&self) -> &AccountIdOf { &BOB } @@ -573,6 +595,53 @@ mod tests { ); } + #[test] + #[cfg(feature = "unstable-interface")] + fn contract_delegate_call() { + const CODE: &str = r#" +(module + ;; seal_delegate_call( + ;; flags: u32, + ;; code_hash_ptr: u32, + ;; input_data_ptr: u32, + ;; input_data_len: u32, + ;; output_ptr: u32, + ;; output_len_ptr: u32 + ;;) -> u32 + (import "__unstable__" "seal_delegate_call" (func $seal_delegate_call (param i32 i32 i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + (func (export "call") + (drop + (call $seal_delegate_call + (i32.const 0) ;; No flags are set + (i32.const 4) ;; Pointer to "callee" code_hash. + (i32.const 36) ;; Pointer to input data buffer address + (i32.const 4) ;; Length of input data buffer + (i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output + (i32.const 0) ;; Length is ignored in this case + ) + ) + ) + (func (export "deploy")) + + ;; Callee code_hash + (data (i32.const 4) + "\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11" + "\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11" + ) + + (data (i32.const 36) "\01\02\03\04") +) +"#; + let mut mock_ext = MockExt::default(); + assert_ok!(execute(CODE, vec![], &mut mock_ext)); + + assert_eq!( + &mock_ext.code_calls, + &[CallCodeEntry { code_hash: [0x11; 32].into(), data: vec![1, 2, 3, 4] }] + ); + } + #[test] fn contract_call_forward_input() { const CODE: &str = r#" @@ -2023,7 +2092,7 @@ mod tests { // value did not exist before -> sentinel returned let input = ([1u8; 32], [42u8, 48]).encode(); let result = execute(CODE, input, &mut ext).unwrap(); - assert_eq!(u32::from_le_bytes(result.data.0.try_into().unwrap()), u32::MAX); + assert_eq!(u32::from_le_bytes(result.data.0.try_into().unwrap()), crate::SENTINEL); assert_eq!(ext.storage.get(&[1u8; 32]).unwrap(), &[42u8, 48]); // value do exist -> length of old value returned @@ -2083,7 +2152,7 @@ mod tests { // value does not exist -> sentinel returned let result = execute(CODE, [3u8; 32].encode(), &mut ext).unwrap(); - assert_eq!(u32::from_le_bytes(result.data.0.try_into().unwrap()), u32::MAX); + assert_eq!(u32::from_le_bytes(result.data.0.try_into().unwrap()), crate::SENTINEL); assert_eq!(ext.storage.get(&[3u8; 32]), None); // value did exist -> length returned @@ -2228,25 +2297,92 @@ mod tests { ext.storage.insert([1u8; 32], vec![42u8]); ext.storage.insert([2u8; 32], vec![]); - // value does not exist -> error returned + // value does not exist -> sentinel value returned let result = execute(CODE, [3u8; 32].encode(), &mut ext).unwrap(); - assert_eq!( - u32::from_le_bytes(result.data.0.try_into().unwrap()), - ReturnCode::KeyNotFound as u32 - ); + assert_eq!(u32::from_le_bytes(result.data.0.try_into().unwrap()), crate::SENTINEL); // value did exist -> success let result = execute(CODE, [1u8; 32].encode(), &mut ext).unwrap(); - assert_eq!( - u32::from_le_bytes(result.data.0.try_into().unwrap()), - ReturnCode::Success as u32 - ); + assert_eq!(u32::from_le_bytes(result.data.0.try_into().unwrap()), 1,); // value did exist -> success (zero sized type) let result = execute(CODE, [2u8; 32].encode(), &mut ext).unwrap(); + assert_eq!(u32::from_le_bytes(result.data.0.try_into().unwrap()), 0,); + } + + #[test] + #[cfg(feature = "unstable-interface")] + fn is_contract_works() { + const CODE_IS_CONTRACT: &str = r#" +;; This runs `is_contract` check on zero account address +(module + (import "__unstable__" "seal_is_contract" (func $seal_is_contract (param i32) (result i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 32) zero-adress + (data (i32.const 0) + "\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00" + "\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00" + ) + + ;; [32, 36) here we store the return code of the `seal_is_contract` + + (func (export "deploy")) + + (func (export "call") + (i32.store + (i32.const 32) + (call $seal_is_contract + (i32.const 0) ;; ptr to destination address + ) + ) + ;; exit with success and take `seal_is_contract` return code to the output buffer + (call $seal_return (i32.const 0) (i32.const 32) (i32.const 4)) + ) +) +"#; + let output = execute(CODE_IS_CONTRACT, vec![], MockExt::default()).unwrap(); + + // The mock ext just always returns 1u32 (`true`). assert_eq!( - u32::from_le_bytes(result.data.0.try_into().unwrap()), - ReturnCode::Success as u32 + output, + ExecReturnValue { flags: ReturnFlags::empty(), data: Bytes(1u32.encode()) }, + ); + } + + #[test] + #[cfg(feature = "unstable-interface")] + fn caller_is_origin_works() { + const CODE_CALLER_IS_ORIGIN: &str = r#" +;; This runs `caller_is_origin` check on zero account address +(module + (import "__unstable__" "seal_caller_is_origin" (func $seal_caller_is_origin (result i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 4) here the return code of the `seal_caller_is_origin` will be stored + ;; we initialize it with non-zero value to be sure that it's being overwritten below + (data (i32.const 0) "\10\10\10\10") + + (func (export "deploy")) + + (func (export "call") + (i32.store + (i32.const 0) + (call $seal_caller_is_origin) + ) + ;; exit with success and take `seal_caller_is_origin` return code to the output buffer + (call $seal_return (i32.const 0) (i32.const 0) (i32.const 4)) + ) +) +"#; + let output = execute(CODE_CALLER_IS_ORIGIN, vec![], MockExt::default()).unwrap(); + + // The mock ext just always returns 0u32 (`false`) + assert_eq!( + output, + ExecReturnValue { flags: ReturnFlags::empty(), data: Bytes(0u32.encode()) }, ); } } diff --git a/frame/contracts/src/wasm/runtime.rs b/frame/contracts/src/wasm/runtime.rs index 98d9d9a40cda9..55ab0dfa0adef 100644 --- a/frame/contracts/src/wasm/runtime.rs +++ b/frame/contracts/src/wasm/runtime.rs @@ -21,9 +21,8 @@ use crate::{ exec::{ExecError, ExecResult, Ext, StorageKey, TopicOf}, gas::{ChargedAmount, Token}, schedule::HostFnWeights, - storage::WriteOutcome, wasm::env_def::ConvertibleToWasm, - BalanceOf, CodeHash, Config, Error, + BalanceOf, CodeHash, Config, Error, SENTINEL, }; use bitflags::bitflags; use codec::{Decode, DecodeAll, Encode, MaxEncodedLen}; @@ -139,6 +138,12 @@ pub enum RuntimeCosts { MeteringBlock(u32), /// Weight of calling `seal_caller`. Caller, + /// Weight of calling `seal_is_contract`. + #[cfg(feature = "unstable-interface")] + IsContract, + /// Weight of calling `seal_caller_is_origin`. + #[cfg(feature = "unstable-interface")] + CallerIsOrigin, /// Weight of calling `seal_address`. Address, /// Weight of calling `seal_gas_left`. @@ -169,27 +174,25 @@ pub enum RuntimeCosts { DepositEvent { num_topic: u32, len: u32 }, /// Weight of calling `seal_debug_message`. DebugMessage, - /// Weight of calling `seal_set_storage` for the given storage item size. - SetStorage(u32), - /// Weight of calling `seal_clear_storage`. - ClearStorage, - /// Weight of calling `seal_contains_storage`. + /// Weight of calling `seal_set_storage` for the given storage item sizes. + SetStorage { old_bytes: u32, new_bytes: u32 }, + /// Weight of calling `seal_clear_storage` per cleared byte. + ClearStorage(u32), + /// Weight of calling `seal_contains_storage` per byte of the checked item. #[cfg(feature = "unstable-interface")] - ContainsStorage, - /// Weight of calling `seal_get_storage` without output weight. - GetStorageBase, - /// Weight of an item received via `seal_get_storage` for the given size. - GetStorageCopyOut(u32), - /// Weight of calling `seal_take_storage` without output weight. + ContainsStorage(u32), + /// Weight of calling `seal_get_storage` with the specified size in storage. + GetStorage(u32), + /// Weight of calling `seal_take_storage` for the given size. #[cfg(feature = "unstable-interface")] - TakeStorageBase, - /// Weight of an item received via `seal_take_storage` for the given size. - #[cfg(feature = "unstable-interface")] - TakeStorageCopyOut(u32), + TakeStorage(u32), /// Weight of calling `seal_transfer`. Transfer, /// Weight of calling `seal_call` for the given input size. CallBase(u32), + /// Weight of calling `seal_delegate_call` for the given input size. + #[cfg(feature = "unstable-interface")] + DelegateCallBase(u32), /// Weight of the transfer performed during a call. CallSurchargeTransfer, /// Weight of output received through `seal_call` for the given size. @@ -231,6 +234,10 @@ impl RuntimeCosts { let weight = match *self { MeteringBlock(amount) => s.gas.saturating_add(amount.into()), Caller => s.caller, + #[cfg(feature = "unstable-interface")] + IsContract => s.is_contract, + #[cfg(feature = "unstable-interface")] + CallerIsOrigin => s.caller_is_origin, Address => s.address, GasLeft => s.gas_left, Balance => s.balance, @@ -249,22 +256,31 @@ impl RuntimeCosts { .saturating_add(s.deposit_event_per_topic.saturating_mul(num_topic.into())) .saturating_add(s.deposit_event_per_byte.saturating_mul(len.into())), DebugMessage => s.debug_message, - SetStorage(len) => - s.set_storage.saturating_add(s.set_storage_per_byte.saturating_mul(len.into())), - ClearStorage => s.clear_storage, - #[cfg(feature = "unstable-interface")] - ContainsStorage => s.contains_storage, - GetStorageBase => s.get_storage, - GetStorageCopyOut(len) => s.get_storage_per_byte.saturating_mul(len.into()), + SetStorage { new_bytes, old_bytes } => s + .set_storage + .saturating_add(s.set_storage_per_new_byte.saturating_mul(new_bytes.into())) + .saturating_add(s.set_storage_per_old_byte.saturating_mul(old_bytes.into())), + ClearStorage(len) => s + .clear_storage + .saturating_add(s.clear_storage_per_byte.saturating_mul(len.into())), #[cfg(feature = "unstable-interface")] - TakeStorageBase => s.take_storage, + ContainsStorage(len) => s + .contains_storage + .saturating_add(s.contains_storage_per_byte.saturating_mul(len.into())), + GetStorage(len) => + s.get_storage.saturating_add(s.get_storage_per_byte.saturating_mul(len.into())), #[cfg(feature = "unstable-interface")] - TakeStorageCopyOut(len) => s.take_storage_per_byte.saturating_mul(len.into()), + TakeStorage(len) => s + .take_storage + .saturating_add(s.take_storage_per_byte.saturating_mul(len.into())), Transfer => s.transfer, CallBase(len) => s.call.saturating_add(s.call_per_input_byte.saturating_mul(len.into())), CallSurchargeTransfer => s.call_transfer_surcharge, CallCopyOut(len) => s.call_per_output_byte.saturating_mul(len.into()), + #[cfg(feature = "unstable-interface")] + DelegateCallBase(len) => + s.delegate_call.saturating_add(s.call_per_input_byte.saturating_mul(len.into())), InstantiateBase { input_data_len, salt_len } => s .instantiate .saturating_add(s.instantiate_per_input_byte.saturating_mul(input_data_len.into())) @@ -317,7 +333,7 @@ where } bitflags! { - /// Flags used to change the behaviour of `seal_call`. + /// Flags used to change the behaviour of `seal_call` and `seal_delegate_call`. struct CallFlags: u32 { /// Forward the input of current function to the callee. /// @@ -353,10 +369,34 @@ bitflags! { /// Without this flag any reentrancy into the current contract that originates from /// the callee (or any of its callees) is denied. This includes the first callee: /// You cannot call into yourself with this flag set. + /// + /// # Note + /// + /// For `seal_delegate_call` should be always unset, otherwise + /// [`Error::InvalidCallFlags`] is returned. const ALLOW_REENTRY = 0b0000_1000; } } +/// The kind of call that should be performed. +enum CallType { + /// Execute another instantiated contract + Call { callee_ptr: u32, value_ptr: u32, gas: u64 }, + #[cfg(feature = "unstable-interface")] + /// Execute deployed code in the context (storage, account ID, value) of the caller contract + DelegateCall { code_hash_ptr: u32 }, +} + +impl CallType { + fn cost(&self, input_data_len: u32) -> RuntimeCosts { + match self { + CallType::Call { .. } => RuntimeCosts::CallBase(input_data_len), + #[cfg(feature = "unstable-interface")] + CallType::DelegateCall { .. } => RuntimeCosts::DelegateCallBase(input_data_len), + } + } +} + /// This is only appropriate when writing out data of constant size that does not depend on user /// input. In this case the costs for this copy was already charged as part of the token at /// the beginning of the API entry point. @@ -401,7 +441,7 @@ where // The trap was the result of the execution `return` host function. TrapReason::Return(ReturnData { flags, data }) => { let flags = ReturnFlags::from_bits(flags) - .ok_or_else(|| "used reserved bit in return flags")?; + .ok_or_else(|| Error::::InvalidCallFlags)?; Ok(ExecReturnValue { flags, data: Bytes(data) }) }, TrapReason::Termination => @@ -534,7 +574,7 @@ where /// length of the buffer located at `out_ptr`. If that buffer is large enough the actual /// `buf.len()` is written to this location. /// - /// If `out_ptr` is set to the sentinel value of `u32::MAX` and `allow_skip` is true the + /// If `out_ptr` is set to the sentinel value of `SENTINEL` and `allow_skip` is true the /// operation is skipped and `Ok` is returned. This is supposed to help callers to make copying /// output optional. For example to skip copying back the output buffer of an `seal_call` /// when the caller is not interested in the result. @@ -553,7 +593,7 @@ where allow_skip: bool, create_token: impl FnOnce(u32) -> Option, ) -> Result<(), DispatchError> { - if allow_skip && out_ptr == u32::MAX { + if allow_skip && out_ptr == SENTINEL { return Ok(()) } @@ -648,65 +688,48 @@ where } } - /// Extracts the size of the overwritten value or `u32::MAX` if there - /// was no value in storage. - /// - /// # Note - /// - /// We cannot use `0` as sentinel value because there could be a zero sized - /// storage entry which is different from a non existing one. - fn overwritten_len(outcome: WriteOutcome) -> u32 { - match outcome { - WriteOutcome::New => u32::MAX, - WriteOutcome::Overwritten(len) => len, - WriteOutcome::Taken(value) => value.len() as u32, - } - } - fn set_storage( &mut self, key_ptr: u32, value_ptr: u32, value_len: u32, ) -> Result { - self.charge_gas(RuntimeCosts::SetStorage(value_len))?; - if value_len > self.ext.max_value_size() { + let max_size = self.ext.max_value_size(); + let charged = self + .charge_gas(RuntimeCosts::SetStorage { new_bytes: value_len, old_bytes: max_size })?; + if value_len > max_size { Err(Error::::ValueTooLarge)?; } let mut key: StorageKey = [0; 32]; self.read_sandbox_memory_into_buf(key_ptr, &mut key)?; let value = Some(self.read_sandbox_memory(value_ptr, value_len)?); - self.ext - .set_storage(key, value, false) - .map(Self::overwritten_len) - .map_err(Into::into) + let write_outcome = self.ext.set_storage(key, value, false)?; + self.adjust_gas( + charged, + RuntimeCosts::SetStorage { new_bytes: value_len, old_bytes: write_outcome.old_len() }, + ); + Ok(write_outcome.old_len_with_sentinel()) } fn clear_storage(&mut self, key_ptr: u32) -> Result { - self.charge_gas(RuntimeCosts::ClearStorage)?; + let charged = self.charge_gas(RuntimeCosts::ClearStorage(self.ext.max_value_size()))?; let mut key: StorageKey = [0; 32]; self.read_sandbox_memory_into_buf(key_ptr, &mut key)?; - self.ext - .set_storage(key, None, false) - .map(Self::overwritten_len) - .map_err(Into::into) + let outcome = self.ext.set_storage(key, None, false)?; + self.adjust_gas(charged, RuntimeCosts::ClearStorage(outcome.old_len())); + Ok(outcome.old_len_with_sentinel()) } fn call( &mut self, flags: CallFlags, - callee_ptr: u32, - gas: u64, - value_ptr: u32, + call_type: CallType, input_data_ptr: u32, input_data_len: u32, output_ptr: u32, output_len_ptr: u32, ) -> Result { - self.charge_gas(RuntimeCosts::CallBase(input_data_len))?; - let callee: <::T as frame_system::Config>::AccountId = - self.read_sandbox_memory_as(callee_ptr)?; - let value: BalanceOf<::T> = self.read_sandbox_memory_as(value_ptr)?; + self.charge_gas(call_type.cost(input_data_len))?; let input_data = if flags.contains(CallFlags::CLONE_INPUT) { self.input_data.as_ref().ok_or_else(|| Error::::InputForwarded)?.clone() } else if flags.contains(CallFlags::FORWARD_INPUT) { @@ -714,12 +737,32 @@ where } else { self.read_sandbox_memory(input_data_ptr, input_data_len)? }; - if value > 0u32.into() { - self.charge_gas(RuntimeCosts::CallSurchargeTransfer)?; - } - let ext = &mut self.ext; - let call_outcome = - ext.call(gas, callee, value, input_data, flags.contains(CallFlags::ALLOW_REENTRY)); + + let call_outcome = match call_type { + CallType::Call { callee_ptr, value_ptr, gas } => { + let callee: <::T as frame_system::Config>::AccountId = + self.read_sandbox_memory_as(callee_ptr)?; + let value: BalanceOf<::T> = self.read_sandbox_memory_as(value_ptr)?; + if value > 0u32.into() { + self.charge_gas(RuntimeCosts::CallSurchargeTransfer)?; + } + self.ext.call( + gas, + callee, + value, + input_data, + flags.contains(CallFlags::ALLOW_REENTRY), + ) + }, + #[cfg(feature = "unstable-interface")] + CallType::DelegateCall { code_hash_ptr } => { + if flags.contains(CallFlags::ALLOW_REENTRY) { + return Err(Error::::InvalidCallFlags.into()) + } + let code_hash = self.read_sandbox_memory_as(code_hash_ptr)?; + self.ext.delegate_call(code_hash, input_data) + }, + }; // `TAIL_CALL` only matters on an `OK` result. Otherwise the call stack comes to // a halt anyways without anymore code being executed. @@ -827,7 +870,7 @@ define_env!(Env, , // # Return Value // // Returns the size of the pre-existing value at the specified key if any. Otherwise - // `u32::MAX` is returned as a sentinel value. + // `SENTINEL` is returned as a sentinel value. [__unstable__] seal_set_storage(ctx, key_ptr: u32, value_ptr: u32, value_len: u32) -> u32 => { ctx.set_storage(key_ptr, value_ptr, value_len) }, @@ -849,7 +892,7 @@ define_env!(Env, , // # Return Value // // Returns the size of the pre-existing value at the specified key if any. Otherwise - // `u32::MAX` is returned as a sentinel value. + // `SENTINEL` is returned as a sentinel value. [__unstable__] seal_clear_storage(ctx, key_ptr: u32) -> u32 => { ctx.clear_storage(key_ptr).map_err(Into::into) }, @@ -867,39 +910,39 @@ define_env!(Env, , // // `ReturnCode::KeyNotFound` [seal0] seal_get_storage(ctx, key_ptr: u32, out_ptr: u32, out_len_ptr: u32) -> ReturnCode => { - ctx.charge_gas(RuntimeCosts::GetStorageBase)?; + let charged = ctx.charge_gas(RuntimeCosts::GetStorage(ctx.ext.max_value_size()))?; let mut key: StorageKey = [0; 32]; ctx.read_sandbox_memory_into_buf(key_ptr, &mut key)?; if let Some(value) = ctx.ext.get_storage(&key) { - ctx.write_sandbox_output(out_ptr, out_len_ptr, &value, false, |len| { - Some(RuntimeCosts::GetStorageCopyOut(len)) - })?; + ctx.adjust_gas(charged, RuntimeCosts::GetStorage(value.len() as u32)); + ctx.write_sandbox_output(out_ptr, out_len_ptr, &value, false, already_charged)?; Ok(ReturnCode::Success) } else { + ctx.adjust_gas(charged, RuntimeCosts::GetStorage(0)); Ok(ReturnCode::KeyNotFound) } }, // Checks whether there is a value stored under the given key. // - // Returns `ReturnCode::Success` if there is a key in storage. Otherwise an error - // is returned. - // // # Parameters // // - `key_ptr`: pointer into the linear memory where the key of the requested value is placed. // - // # Errors + // # Return Value // - // `ReturnCode::KeyNotFound` - [__unstable__] seal_contains_storage(ctx, key_ptr: u32) -> ReturnCode => { - ctx.charge_gas(RuntimeCosts::ContainsStorage)?; + // Returns the size of the pre-existing value at the specified key if any. Otherwise + // `SENTINEL` is returned as a sentinel value. + [__unstable__] seal_contains_storage(ctx, key_ptr: u32) -> u32 => { + let charged = ctx.charge_gas(RuntimeCosts::ContainsStorage(ctx.ext.max_value_size()))?; let mut key: StorageKey = [0; 32]; ctx.read_sandbox_memory_into_buf(key_ptr, &mut key)?; - if ctx.ext.contains_storage(&key) { - Ok(ReturnCode::Success) + if let Some(len) = ctx.ext.get_storage_size(&key) { + ctx.adjust_gas(charged, RuntimeCosts::ContainsStorage(len)); + Ok(len) } else { - Ok(ReturnCode::KeyNotFound) + ctx.adjust_gas(charged, RuntimeCosts::ContainsStorage(0)); + Ok(SENTINEL) } }, @@ -916,15 +959,15 @@ define_env!(Env, , // // `ReturnCode::KeyNotFound` [__unstable__] seal_take_storage(ctx, key_ptr: u32, out_ptr: u32, out_len_ptr: u32) -> ReturnCode => { - ctx.charge_gas(RuntimeCosts::TakeStorageBase)?; + let charged = ctx.charge_gas(RuntimeCosts::TakeStorage(ctx.ext.max_value_size()))?; let mut key: StorageKey = [0; 32]; ctx.read_sandbox_memory_into_buf(key_ptr, &mut key)?; - if let WriteOutcome::Taken(value) = ctx.ext.set_storage(key, None, true)? { - ctx.write_sandbox_output(out_ptr, out_len_ptr, &value, false, |len| { - Some(RuntimeCosts::TakeStorageCopyOut(len)) - })?; + if let crate::storage::WriteOutcome::Taken(value) = ctx.ext.set_storage(key, None, true)? { + ctx.adjust_gas(charged, RuntimeCosts::TakeStorage(value.len() as u32)); + ctx.write_sandbox_output(out_ptr, out_len_ptr, &value, false, already_charged)?; Ok(ReturnCode::Success) } else { + ctx.adjust_gas(charged, RuntimeCosts::TakeStorage(0)); Ok(ReturnCode::KeyNotFound) } }, @@ -992,9 +1035,7 @@ define_env!(Env, , ) -> ReturnCode => { ctx.call( CallFlags::ALLOW_REENTRY, - callee_ptr, - gas, - value_ptr, + CallType::Call{callee_ptr, value_ptr, gas}, input_data_ptr, input_data_len, output_ptr, @@ -1006,7 +1047,7 @@ define_env!(Env, , // // The callees output buffer is copied to `output_ptr` and its length to `output_len_ptr`. // The copy of the output buffer can be skipped by supplying the sentinel value - // of `u32::MAX` to `output_ptr`. + // of `SENTINEL` to `output_ptr`. // // # Parameters // @@ -1043,10 +1084,51 @@ define_env!(Env, , output_len_ptr: u32 ) -> ReturnCode => { ctx.call( - CallFlags::from_bits(flags).ok_or_else(|| "used reserved bit in CallFlags")?, - callee_ptr, - gas, - value_ptr, + CallFlags::from_bits(flags).ok_or_else(|| Error::::InvalidCallFlags)?, + CallType::Call{callee_ptr, value_ptr, gas}, + input_data_ptr, + input_data_len, + output_ptr, + output_len_ptr, + ) + }, + + // Execute code in the context (storage, caller, value) of the current contract. + // + // Reentrancy protection is always disabled since the callee is allowed + // to modify the callers storage. This makes going through a reentrancy attack + // unnecessary for the callee when it wants to exploit the caller. + // + // # Parameters + // + // - flags: See [`CallFlags`] for a documentation of the supported flags. + // - code_hash: a pointer to the hash of the code to be called. + // - input_data_ptr: a pointer to a buffer to be used as input data to the callee. + // - input_data_len: length of the input data buffer. + // - output_ptr: a pointer where the output buffer is copied to. + // - output_len_ptr: in-out pointer to where the length of the buffer is read from + // and the actual length is written to. + // + // # Errors + // + // An error means that the call wasn't successful and no output buffer is returned unless + // stated otherwise. + // + // `ReturnCode::CalleeReverted`: Output buffer is returned. + // `ReturnCode::CalleeTrapped` + // `ReturnCode::CodeNotFound` + [__unstable__] seal_delegate_call( + ctx, + flags: u32, + code_hash_ptr: u32, + input_data_ptr: u32, + input_data_len: u32, + output_ptr: u32, + output_len_ptr: u32 + ) -> ReturnCode => { + ctx.call( + CallFlags::from_bits(flags).ok_or_else(|| Error::::InvalidCallFlags)?, + CallType::DelegateCall{code_hash_ptr}, input_data_ptr, input_data_len, output_ptr, @@ -1103,7 +1185,7 @@ define_env!(Env, , // by the code hash. The address of this new account is copied to `address_ptr` and its length // to `address_len_ptr`. The constructors output buffer is copied to `output_ptr` and its // length to `output_len_ptr`. The copy of the output buffer and address can be skipped by - // supplying the sentinel value of `u32::MAX` to `output_ptr` or `address_ptr`. + // supplying the sentinel value of `SENTINEL` to `output_ptr` or `address_ptr`. // // `value` must be at least the minimum balance. Otherwise the instantiation fails and the // contract is not created. @@ -1266,6 +1348,37 @@ define_env!(Env, , )?) }, + // Checks whether a specified address belongs to a contract. + // + // # Parameters + // + // - account_ptr: a pointer to the address of the beneficiary account + // Should be decodable as an `T::AccountId`. Traps otherwise. + // + // Returned value is a u32-encoded boolean: (0 = false, 1 = true). + [__unstable__] seal_is_contract(ctx, account_ptr: u32) -> u32 => { + ctx.charge_gas(RuntimeCosts::IsContract)?; + let address: <::T as frame_system::Config>::AccountId = + ctx.read_sandbox_memory_as(account_ptr)?; + + Ok(ctx.ext.is_contract(&address) as u32) + }, + + // Checks whether the caller of the current contract is the origin of the whole call stack. + // + // Prefer this over `seal_is_contract` when checking whether your contract is being called by a contract + // or a plain account. The reason is that it performs better since it does not need to + // do any storage lookups. + // + // A return value of`true` indicates that this contract is being called by a plain account + // and `false` indicates that the caller is another contract. + // + // Returned value is a u32-encoded boolean: (0 = false, 1 = true). + [__unstable__] seal_caller_is_origin(ctx) -> u32 => { + ctx.charge_gas(RuntimeCosts::CallerIsOrigin)?; + Ok(ctx.ext.caller_is_origin() as u32) + }, + // Stores the address of the current contract into the supplied buffer. // // The value is stored to linear memory at the address pointed to by `out_ptr`. diff --git a/frame/contracts/src/weights.rs b/frame/contracts/src/weights.rs index 17ee020f01134..ec6dcd2eee892 100644 --- a/frame/contracts/src/weights.rs +++ b/frame/contracts/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_contracts //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-12-20, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-02-04, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -55,6 +55,8 @@ pub trait WeightInfo { fn upload_code(c: u32, ) -> Weight; fn remove_code() -> Weight; fn seal_caller(r: u32, ) -> Weight; + fn seal_is_contract(r: u32, ) -> Weight; + fn seal_caller_is_origin(r: u32, ) -> Weight; fn seal_address(r: u32, ) -> Weight; fn seal_gas_left(r: u32, ) -> Weight; fn seal_balance(r: u32, ) -> Weight; @@ -74,15 +76,19 @@ pub trait WeightInfo { fn seal_deposit_event_per_topic_and_kb(t: u32, n: u32, ) -> Weight; fn seal_debug_message(r: u32, ) -> Weight; fn seal_set_storage(r: u32, ) -> Weight; - fn seal_set_storage_per_kb(n: u32, ) -> Weight; + fn seal_set_storage_per_new_kb(n: u32, ) -> Weight; + fn seal_set_storage_per_old_kb(n: u32, ) -> Weight; fn seal_clear_storage(r: u32, ) -> Weight; + fn seal_clear_storage_per_kb(n: u32, ) -> Weight; fn seal_get_storage(r: u32, ) -> Weight; - fn seal_contains_storage(r: u32, ) -> Weight; fn seal_get_storage_per_kb(n: u32, ) -> Weight; + fn seal_contains_storage(r: u32, ) -> Weight; + fn seal_contains_storage_per_kb(n: u32, ) -> Weight; fn seal_take_storage(r: u32, ) -> Weight; fn seal_take_storage_per_kb(n: u32, ) -> Weight; fn seal_transfer(r: u32, ) -> Weight; fn seal_call(r: u32, ) -> Weight; + fn seal_delegate_call(r: u32, ) -> Weight; fn seal_call_per_transfer_input_output_kb(t: u32, i: u32, o: u32, ) -> Weight; fn seal_instantiate(r: u32, ) -> Weight; fn seal_instantiate_per_input_output_salt_kb(i: u32, o: u32, s: u32, ) -> Weight; @@ -153,32 +159,32 @@ pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { // Storage: Contracts DeletionQueue (r:1 w:0) fn on_initialize() -> Weight { - (2_286_000 as Weight) + (1_640_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) } // Storage: Skipped Metadata (r:0 w:0) fn on_initialize_per_trie_key(k: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 3_000 - .saturating_add((2_219_000 as Weight).saturating_mul(k as Weight)) + (6_385_000 as Weight) + // Standard Error: 0 + .saturating_add((748_000 as Weight).saturating_mul(k as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(k as Weight))) } // Storage: Contracts DeletionQueue (r:1 w:0) fn on_initialize_per_queue_item(q: u32, ) -> Weight { - (95_627_000 as Weight) - // Standard Error: 2_000 - .saturating_add((242_000 as Weight).saturating_mul(q as Weight)) + (0 as Weight) + // Standard Error: 5_000 + .saturating_add((2_304_000 as Weight).saturating_mul(q as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Contracts PristineCode (r:1 w:0) // Storage: Contracts CodeStorage (r:0 w:1) fn reinstrument(c: u32, ) -> Weight { - (17_037_000 as Weight) - // Standard Error: 98_000 - .saturating_add((88_875_000 as Weight).saturating_mul(c as Weight)) + (22_923_000 as Weight) + // Standard Error: 33_000 + .saturating_add((65_851_000 as Weight).saturating_mul(c as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -187,9 +193,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Timestamp Now (r:1 w:0) // Storage: System Account (r:1 w:1) fn call_with_code_kb(c: u32, ) -> Weight { - (348_110_000 as Weight) - // Standard Error: 136_000 - .saturating_add((81_086_000 as Weight).saturating_mul(c as Weight)) + (209_577_000 as Weight) + // Standard Error: 53_000 + .saturating_add((61_341_000 as Weight).saturating_mul(c as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -201,11 +207,11 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts PristineCode (r:0 w:1) // Storage: Contracts OwnerInfoOf (r:0 w:1) fn instantiate_with_code(c: u32, s: u32, ) -> Weight { - (414_966_000 as Weight) - // Standard Error: 137_000 - .saturating_add((198_330_000 as Weight).saturating_mul(c as Weight)) - // Standard Error: 8_000 - .saturating_add((2_180_000 as Weight).saturating_mul(s as Weight)) + (240_302_000 as Weight) + // Standard Error: 119_000 + .saturating_add((151_894_000 as Weight).saturating_mul(c as Weight)) + // Standard Error: 7_000 + .saturating_add((1_740_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(6 as Weight)) } @@ -216,9 +222,9 @@ impl WeightInfo for SubstrateWeight { // Storage: System Account (r:1 w:1) // Storage: Contracts OwnerInfoOf (r:1 w:1) fn instantiate(s: u32, ) -> Weight { - (201_465_000 as Weight) + (172_047_000 as Weight) // Standard Error: 2_000 - .saturating_add((1_993_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((1_729_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(5 as Weight)) } @@ -227,7 +233,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Timestamp Now (r:1 w:0) // Storage: System Account (r:1 w:1) fn call() -> Weight { - (154_139_000 as Weight) + (139_349_000 as Weight) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -235,9 +241,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts PristineCode (r:0 w:1) // Storage: Contracts OwnerInfoOf (r:0 w:1) fn upload_code(c: u32, ) -> Weight { - (69_640_000 as Weight) - // Standard Error: 93_000 - .saturating_add((89_969_000 as Weight).saturating_mul(c as Weight)) + (50_449_000 as Weight) + // Standard Error: 45_000 + .saturating_add((68_254_000 as Weight).saturating_mul(c as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -245,7 +251,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:0 w:1) // Storage: Contracts PristineCode (r:0 w:1) fn remove_code() -> Weight { - (31_567_000 as Weight) + (24_576_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -254,9 +260,32 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_caller(r: u32, ) -> Weight { - (405_395_000 as Weight) - // Standard Error: 167_000 - .saturating_add((79_867_000 as Weight).saturating_mul(r as Weight)) + (220_059_000 as Weight) + // Standard Error: 128_000 + .saturating_add((49_607_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:0) + // Storage: Contracts ContractInfoOf (r:1 w:1) + // Storage: Contracts CodeStorage (r:1 w:0) + // Storage: Timestamp Now (r:1 w:0) + fn seal_is_contract(r: u32, ) -> Weight { + (84_138_000 as Weight) + // Standard Error: 896_000 + .saturating_add((375_553_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:0) + // Storage: Contracts ContractInfoOf (r:1 w:1) + // Storage: Contracts CodeStorage (r:1 w:0) + // Storage: Timestamp Now (r:1 w:0) + fn seal_caller_is_origin(r: u32, ) -> Weight { + (222_496_000 as Weight) + // Standard Error: 119_000 + .saturating_add((22_340_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -265,9 +294,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_address(r: u32, ) -> Weight { - (405_173_000 as Weight) - // Standard Error: 152_000 - .saturating_add((79_619_000 as Weight).saturating_mul(r as Weight)) + (221_446_000 as Weight) + // Standard Error: 131_000 + .saturating_add((49_401_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -276,9 +305,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_gas_left(r: u32, ) -> Weight { - (406_537_000 as Weight) - // Standard Error: 148_000 - .saturating_add((78_129_000 as Weight).saturating_mul(r as Weight)) + (220_964_000 as Weight) + // Standard Error: 132_000 + .saturating_add((49_230_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -287,9 +316,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_balance(r: u32, ) -> Weight { - (416_289_000 as Weight) - // Standard Error: 165_000 - .saturating_add((218_401_000 as Weight).saturating_mul(r as Weight)) + (229_399_000 as Weight) + // Standard Error: 166_000 + .saturating_add((137_407_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -298,9 +327,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_value_transferred(r: u32, ) -> Weight { - (408_205_000 as Weight) - // Standard Error: 154_000 - .saturating_add((79_563_000 as Weight).saturating_mul(r as Weight)) + (220_103_000 as Weight) + // Standard Error: 133_000 + .saturating_add((49_410_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -309,9 +338,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_minimum_balance(r: u32, ) -> Weight { - (408_124_000 as Weight) - // Standard Error: 149_000 - .saturating_add((79_032_000 as Weight).saturating_mul(r as Weight)) + (228_143_000 as Weight) + // Standard Error: 151_000 + .saturating_add((48_608_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -320,9 +349,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_block_number(r: u32, ) -> Weight { - (406_141_000 as Weight) - // Standard Error: 150_000 - .saturating_add((78_992_000 as Weight).saturating_mul(r as Weight)) + (223_899_000 as Weight) + // Standard Error: 142_000 + .saturating_add((48_841_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -331,9 +360,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_now(r: u32, ) -> Weight { - (418_112_000 as Weight) - // Standard Error: 155_000 - .saturating_add((77_902_000 as Weight).saturating_mul(r as Weight)) + (224_974_000 as Weight) + // Standard Error: 148_000 + .saturating_add((48_902_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -343,9 +372,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Timestamp Now (r:1 w:0) // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) fn seal_weight_to_fee(r: u32, ) -> Weight { - (411_683_000 as Weight) - // Standard Error: 173_000 - .saturating_add((205_824_000 as Weight).saturating_mul(r as Weight)) + (227_556_000 as Weight) + // Standard Error: 151_000 + .saturating_add((121_252_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -354,9 +383,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_gas(r: u32, ) -> Weight { - (132_178_000 as Weight) - // Standard Error: 84_000 - .saturating_add((38_233_000 as Weight).saturating_mul(r as Weight)) + (127_975_000 as Weight) + // Standard Error: 57_000 + .saturating_add((24_843_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -365,9 +394,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_input(r: u32, ) -> Weight { - (405_685_000 as Weight) - // Standard Error: 142_000 - .saturating_add((72_826_000 as Weight).saturating_mul(r as Weight)) + (224_592_000 as Weight) + // Standard Error: 141_000 + .saturating_add((48_296_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -376,9 +405,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_input_per_kb(n: u32, ) -> Weight { - (490_336_000 as Weight) - // Standard Error: 7_000 - .saturating_add((38_070_000 as Weight).saturating_mul(n as Weight)) + (296_995_000 as Weight) + // Standard Error: 3_000 + .saturating_add((11_884_000 as Weight).saturating_mul(n as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -386,10 +415,8 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts ContractInfoOf (r:1 w:1) // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) - fn seal_return(r: u32, ) -> Weight { - (384_543_000 as Weight) - // Standard Error: 105_000 - .saturating_add((15_793_000 as Weight).saturating_mul(r as Weight)) + fn seal_return(_r: u32, ) -> Weight { + (224_322_000 as Weight) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -398,9 +425,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_return_per_kb(n: u32, ) -> Weight { - (399_205_000 as Weight) + (216_240_000 as Weight) // Standard Error: 1_000 - .saturating_add((637_000 as Weight).saturating_mul(n as Weight)) + .saturating_add((206_000 as Weight).saturating_mul(n as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -411,9 +438,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts DeletionQueue (r:1 w:1) // Storage: Contracts OwnerInfoOf (r:1 w:1) fn seal_terminate(r: u32, ) -> Weight { - (396_375_000 as Weight) - // Standard Error: 3_023_000 - .saturating_add((79_797_000 as Weight).saturating_mul(r as Weight)) + (219_637_000 as Weight) + // Standard Error: 3_916_000 + .saturating_add((51_769_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().reads((4 as Weight).saturating_mul(r as Weight))) .saturating_add(T::DbWeight::get().writes(1 as Weight)) @@ -425,9 +452,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Timestamp Now (r:1 w:0) // Storage: RandomnessCollectiveFlip RandomMaterial (r:1 w:0) fn seal_random(r: u32, ) -> Weight { - (390_550_000 as Weight) - // Standard Error: 290_000 - .saturating_add((245_730_000 as Weight).saturating_mul(r as Weight)) + (221_470_000 as Weight) + // Standard Error: 154_000 + .saturating_add((158_758_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -436,9 +463,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_deposit_event(r: u32, ) -> Weight { - (408_011_000 as Weight) - // Standard Error: 273_000 - .saturating_add((406_522_000 as Weight).saturating_mul(r as Weight)) + (228_674_000 as Weight) + // Standard Error: 203_000 + .saturating_add((287_195_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -448,11 +475,11 @@ impl WeightInfo for SubstrateWeight { // Storage: Timestamp Now (r:1 w:0) // Storage: System EventTopics (r:100 w:100) fn seal_deposit_event_per_topic_and_kb(t: u32, n: u32, ) -> Weight { - (890_741_000 as Weight) - // Standard Error: 2_072_000 - .saturating_add((382_953_000 as Weight).saturating_mul(t as Weight)) - // Standard Error: 408_000 - .saturating_add((162_320_000 as Weight).saturating_mul(n as Weight)) + (507_091_000 as Weight) + // Standard Error: 1_863_000 + .saturating_add((291_858_000 as Weight).saturating_mul(t as Weight)) + // Standard Error: 367_000 + .saturating_add((83_459_000 as Weight).saturating_mul(n as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().reads((100 as Weight).saturating_mul(t as Weight))) .saturating_add(T::DbWeight::get().writes(1 as Weight)) @@ -463,79 +490,95 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_debug_message(r: u32, ) -> Weight { - (153_163_000 as Weight) - // Standard Error: 137_000 - .saturating_add((59_081_000 as Weight).saturating_mul(r as Weight)) + (133_592_000 as Weight) + // Standard Error: 87_000 + .saturating_add((41_718_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Skipped Metadata (r:0 w:0) fn seal_set_storage(r: u32, ) -> Weight { - (459_368_000 as Weight) - // Standard Error: 560_000 - .saturating_add((330_190_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) + (44_719_000 as Weight) + // Standard Error: 1_036_000 + .saturating_add((407_521_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) .saturating_add(T::DbWeight::get().writes((100 as Weight).saturating_mul(r as Weight))) } - // Storage: System Account (r:2 w:2) - // Storage: Contracts ContractInfoOf (r:1 w:1) - // Storage: Contracts CodeStorage (r:1 w:0) - // Storage: Timestamp Now (r:1 w:0) - // Storage: unknown [0x7afa01283080ef247df84e0ba38ea5a587d25ce6633a6bfbba02068c14023441] (r:1 w:1) - fn seal_set_storage_per_kb(n: u32, ) -> Weight { - (727_394_000 as Weight) - // Standard Error: 247_000 - .saturating_add((73_350_000 as Weight).saturating_mul(n as Weight)) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) + // Storage: Skipped Metadata (r:0 w:0) + fn seal_set_storage_per_new_kb(n: u32, ) -> Weight { + (606_108_000 as Weight) + // Standard Error: 315_000 + .saturating_add((29_136_000 as Weight).saturating_mul(n as Weight)) + .saturating_add(T::DbWeight::get().reads(105 as Weight)) + .saturating_add(T::DbWeight::get().writes(103 as Weight)) + } + // Storage: Skipped Metadata (r:0 w:0) + fn seal_set_storage_per_old_kb(n: u32, ) -> Weight { + (634_330_000 as Weight) + // Standard Error: 281_000 + .saturating_add((10_741_000 as Weight).saturating_mul(n as Weight)) + .saturating_add(T::DbWeight::get().reads(105 as Weight)) + .saturating_add(T::DbWeight::get().writes(103 as Weight)) } // Storage: Skipped Metadata (r:0 w:0) fn seal_clear_storage(r: u32, ) -> Weight { - (163_262_000 as Weight) - // Standard Error: 1_492_000 - .saturating_add((799_087_000 as Weight).saturating_mul(r as Weight)) + (89_750_000 as Weight) + // Standard Error: 924_000 + .saturating_add((382_525_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) .saturating_add(T::DbWeight::get().writes(3 as Weight)) .saturating_add(T::DbWeight::get().writes((100 as Weight).saturating_mul(r as Weight))) } // Storage: Skipped Metadata (r:0 w:0) + fn seal_clear_storage_per_kb(n: u32, ) -> Weight { + (616_463_000 as Weight) + // Standard Error: 260_000 + .saturating_add((10_373_000 as Weight).saturating_mul(n as Weight)) + .saturating_add(T::DbWeight::get().reads(105 as Weight)) + .saturating_add(T::DbWeight::get().writes(103 as Weight)) + } + // Storage: Skipped Metadata (r:0 w:0) fn seal_get_storage(r: u32, ) -> Weight { - (288_728_000 as Weight) - // Standard Error: 752_000 - .saturating_add((434_780_000 as Weight).saturating_mul(r as Weight)) + (116_340_000 as Weight) + // Standard Error: 633_000 + .saturating_add((322_054_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Skipped Metadata (r:0 w:0) + fn seal_get_storage_per_kb(n: u32, ) -> Weight { + (563_077_000 as Weight) + // Standard Error: 340_000 + .saturating_add((63_889_000 as Weight).saturating_mul(n as Weight)) + .saturating_add(T::DbWeight::get().reads(104 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Skipped Metadata (r:0 w:0) fn seal_contains_storage(r: u32, ) -> Weight { - (209_606_000 as Weight) - // Standard Error: 1_137_000 - .saturating_add((680_187_000 as Weight).saturating_mul(r as Weight)) + (118_832_000 as Weight) + // Standard Error: 595_000 + .saturating_add((291_817_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } - // Storage: System Account (r:1 w:0) - // Storage: Contracts ContractInfoOf (r:1 w:1) - // Storage: Contracts CodeStorage (r:1 w:0) - // Storage: Timestamp Now (r:1 w:0) - // Storage: unknown [0x7afa01283080ef247df84e0ba38ea5a587d25ce6633a6bfbba02068c14023441] (r:1 w:0) - fn seal_get_storage_per_kb(n: u32, ) -> Weight { - (619_600_000 as Weight) - // Standard Error: 207_000 - .saturating_add((111_030_000 as Weight).saturating_mul(n as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) + // Storage: Skipped Metadata (r:0 w:0) + fn seal_contains_storage_per_kb(n: u32, ) -> Weight { + (520_386_000 as Weight) + // Standard Error: 297_000 + .saturating_add((10_076_000 as Weight).saturating_mul(n as Weight)) + .saturating_add(T::DbWeight::get().reads(104 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Skipped Metadata (r:0 w:0) fn seal_take_storage(r: u32, ) -> Weight { - (279_528_000 as Weight) - // Standard Error: 932_000 - .saturating_add((541_965_000 as Weight).saturating_mul(r as Weight)) + (85_377_000 as Weight) + // Standard Error: 847_000 + .saturating_add((419_438_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) .saturating_add(T::DbWeight::get().writes(3 as Weight)) @@ -543,9 +586,9 @@ impl WeightInfo for SubstrateWeight { } // Storage: Skipped Metadata (r:0 w:0) fn seal_take_storage_per_kb(n: u32, ) -> Weight { - (985_732_000 as Weight) - // Standard Error: 446_000 - .saturating_add((123_295_000 as Weight).saturating_mul(n as Weight)) + (666_218_000 as Weight) + // Standard Error: 294_000 + .saturating_add((64_627_000 as Weight).saturating_mul(n as Weight)) .saturating_add(T::DbWeight::get().reads(105 as Weight)) .saturating_add(T::DbWeight::get().writes(103 as Weight)) } @@ -554,9 +597,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_transfer(r: u32, ) -> Weight { - (284_785_000 as Weight) - // Standard Error: 1_479_000 - .saturating_add((2_527_544_000 as Weight).saturating_mul(r as Weight)) + (108_224_000 as Weight) + // Standard Error: 1_042_000 + .saturating_add((1_723_539_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) .saturating_add(T::DbWeight::get().writes(2 as Weight)) @@ -568,25 +611,36 @@ impl WeightInfo for SubstrateWeight { // Storage: Timestamp Now (r:1 w:0) fn seal_call(r: u32, ) -> Weight { (0 as Weight) - // Standard Error: 5_742_000 - .saturating_add((37_993_391_000 as Weight).saturating_mul(r as Weight)) + // Standard Error: 7_843_000 + .saturating_add((19_825_093_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) .saturating_add(T::DbWeight::get().writes(1 as Weight)) .saturating_add(T::DbWeight::get().writes((100 as Weight).saturating_mul(r as Weight))) } // Storage: System Account (r:1 w:0) + // Storage: Contracts ContractInfoOf (r:1 w:1) + // Storage: Contracts CodeStorage (r:1 w:0) + // Storage: Timestamp Now (r:1 w:0) + fn seal_delegate_call(r: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 11_788_000 + .saturating_add((19_855_594_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads((99 as Weight).saturating_mul(r as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:0) // Storage: Contracts ContractInfoOf (r:101 w:101) // Storage: Contracts CodeStorage (r:2 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_call_per_transfer_input_output_kb(t: u32, i: u32, o: u32, ) -> Weight { - (37_404_660_000 as Weight) - // Standard Error: 92_661_000 - .saturating_add((2_486_257_000 as Weight).saturating_mul(t as Weight)) - // Standard Error: 33_000 - .saturating_add((63_001_000 as Weight).saturating_mul(i as Weight)) - // Standard Error: 35_000 - .saturating_add((101_347_000 as Weight).saturating_mul(o as Weight)) + (20_190_331_000 as Weight) + // Standard Error: 75_647_000 + .saturating_add((2_369_225_000 as Weight).saturating_mul(t as Weight)) + // Standard Error: 27_000 + .saturating_add((19_831_000 as Weight).saturating_mul(i as Weight)) + // Standard Error: 28_000 + .saturating_add((31_191_000 as Weight).saturating_mul(o as Weight)) .saturating_add(T::DbWeight::get().reads(105 as Weight)) .saturating_add(T::DbWeight::get().reads((101 as Weight).saturating_mul(t as Weight))) .saturating_add(T::DbWeight::get().writes(101 as Weight)) @@ -600,8 +654,8 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts OwnerInfoOf (r:100 w:100) fn seal_instantiate(r: u32, ) -> Weight { (0 as Weight) - // Standard Error: 119_281_000 - .saturating_add((47_113_525_000 as Weight).saturating_mul(r as Weight)) + // Standard Error: 50_368_000 + .saturating_add((27_757_564_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().reads((400 as Weight).saturating_mul(r as Weight))) .saturating_add(T::DbWeight::get().writes(3 as Weight)) @@ -614,13 +668,13 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts AccountCounter (r:1 w:1) // Storage: Contracts OwnerInfoOf (r:1 w:1) fn seal_instantiate_per_input_output_salt_kb(i: u32, o: u32, s: u32, ) -> Weight { - (41_157_901_000 as Weight) - // Standard Error: 147_000 - .saturating_add((64_877_000 as Weight).saturating_mul(i as Weight)) - // Standard Error: 147_000 - .saturating_add((102_420_000 as Weight).saturating_mul(o as Weight)) - // Standard Error: 147_000 - .saturating_add((201_587_000 as Weight).saturating_mul(s as Weight)) + (25_199_228_000 as Weight) + // Standard Error: 36_000 + .saturating_add((19_598_000 as Weight).saturating_mul(i as Weight)) + // Standard Error: 36_000 + .saturating_add((30_986_000 as Weight).saturating_mul(o as Weight)) + // Standard Error: 36_000 + .saturating_add((158_016_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(208 as Weight)) .saturating_add(T::DbWeight::get().writes(206 as Weight)) } @@ -629,9 +683,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_sha2_256(r: u32, ) -> Weight { - (402_224_000 as Weight) - // Standard Error: 166_000 - .saturating_add((103_985_000 as Weight).saturating_mul(r as Weight)) + (222_984_000 as Weight) + // Standard Error: 155_000 + .saturating_add((80_649_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -640,9 +694,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_sha2_256_per_kb(n: u32, ) -> Weight { - (663_731_000 as Weight) - // Standard Error: 42_000 - .saturating_add((505_157_000 as Weight).saturating_mul(n as Weight)) + (393_726_000 as Weight) + // Standard Error: 36_000 + .saturating_add((463_983_000 as Weight).saturating_mul(n as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -651,9 +705,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_keccak_256(r: u32, ) -> Weight { - (402_638_000 as Weight) - // Standard Error: 165_000 - .saturating_add((117_589_000 as Weight).saturating_mul(r as Weight)) + (217_461_000 as Weight) + // Standard Error: 146_000 + .saturating_add((92_540_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -662,9 +716,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_keccak_256_per_kb(n: u32, ) -> Weight { - (491_978_000 as Weight) - // Standard Error: 23_000 - .saturating_add((363_687_000 as Weight).saturating_mul(n as Weight)) + (271_742_000 as Weight) + // Standard Error: 19_000 + .saturating_add((307_055_000 as Weight).saturating_mul(n as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -673,9 +727,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_blake2_256(r: u32, ) -> Weight { - (402_254_000 as Weight) - // Standard Error: 154_000 - .saturating_add((86_403_000 as Weight).saturating_mul(r as Weight)) + (220_664_000 as Weight) + // Standard Error: 145_000 + .saturating_add((64_516_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -684,9 +738,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_blake2_256_per_kb(n: u32, ) -> Weight { - (476_405_000 as Weight) - // Standard Error: 18_000 - .saturating_add((163_921_000 as Weight).saturating_mul(n as Weight)) + (287_500_000 as Weight) + // Standard Error: 12_000 + .saturating_add((119_931_000 as Weight).saturating_mul(n as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -695,9 +749,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_blake2_128(r: u32, ) -> Weight { - (399_949_000 as Weight) - // Standard Error: 142_000 - .saturating_add((85_448_000 as Weight).saturating_mul(r as Weight)) + (214_922_000 as Weight) + // Standard Error: 122_000 + .saturating_add((64_236_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -706,9 +760,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_blake2_128_per_kb(n: u32, ) -> Weight { - (475_437_000 as Weight) - // Standard Error: 15_000 - .saturating_add((163_921_000 as Weight).saturating_mul(n as Weight)) + (251_648_000 as Weight) + // Standard Error: 13_000 + .saturating_add((120_105_000 as Weight).saturating_mul(n as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -717,266 +771,266 @@ impl WeightInfo for SubstrateWeight { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_ecdsa_recover(r: u32, ) -> Weight { - (373_575_000 as Weight) - // Standard Error: 1_639_000 - .saturating_add((15_530_027_000 as Weight).saturating_mul(r as Weight)) + (124_760_000 as Weight) + // Standard Error: 1_397_000 + .saturating_add((15_387_180_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } fn instr_i64const(r: u32, ) -> Weight { - (52_763_000 as Weight) - // Standard Error: 12_000 - .saturating_add((857_000 as Weight).saturating_mul(r as Weight)) + (75_287_000 as Weight) + // Standard Error: 11_000 + .saturating_add((569_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64load(r: u32, ) -> Weight { - (47_313_000 as Weight) - // Standard Error: 10_000 - .saturating_add((2_935_000 as Weight).saturating_mul(r as Weight)) + (74_251_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_306_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64store(r: u32, ) -> Weight { - (47_147_000 as Weight) - // Standard Error: 10_000 - .saturating_add((2_995_000 as Weight).saturating_mul(r as Weight)) + (75_072_000 as Weight) + // Standard Error: 4_000 + .saturating_add((1_386_000 as Weight).saturating_mul(r as Weight)) } fn instr_select(r: u32, ) -> Weight { - (50_124_000 as Weight) - // Standard Error: 11_000 - .saturating_add((2_421_000 as Weight).saturating_mul(r as Weight)) + (73_811_000 as Weight) + // Standard Error: 0 + .saturating_add((1_783_000 as Weight).saturating_mul(r as Weight)) } fn instr_if(r: u32, ) -> Weight { - (47_288_000 as Weight) - // Standard Error: 11_000 - .saturating_add((2_523_000 as Weight).saturating_mul(r as Weight)) + (73_901_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_886_000 as Weight).saturating_mul(r as Weight)) } fn instr_br(r: u32, ) -> Weight { - (50_198_000 as Weight) - // Standard Error: 16_000 - .saturating_add((1_473_000 as Weight).saturating_mul(r as Weight)) + (73_720_000 as Weight) + // Standard Error: 1_000 + .saturating_add((903_000 as Weight).saturating_mul(r as Weight)) } fn instr_br_if(r: u32, ) -> Weight { - (44_008_000 as Weight) - // Standard Error: 17_000 - .saturating_add((2_174_000 as Weight).saturating_mul(r as Weight)) + (73_534_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_459_000 as Weight).saturating_mul(r as Weight)) } fn instr_br_table(r: u32, ) -> Weight { - (37_602_000 as Weight) - // Standard Error: 16_000 - .saturating_add((2_820_000 as Weight).saturating_mul(r as Weight)) + (73_281_000 as Weight) + // Standard Error: 8_000 + .saturating_add((1_584_000 as Weight).saturating_mul(r as Weight)) } fn instr_br_table_per_entry(e: u32, ) -> Weight { - (46_232_000 as Weight) - // Standard Error: 3_000 - .saturating_add((17_000 as Weight).saturating_mul(e as Weight)) + (76_135_000 as Weight) + // Standard Error: 1_000 + .saturating_add((6_000 as Weight).saturating_mul(e as Weight)) } fn instr_call(r: u32, ) -> Weight { - (40_148_000 as Weight) - // Standard Error: 22_000 - .saturating_add((20_585_000 as Weight).saturating_mul(r as Weight)) + (75_938_000 as Weight) + // Standard Error: 23_000 + .saturating_add((17_156_000 as Weight).saturating_mul(r as Weight)) } fn instr_call_indirect(r: u32, ) -> Weight { - (43_948_000 as Weight) - // Standard Error: 31_000 - .saturating_add((30_226_000 as Weight).saturating_mul(r as Weight)) + (85_864_000 as Weight) + // Standard Error: 28_000 + .saturating_add((28_343_000 as Weight).saturating_mul(r as Weight)) } fn instr_call_indirect_per_param(p: u32, ) -> Weight { - (78_722_000 as Weight) - // Standard Error: 5_000 - .saturating_add((1_199_000 as Weight).saturating_mul(p as Weight)) + (119_795_000 as Weight) + // Standard Error: 1_000 + .saturating_add((911_000 as Weight).saturating_mul(p as Weight)) } fn instr_local_get(r: u32, ) -> Weight { - (48_083_000 as Weight) - // Standard Error: 12_000 - .saturating_add((805_000 as Weight).saturating_mul(r as Weight)) + (74_750_000 as Weight) + // Standard Error: 1_000 + .saturating_add((613_000 as Weight).saturating_mul(r as Weight)) } fn instr_local_set(r: u32, ) -> Weight { - (47_710_000 as Weight) - // Standard Error: 11_000 - .saturating_add((843_000 as Weight).saturating_mul(r as Weight)) + (74_831_000 as Weight) + // Standard Error: 2_000 + .saturating_add((672_000 as Weight).saturating_mul(r as Weight)) } fn instr_local_tee(r: u32, ) -> Weight { - (44_785_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_466_000 as Weight).saturating_mul(r as Weight)) + (74_314_000 as Weight) + // Standard Error: 1_000 + .saturating_add((902_000 as Weight).saturating_mul(r as Weight)) } fn instr_global_get(r: u32, ) -> Weight { - (50_106_000 as Weight) - // Standard Error: 20_000 - .saturating_add((1_641_000 as Weight).saturating_mul(r as Weight)) + (77_040_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_161_000 as Weight).saturating_mul(r as Weight)) } fn instr_global_set(r: u32, ) -> Weight { - (47_058_000 as Weight) - // Standard Error: 18_000 - .saturating_add((1_707_000 as Weight).saturating_mul(r as Weight)) + (76_770_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_372_000 as Weight).saturating_mul(r as Weight)) } fn instr_memory_current(r: u32, ) -> Weight { - (51_494_000 as Weight) - // Standard Error: 15_000 - .saturating_add((925_000 as Weight).saturating_mul(r as Weight)) + (74_010_000 as Weight) + // Standard Error: 1_000 + .saturating_add((665_000 as Weight).saturating_mul(r as Weight)) } fn instr_memory_grow(r: u32, ) -> Weight { - (36_983_000 as Weight) - // Standard Error: 3_602_000 - .saturating_add((634_259_000 as Weight).saturating_mul(r as Weight)) + (73_597_000 as Weight) + // Standard Error: 929_000 + .saturating_add((183_940_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64clz(r: u32, ) -> Weight { - (60_711_000 as Weight) - // Standard Error: 22_000 - .saturating_add((1_157_000 as Weight).saturating_mul(r as Weight)) + (74_488_000 as Weight) + // Standard Error: 4_000 + .saturating_add((893_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64ctz(r: u32, ) -> Weight { - (53_908_000 as Weight) - // Standard Error: 9_000 - .saturating_add((1_305_000 as Weight).saturating_mul(r as Weight)) + (74_024_000 as Weight) + // Standard Error: 5_000 + .saturating_add((908_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64popcnt(r: u32, ) -> Weight { - (53_939_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_314_000 as Weight).saturating_mul(r as Weight)) + (74_084_000 as Weight) + // Standard Error: 1_000 + .saturating_add((895_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64eqz(r: u32, ) -> Weight { - (54_086_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_309_000 as Weight).saturating_mul(r as Weight)) + (74_250_000 as Weight) + // Standard Error: 2_000 + .saturating_add((916_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64extendsi32(r: u32, ) -> Weight { - (43_845_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_493_000 as Weight).saturating_mul(r as Weight)) + (74_027_000 as Weight) + // Standard Error: 1_000 + .saturating_add((883_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64extendui32(r: u32, ) -> Weight { - (43_518_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_501_000 as Weight).saturating_mul(r as Weight)) + (74_201_000 as Weight) + // Standard Error: 1_000 + .saturating_add((879_000 as Weight).saturating_mul(r as Weight)) } fn instr_i32wrapi64(r: u32, ) -> Weight { - (53_912_000 as Weight) - // Standard Error: 9_000 - .saturating_add((1_302_000 as Weight).saturating_mul(r as Weight)) + (74_116_000 as Weight) + // Standard Error: 1_000 + .saturating_add((892_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64eq(r: u32, ) -> Weight { - (49_594_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_890_000 as Weight).saturating_mul(r as Weight)) + (74_109_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_358_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64ne(r: u32, ) -> Weight { - (49_659_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_894_000 as Weight).saturating_mul(r as Weight)) + (73_962_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_363_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64lts(r: u32, ) -> Weight { - (49_401_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_902_000 as Weight).saturating_mul(r as Weight)) + (73_977_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_360_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64ltu(r: u32, ) -> Weight { - (49_880_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_885_000 as Weight).saturating_mul(r as Weight)) + (74_046_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_360_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64gts(r: u32, ) -> Weight { - (49_466_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_894_000 as Weight).saturating_mul(r as Weight)) + (73_912_000 as Weight) + // Standard Error: 0 + .saturating_add((1_362_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64gtu(r: u32, ) -> Weight { - (49_514_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_891_000 as Weight).saturating_mul(r as Weight)) + (73_918_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_367_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64les(r: u32, ) -> Weight { - (49_588_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_898_000 as Weight).saturating_mul(r as Weight)) + (73_953_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_363_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64leu(r: u32, ) -> Weight { - (49_589_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_891_000 as Weight).saturating_mul(r as Weight)) + (74_855_000 as Weight) + // Standard Error: 4_000 + .saturating_add((1_347_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64ges(r: u32, ) -> Weight { - (49_685_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_892_000 as Weight).saturating_mul(r as Weight)) + (73_917_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_364_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64geu(r: u32, ) -> Weight { - (49_601_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_891_000 as Weight).saturating_mul(r as Weight)) + (73_949_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_361_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64add(r: u32, ) -> Weight { - (49_430_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_894_000 as Weight).saturating_mul(r as Weight)) + (73_726_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_347_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64sub(r: u32, ) -> Weight { - (49_533_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_893_000 as Weight).saturating_mul(r as Weight)) + (73_921_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_345_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64mul(r: u32, ) -> Weight { - (49_766_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_888_000 as Weight).saturating_mul(r as Weight)) + (73_924_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_341_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64divs(r: u32, ) -> Weight { - (49_315_000 as Weight) - // Standard Error: 11_000 - .saturating_add((2_552_000 as Weight).saturating_mul(r as Weight)) + (73_842_000 as Weight) + // Standard Error: 2_000 + .saturating_add((2_011_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64divu(r: u32, ) -> Weight { - (49_786_000 as Weight) - // Standard Error: 11_000 - .saturating_add((2_203_000 as Weight).saturating_mul(r as Weight)) + (73_932_000 as Weight) + // Standard Error: 1_000 + .saturating_add((2_057_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64rems(r: u32, ) -> Weight { - (49_651_000 as Weight) - // Standard Error: 11_000 - .saturating_add((2_461_000 as Weight).saturating_mul(r as Weight)) + (74_028_000 as Weight) + // Standard Error: 2_000 + .saturating_add((2_001_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64remu(r: u32, ) -> Weight { - (49_747_000 as Weight) - // Standard Error: 10_000 - .saturating_add((2_196_000 as Weight).saturating_mul(r as Weight)) + (73_784_000 as Weight) + // Standard Error: 2_000 + .saturating_add((2_059_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64and(r: u32, ) -> Weight { - (49_719_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_892_000 as Weight).saturating_mul(r as Weight)) + (74_169_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_334_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64or(r: u32, ) -> Weight { - (49_463_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_896_000 as Weight).saturating_mul(r as Weight)) + (73_982_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_340_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64xor(r: u32, ) -> Weight { - (49_379_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_903_000 as Weight).saturating_mul(r as Weight)) + (74_310_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_329_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64shl(r: u32, ) -> Weight { - (49_404_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_902_000 as Weight).saturating_mul(r as Weight)) + (73_861_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_362_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64shrs(r: u32, ) -> Weight { - (49_498_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_900_000 as Weight).saturating_mul(r as Weight)) + (73_787_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_364_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64shru(r: u32, ) -> Weight { - (49_541_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_897_000 as Weight).saturating_mul(r as Weight)) + (73_886_000 as Weight) + // Standard Error: 7_000 + .saturating_add((1_372_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64rotl(r: u32, ) -> Weight { - (49_452_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_900_000 as Weight).saturating_mul(r as Weight)) + (73_860_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_362_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64rotr(r: u32, ) -> Weight { - (49_350_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_902_000 as Weight).saturating_mul(r as Weight)) + (73_917_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_356_000 as Weight).saturating_mul(r as Weight)) } } @@ -984,32 +1038,32 @@ impl WeightInfo for SubstrateWeight { impl WeightInfo for () { // Storage: Contracts DeletionQueue (r:1 w:0) fn on_initialize() -> Weight { - (2_286_000 as Weight) + (1_640_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) } // Storage: Skipped Metadata (r:0 w:0) fn on_initialize_per_trie_key(k: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 3_000 - .saturating_add((2_219_000 as Weight).saturating_mul(k as Weight)) + (6_385_000 as Weight) + // Standard Error: 0 + .saturating_add((748_000 as Weight).saturating_mul(k as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(k as Weight))) } // Storage: Contracts DeletionQueue (r:1 w:0) fn on_initialize_per_queue_item(q: u32, ) -> Weight { - (95_627_000 as Weight) - // Standard Error: 2_000 - .saturating_add((242_000 as Weight).saturating_mul(q as Weight)) + (0 as Weight) + // Standard Error: 5_000 + .saturating_add((2_304_000 as Weight).saturating_mul(q as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Contracts PristineCode (r:1 w:0) // Storage: Contracts CodeStorage (r:0 w:1) fn reinstrument(c: u32, ) -> Weight { - (17_037_000 as Weight) - // Standard Error: 98_000 - .saturating_add((88_875_000 as Weight).saturating_mul(c as Weight)) + (22_923_000 as Weight) + // Standard Error: 33_000 + .saturating_add((65_851_000 as Weight).saturating_mul(c as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1018,9 +1072,9 @@ impl WeightInfo for () { // Storage: Timestamp Now (r:1 w:0) // Storage: System Account (r:1 w:1) fn call_with_code_kb(c: u32, ) -> Weight { - (348_110_000 as Weight) - // Standard Error: 136_000 - .saturating_add((81_086_000 as Weight).saturating_mul(c as Weight)) + (209_577_000 as Weight) + // Standard Error: 53_000 + .saturating_add((61_341_000 as Weight).saturating_mul(c as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -1032,11 +1086,11 @@ impl WeightInfo for () { // Storage: Contracts PristineCode (r:0 w:1) // Storage: Contracts OwnerInfoOf (r:0 w:1) fn instantiate_with_code(c: u32, s: u32, ) -> Weight { - (414_966_000 as Weight) - // Standard Error: 137_000 - .saturating_add((198_330_000 as Weight).saturating_mul(c as Weight)) - // Standard Error: 8_000 - .saturating_add((2_180_000 as Weight).saturating_mul(s as Weight)) + (240_302_000 as Weight) + // Standard Error: 119_000 + .saturating_add((151_894_000 as Weight).saturating_mul(c as Weight)) + // Standard Error: 7_000 + .saturating_add((1_740_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(6 as Weight)) } @@ -1047,9 +1101,9 @@ impl WeightInfo for () { // Storage: System Account (r:1 w:1) // Storage: Contracts OwnerInfoOf (r:1 w:1) fn instantiate(s: u32, ) -> Weight { - (201_465_000 as Weight) + (172_047_000 as Weight) // Standard Error: 2_000 - .saturating_add((1_993_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((1_729_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(5 as Weight)) } @@ -1058,7 +1112,7 @@ impl WeightInfo for () { // Storage: Timestamp Now (r:1 w:0) // Storage: System Account (r:1 w:1) fn call() -> Weight { - (154_139_000 as Weight) + (139_349_000 as Weight) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -1066,9 +1120,9 @@ impl WeightInfo for () { // Storage: Contracts PristineCode (r:0 w:1) // Storage: Contracts OwnerInfoOf (r:0 w:1) fn upload_code(c: u32, ) -> Weight { - (69_640_000 as Weight) - // Standard Error: 93_000 - .saturating_add((89_969_000 as Weight).saturating_mul(c as Weight)) + (50_449_000 as Weight) + // Standard Error: 45_000 + .saturating_add((68_254_000 as Weight).saturating_mul(c as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } @@ -1076,7 +1130,7 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:0 w:1) // Storage: Contracts PristineCode (r:0 w:1) fn remove_code() -> Weight { - (31_567_000 as Weight) + (24_576_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } @@ -1085,9 +1139,32 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_caller(r: u32, ) -> Weight { - (405_395_000 as Weight) - // Standard Error: 167_000 - .saturating_add((79_867_000 as Weight).saturating_mul(r as Weight)) + (220_059_000 as Weight) + // Standard Error: 128_000 + .saturating_add((49_607_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:0) + // Storage: Contracts ContractInfoOf (r:1 w:1) + // Storage: Contracts CodeStorage (r:1 w:0) + // Storage: Timestamp Now (r:1 w:0) + fn seal_is_contract(r: u32, ) -> Weight { + (84_138_000 as Weight) + // Standard Error: 896_000 + .saturating_add((375_553_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:0) + // Storage: Contracts ContractInfoOf (r:1 w:1) + // Storage: Contracts CodeStorage (r:1 w:0) + // Storage: Timestamp Now (r:1 w:0) + fn seal_caller_is_origin(r: u32, ) -> Weight { + (222_496_000 as Weight) + // Standard Error: 119_000 + .saturating_add((22_340_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1096,9 +1173,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_address(r: u32, ) -> Weight { - (405_173_000 as Weight) - // Standard Error: 152_000 - .saturating_add((79_619_000 as Weight).saturating_mul(r as Weight)) + (221_446_000 as Weight) + // Standard Error: 131_000 + .saturating_add((49_401_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1107,9 +1184,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_gas_left(r: u32, ) -> Weight { - (406_537_000 as Weight) - // Standard Error: 148_000 - .saturating_add((78_129_000 as Weight).saturating_mul(r as Weight)) + (220_964_000 as Weight) + // Standard Error: 132_000 + .saturating_add((49_230_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1118,9 +1195,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_balance(r: u32, ) -> Weight { - (416_289_000 as Weight) - // Standard Error: 165_000 - .saturating_add((218_401_000 as Weight).saturating_mul(r as Weight)) + (229_399_000 as Weight) + // Standard Error: 166_000 + .saturating_add((137_407_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1129,9 +1206,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_value_transferred(r: u32, ) -> Weight { - (408_205_000 as Weight) - // Standard Error: 154_000 - .saturating_add((79_563_000 as Weight).saturating_mul(r as Weight)) + (220_103_000 as Weight) + // Standard Error: 133_000 + .saturating_add((49_410_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1140,9 +1217,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_minimum_balance(r: u32, ) -> Weight { - (408_124_000 as Weight) - // Standard Error: 149_000 - .saturating_add((79_032_000 as Weight).saturating_mul(r as Weight)) + (228_143_000 as Weight) + // Standard Error: 151_000 + .saturating_add((48_608_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1151,9 +1228,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_block_number(r: u32, ) -> Weight { - (406_141_000 as Weight) - // Standard Error: 150_000 - .saturating_add((78_992_000 as Weight).saturating_mul(r as Weight)) + (223_899_000 as Weight) + // Standard Error: 142_000 + .saturating_add((48_841_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1162,9 +1239,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_now(r: u32, ) -> Weight { - (418_112_000 as Weight) - // Standard Error: 155_000 - .saturating_add((77_902_000 as Weight).saturating_mul(r as Weight)) + (224_974_000 as Weight) + // Standard Error: 148_000 + .saturating_add((48_902_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1174,9 +1251,9 @@ impl WeightInfo for () { // Storage: Timestamp Now (r:1 w:0) // Storage: TransactionPayment NextFeeMultiplier (r:1 w:0) fn seal_weight_to_fee(r: u32, ) -> Weight { - (411_683_000 as Weight) - // Standard Error: 173_000 - .saturating_add((205_824_000 as Weight).saturating_mul(r as Weight)) + (227_556_000 as Weight) + // Standard Error: 151_000 + .saturating_add((121_252_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1185,9 +1262,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_gas(r: u32, ) -> Weight { - (132_178_000 as Weight) - // Standard Error: 84_000 - .saturating_add((38_233_000 as Weight).saturating_mul(r as Weight)) + (127_975_000 as Weight) + // Standard Error: 57_000 + .saturating_add((24_843_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1196,9 +1273,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_input(r: u32, ) -> Weight { - (405_685_000 as Weight) - // Standard Error: 142_000 - .saturating_add((72_826_000 as Weight).saturating_mul(r as Weight)) + (224_592_000 as Weight) + // Standard Error: 141_000 + .saturating_add((48_296_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1207,9 +1284,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_input_per_kb(n: u32, ) -> Weight { - (490_336_000 as Weight) - // Standard Error: 7_000 - .saturating_add((38_070_000 as Weight).saturating_mul(n as Weight)) + (296_995_000 as Weight) + // Standard Error: 3_000 + .saturating_add((11_884_000 as Weight).saturating_mul(n as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1217,10 +1294,8 @@ impl WeightInfo for () { // Storage: Contracts ContractInfoOf (r:1 w:1) // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) - fn seal_return(r: u32, ) -> Weight { - (384_543_000 as Weight) - // Standard Error: 105_000 - .saturating_add((15_793_000 as Weight).saturating_mul(r as Weight)) + fn seal_return(_r: u32, ) -> Weight { + (224_322_000 as Weight) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1229,9 +1304,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_return_per_kb(n: u32, ) -> Weight { - (399_205_000 as Weight) + (216_240_000 as Weight) // Standard Error: 1_000 - .saturating_add((637_000 as Weight).saturating_mul(n as Weight)) + .saturating_add((206_000 as Weight).saturating_mul(n as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1242,9 +1317,9 @@ impl WeightInfo for () { // Storage: Contracts DeletionQueue (r:1 w:1) // Storage: Contracts OwnerInfoOf (r:1 w:1) fn seal_terminate(r: u32, ) -> Weight { - (396_375_000 as Weight) - // Standard Error: 3_023_000 - .saturating_add((79_797_000 as Weight).saturating_mul(r as Weight)) + (219_637_000 as Weight) + // Standard Error: 3_916_000 + .saturating_add((51_769_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().reads((4 as Weight).saturating_mul(r as Weight))) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) @@ -1256,9 +1331,9 @@ impl WeightInfo for () { // Storage: Timestamp Now (r:1 w:0) // Storage: RandomnessCollectiveFlip RandomMaterial (r:1 w:0) fn seal_random(r: u32, ) -> Weight { - (390_550_000 as Weight) - // Standard Error: 290_000 - .saturating_add((245_730_000 as Weight).saturating_mul(r as Weight)) + (221_470_000 as Weight) + // Standard Error: 154_000 + .saturating_add((158_758_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1267,9 +1342,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_deposit_event(r: u32, ) -> Weight { - (408_011_000 as Weight) - // Standard Error: 273_000 - .saturating_add((406_522_000 as Weight).saturating_mul(r as Weight)) + (228_674_000 as Weight) + // Standard Error: 203_000 + .saturating_add((287_195_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1279,11 +1354,11 @@ impl WeightInfo for () { // Storage: Timestamp Now (r:1 w:0) // Storage: System EventTopics (r:100 w:100) fn seal_deposit_event_per_topic_and_kb(t: u32, n: u32, ) -> Weight { - (890_741_000 as Weight) - // Standard Error: 2_072_000 - .saturating_add((382_953_000 as Weight).saturating_mul(t as Weight)) - // Standard Error: 408_000 - .saturating_add((162_320_000 as Weight).saturating_mul(n as Weight)) + (507_091_000 as Weight) + // Standard Error: 1_863_000 + .saturating_add((291_858_000 as Weight).saturating_mul(t as Weight)) + // Standard Error: 367_000 + .saturating_add((83_459_000 as Weight).saturating_mul(n as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().reads((100 as Weight).saturating_mul(t as Weight))) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) @@ -1294,79 +1369,95 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_debug_message(r: u32, ) -> Weight { - (153_163_000 as Weight) - // Standard Error: 137_000 - .saturating_add((59_081_000 as Weight).saturating_mul(r as Weight)) + (133_592_000 as Weight) + // Standard Error: 87_000 + .saturating_add((41_718_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Skipped Metadata (r:0 w:0) fn seal_set_storage(r: u32, ) -> Weight { - (459_368_000 as Weight) - // Standard Error: 560_000 - .saturating_add((330_190_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + (44_719_000 as Weight) + // Standard Error: 1_036_000 + .saturating_add((407_521_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) .saturating_add(RocksDbWeight::get().writes((100 as Weight).saturating_mul(r as Weight))) } - // Storage: System Account (r:2 w:2) - // Storage: Contracts ContractInfoOf (r:1 w:1) - // Storage: Contracts CodeStorage (r:1 w:0) - // Storage: Timestamp Now (r:1 w:0) - // Storage: unknown [0x7afa01283080ef247df84e0ba38ea5a587d25ce6633a6bfbba02068c14023441] (r:1 w:1) - fn seal_set_storage_per_kb(n: u32, ) -> Weight { - (727_394_000 as Weight) - // Standard Error: 247_000 - .saturating_add((73_350_000 as Weight).saturating_mul(n as Weight)) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + // Storage: Skipped Metadata (r:0 w:0) + fn seal_set_storage_per_new_kb(n: u32, ) -> Weight { + (606_108_000 as Weight) + // Standard Error: 315_000 + .saturating_add((29_136_000 as Weight).saturating_mul(n as Weight)) + .saturating_add(RocksDbWeight::get().reads(105 as Weight)) + .saturating_add(RocksDbWeight::get().writes(103 as Weight)) + } + // Storage: Skipped Metadata (r:0 w:0) + fn seal_set_storage_per_old_kb(n: u32, ) -> Weight { + (634_330_000 as Weight) + // Standard Error: 281_000 + .saturating_add((10_741_000 as Weight).saturating_mul(n as Weight)) + .saturating_add(RocksDbWeight::get().reads(105 as Weight)) + .saturating_add(RocksDbWeight::get().writes(103 as Weight)) } // Storage: Skipped Metadata (r:0 w:0) fn seal_clear_storage(r: u32, ) -> Weight { - (163_262_000 as Weight) - // Standard Error: 1_492_000 - .saturating_add((799_087_000 as Weight).saturating_mul(r as Weight)) + (89_750_000 as Weight) + // Standard Error: 924_000 + .saturating_add((382_525_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) .saturating_add(RocksDbWeight::get().writes((100 as Weight).saturating_mul(r as Weight))) } // Storage: Skipped Metadata (r:0 w:0) + fn seal_clear_storage_per_kb(n: u32, ) -> Weight { + (616_463_000 as Weight) + // Standard Error: 260_000 + .saturating_add((10_373_000 as Weight).saturating_mul(n as Weight)) + .saturating_add(RocksDbWeight::get().reads(105 as Weight)) + .saturating_add(RocksDbWeight::get().writes(103 as Weight)) + } + // Storage: Skipped Metadata (r:0 w:0) fn seal_get_storage(r: u32, ) -> Weight { - (288_728_000 as Weight) - // Standard Error: 752_000 - .saturating_add((434_780_000 as Weight).saturating_mul(r as Weight)) + (116_340_000 as Weight) + // Standard Error: 633_000 + .saturating_add((322_054_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Skipped Metadata (r:0 w:0) + fn seal_get_storage_per_kb(n: u32, ) -> Weight { + (563_077_000 as Weight) + // Standard Error: 340_000 + .saturating_add((63_889_000 as Weight).saturating_mul(n as Weight)) + .saturating_add(RocksDbWeight::get().reads(104 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Skipped Metadata (r:0 w:0) fn seal_contains_storage(r: u32, ) -> Weight { - (209_606_000 as Weight) - // Standard Error: 1_137_000 - .saturating_add((680_187_000 as Weight).saturating_mul(r as Weight)) + (118_832_000 as Weight) + // Standard Error: 595_000 + .saturating_add((291_817_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } - // Storage: System Account (r:1 w:0) - // Storage: Contracts ContractInfoOf (r:1 w:1) - // Storage: Contracts CodeStorage (r:1 w:0) - // Storage: Timestamp Now (r:1 w:0) - // Storage: unknown [0x7afa01283080ef247df84e0ba38ea5a587d25ce6633a6bfbba02068c14023441] (r:1 w:0) - fn seal_get_storage_per_kb(n: u32, ) -> Weight { - (619_600_000 as Weight) - // Standard Error: 207_000 - .saturating_add((111_030_000 as Weight).saturating_mul(n as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + // Storage: Skipped Metadata (r:0 w:0) + fn seal_contains_storage_per_kb(n: u32, ) -> Weight { + (520_386_000 as Weight) + // Standard Error: 297_000 + .saturating_add((10_076_000 as Weight).saturating_mul(n as Weight)) + .saturating_add(RocksDbWeight::get().reads(104 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Skipped Metadata (r:0 w:0) fn seal_take_storage(r: u32, ) -> Weight { - (279_528_000 as Weight) - // Standard Error: 932_000 - .saturating_add((541_965_000 as Weight).saturating_mul(r as Weight)) + (85_377_000 as Weight) + // Standard Error: 847_000 + .saturating_add((419_438_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) @@ -1374,9 +1465,9 @@ impl WeightInfo for () { } // Storage: Skipped Metadata (r:0 w:0) fn seal_take_storage_per_kb(n: u32, ) -> Weight { - (985_732_000 as Weight) - // Standard Error: 446_000 - .saturating_add((123_295_000 as Weight).saturating_mul(n as Weight)) + (666_218_000 as Weight) + // Standard Error: 294_000 + .saturating_add((64_627_000 as Weight).saturating_mul(n as Weight)) .saturating_add(RocksDbWeight::get().reads(105 as Weight)) .saturating_add(RocksDbWeight::get().writes(103 as Weight)) } @@ -1385,9 +1476,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_transfer(r: u32, ) -> Weight { - (284_785_000 as Weight) - // Standard Error: 1_479_000 - .saturating_add((2_527_544_000 as Weight).saturating_mul(r as Weight)) + (108_224_000 as Weight) + // Standard Error: 1_042_000 + .saturating_add((1_723_539_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) @@ -1399,25 +1490,36 @@ impl WeightInfo for () { // Storage: Timestamp Now (r:1 w:0) fn seal_call(r: u32, ) -> Weight { (0 as Weight) - // Standard Error: 5_742_000 - .saturating_add((37_993_391_000 as Weight).saturating_mul(r as Weight)) + // Standard Error: 7_843_000 + .saturating_add((19_825_093_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().reads((100 as Weight).saturating_mul(r as Weight))) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) .saturating_add(RocksDbWeight::get().writes((100 as Weight).saturating_mul(r as Weight))) } // Storage: System Account (r:1 w:0) + // Storage: Contracts ContractInfoOf (r:1 w:1) + // Storage: Contracts CodeStorage (r:1 w:0) + // Storage: Timestamp Now (r:1 w:0) + fn seal_delegate_call(r: u32, ) -> Weight { + (0 as Weight) + // Standard Error: 11_788_000 + .saturating_add((19_855_594_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads((99 as Weight).saturating_mul(r as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: System Account (r:1 w:0) // Storage: Contracts ContractInfoOf (r:101 w:101) // Storage: Contracts CodeStorage (r:2 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_call_per_transfer_input_output_kb(t: u32, i: u32, o: u32, ) -> Weight { - (37_404_660_000 as Weight) - // Standard Error: 92_661_000 - .saturating_add((2_486_257_000 as Weight).saturating_mul(t as Weight)) - // Standard Error: 33_000 - .saturating_add((63_001_000 as Weight).saturating_mul(i as Weight)) - // Standard Error: 35_000 - .saturating_add((101_347_000 as Weight).saturating_mul(o as Weight)) + (20_190_331_000 as Weight) + // Standard Error: 75_647_000 + .saturating_add((2_369_225_000 as Weight).saturating_mul(t as Weight)) + // Standard Error: 27_000 + .saturating_add((19_831_000 as Weight).saturating_mul(i as Weight)) + // Standard Error: 28_000 + .saturating_add((31_191_000 as Weight).saturating_mul(o as Weight)) .saturating_add(RocksDbWeight::get().reads(105 as Weight)) .saturating_add(RocksDbWeight::get().reads((101 as Weight).saturating_mul(t as Weight))) .saturating_add(RocksDbWeight::get().writes(101 as Weight)) @@ -1431,8 +1533,8 @@ impl WeightInfo for () { // Storage: Contracts OwnerInfoOf (r:100 w:100) fn seal_instantiate(r: u32, ) -> Weight { (0 as Weight) - // Standard Error: 119_281_000 - .saturating_add((47_113_525_000 as Weight).saturating_mul(r as Weight)) + // Standard Error: 50_368_000 + .saturating_add((27_757_564_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().reads((400 as Weight).saturating_mul(r as Weight))) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) @@ -1445,13 +1547,13 @@ impl WeightInfo for () { // Storage: Contracts AccountCounter (r:1 w:1) // Storage: Contracts OwnerInfoOf (r:1 w:1) fn seal_instantiate_per_input_output_salt_kb(i: u32, o: u32, s: u32, ) -> Weight { - (41_157_901_000 as Weight) - // Standard Error: 147_000 - .saturating_add((64_877_000 as Weight).saturating_mul(i as Weight)) - // Standard Error: 147_000 - .saturating_add((102_420_000 as Weight).saturating_mul(o as Weight)) - // Standard Error: 147_000 - .saturating_add((201_587_000 as Weight).saturating_mul(s as Weight)) + (25_199_228_000 as Weight) + // Standard Error: 36_000 + .saturating_add((19_598_000 as Weight).saturating_mul(i as Weight)) + // Standard Error: 36_000 + .saturating_add((30_986_000 as Weight).saturating_mul(o as Weight)) + // Standard Error: 36_000 + .saturating_add((158_016_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(208 as Weight)) .saturating_add(RocksDbWeight::get().writes(206 as Weight)) } @@ -1460,9 +1562,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_sha2_256(r: u32, ) -> Weight { - (402_224_000 as Weight) - // Standard Error: 166_000 - .saturating_add((103_985_000 as Weight).saturating_mul(r as Weight)) + (222_984_000 as Weight) + // Standard Error: 155_000 + .saturating_add((80_649_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1471,9 +1573,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_sha2_256_per_kb(n: u32, ) -> Weight { - (663_731_000 as Weight) - // Standard Error: 42_000 - .saturating_add((505_157_000 as Weight).saturating_mul(n as Weight)) + (393_726_000 as Weight) + // Standard Error: 36_000 + .saturating_add((463_983_000 as Weight).saturating_mul(n as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1482,9 +1584,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_keccak_256(r: u32, ) -> Weight { - (402_638_000 as Weight) - // Standard Error: 165_000 - .saturating_add((117_589_000 as Weight).saturating_mul(r as Weight)) + (217_461_000 as Weight) + // Standard Error: 146_000 + .saturating_add((92_540_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1493,9 +1595,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_keccak_256_per_kb(n: u32, ) -> Weight { - (491_978_000 as Weight) - // Standard Error: 23_000 - .saturating_add((363_687_000 as Weight).saturating_mul(n as Weight)) + (271_742_000 as Weight) + // Standard Error: 19_000 + .saturating_add((307_055_000 as Weight).saturating_mul(n as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1504,9 +1606,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_blake2_256(r: u32, ) -> Weight { - (402_254_000 as Weight) - // Standard Error: 154_000 - .saturating_add((86_403_000 as Weight).saturating_mul(r as Weight)) + (220_664_000 as Weight) + // Standard Error: 145_000 + .saturating_add((64_516_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1515,9 +1617,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_blake2_256_per_kb(n: u32, ) -> Weight { - (476_405_000 as Weight) - // Standard Error: 18_000 - .saturating_add((163_921_000 as Weight).saturating_mul(n as Weight)) + (287_500_000 as Weight) + // Standard Error: 12_000 + .saturating_add((119_931_000 as Weight).saturating_mul(n as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1526,9 +1628,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_blake2_128(r: u32, ) -> Weight { - (399_949_000 as Weight) - // Standard Error: 142_000 - .saturating_add((85_448_000 as Weight).saturating_mul(r as Weight)) + (214_922_000 as Weight) + // Standard Error: 122_000 + .saturating_add((64_236_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1537,9 +1639,9 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_hash_blake2_128_per_kb(n: u32, ) -> Weight { - (475_437_000 as Weight) - // Standard Error: 15_000 - .saturating_add((163_921_000 as Weight).saturating_mul(n as Weight)) + (251_648_000 as Weight) + // Standard Error: 13_000 + .saturating_add((120_105_000 as Weight).saturating_mul(n as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -1548,265 +1650,265 @@ impl WeightInfo for () { // Storage: Contracts CodeStorage (r:1 w:0) // Storage: Timestamp Now (r:1 w:0) fn seal_ecdsa_recover(r: u32, ) -> Weight { - (373_575_000 as Weight) - // Standard Error: 1_639_000 - .saturating_add((15_530_027_000 as Weight).saturating_mul(r as Weight)) + (124_760_000 as Weight) + // Standard Error: 1_397_000 + .saturating_add((15_387_180_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } fn instr_i64const(r: u32, ) -> Weight { - (52_763_000 as Weight) - // Standard Error: 12_000 - .saturating_add((857_000 as Weight).saturating_mul(r as Weight)) + (75_287_000 as Weight) + // Standard Error: 11_000 + .saturating_add((569_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64load(r: u32, ) -> Weight { - (47_313_000 as Weight) - // Standard Error: 10_000 - .saturating_add((2_935_000 as Weight).saturating_mul(r as Weight)) + (74_251_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_306_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64store(r: u32, ) -> Weight { - (47_147_000 as Weight) - // Standard Error: 10_000 - .saturating_add((2_995_000 as Weight).saturating_mul(r as Weight)) + (75_072_000 as Weight) + // Standard Error: 4_000 + .saturating_add((1_386_000 as Weight).saturating_mul(r as Weight)) } fn instr_select(r: u32, ) -> Weight { - (50_124_000 as Weight) - // Standard Error: 11_000 - .saturating_add((2_421_000 as Weight).saturating_mul(r as Weight)) + (73_811_000 as Weight) + // Standard Error: 0 + .saturating_add((1_783_000 as Weight).saturating_mul(r as Weight)) } fn instr_if(r: u32, ) -> Weight { - (47_288_000 as Weight) - // Standard Error: 11_000 - .saturating_add((2_523_000 as Weight).saturating_mul(r as Weight)) + (73_901_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_886_000 as Weight).saturating_mul(r as Weight)) } fn instr_br(r: u32, ) -> Weight { - (50_198_000 as Weight) - // Standard Error: 16_000 - .saturating_add((1_473_000 as Weight).saturating_mul(r as Weight)) + (73_720_000 as Weight) + // Standard Error: 1_000 + .saturating_add((903_000 as Weight).saturating_mul(r as Weight)) } fn instr_br_if(r: u32, ) -> Weight { - (44_008_000 as Weight) - // Standard Error: 17_000 - .saturating_add((2_174_000 as Weight).saturating_mul(r as Weight)) + (73_534_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_459_000 as Weight).saturating_mul(r as Weight)) } fn instr_br_table(r: u32, ) -> Weight { - (37_602_000 as Weight) - // Standard Error: 16_000 - .saturating_add((2_820_000 as Weight).saturating_mul(r as Weight)) + (73_281_000 as Weight) + // Standard Error: 8_000 + .saturating_add((1_584_000 as Weight).saturating_mul(r as Weight)) } fn instr_br_table_per_entry(e: u32, ) -> Weight { - (46_232_000 as Weight) - // Standard Error: 3_000 - .saturating_add((17_000 as Weight).saturating_mul(e as Weight)) + (76_135_000 as Weight) + // Standard Error: 1_000 + .saturating_add((6_000 as Weight).saturating_mul(e as Weight)) } fn instr_call(r: u32, ) -> Weight { - (40_148_000 as Weight) - // Standard Error: 22_000 - .saturating_add((20_585_000 as Weight).saturating_mul(r as Weight)) + (75_938_000 as Weight) + // Standard Error: 23_000 + .saturating_add((17_156_000 as Weight).saturating_mul(r as Weight)) } fn instr_call_indirect(r: u32, ) -> Weight { - (43_948_000 as Weight) - // Standard Error: 31_000 - .saturating_add((30_226_000 as Weight).saturating_mul(r as Weight)) + (85_864_000 as Weight) + // Standard Error: 28_000 + .saturating_add((28_343_000 as Weight).saturating_mul(r as Weight)) } fn instr_call_indirect_per_param(p: u32, ) -> Weight { - (78_722_000 as Weight) - // Standard Error: 5_000 - .saturating_add((1_199_000 as Weight).saturating_mul(p as Weight)) + (119_795_000 as Weight) + // Standard Error: 1_000 + .saturating_add((911_000 as Weight).saturating_mul(p as Weight)) } fn instr_local_get(r: u32, ) -> Weight { - (48_083_000 as Weight) - // Standard Error: 12_000 - .saturating_add((805_000 as Weight).saturating_mul(r as Weight)) + (74_750_000 as Weight) + // Standard Error: 1_000 + .saturating_add((613_000 as Weight).saturating_mul(r as Weight)) } fn instr_local_set(r: u32, ) -> Weight { - (47_710_000 as Weight) - // Standard Error: 11_000 - .saturating_add((843_000 as Weight).saturating_mul(r as Weight)) + (74_831_000 as Weight) + // Standard Error: 2_000 + .saturating_add((672_000 as Weight).saturating_mul(r as Weight)) } fn instr_local_tee(r: u32, ) -> Weight { - (44_785_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_466_000 as Weight).saturating_mul(r as Weight)) + (74_314_000 as Weight) + // Standard Error: 1_000 + .saturating_add((902_000 as Weight).saturating_mul(r as Weight)) } fn instr_global_get(r: u32, ) -> Weight { - (50_106_000 as Weight) - // Standard Error: 20_000 - .saturating_add((1_641_000 as Weight).saturating_mul(r as Weight)) + (77_040_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_161_000 as Weight).saturating_mul(r as Weight)) } fn instr_global_set(r: u32, ) -> Weight { - (47_058_000 as Weight) - // Standard Error: 18_000 - .saturating_add((1_707_000 as Weight).saturating_mul(r as Weight)) + (76_770_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_372_000 as Weight).saturating_mul(r as Weight)) } fn instr_memory_current(r: u32, ) -> Weight { - (51_494_000 as Weight) - // Standard Error: 15_000 - .saturating_add((925_000 as Weight).saturating_mul(r as Weight)) + (74_010_000 as Weight) + // Standard Error: 1_000 + .saturating_add((665_000 as Weight).saturating_mul(r as Weight)) } fn instr_memory_grow(r: u32, ) -> Weight { - (36_983_000 as Weight) - // Standard Error: 3_602_000 - .saturating_add((634_259_000 as Weight).saturating_mul(r as Weight)) + (73_597_000 as Weight) + // Standard Error: 929_000 + .saturating_add((183_940_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64clz(r: u32, ) -> Weight { - (60_711_000 as Weight) - // Standard Error: 22_000 - .saturating_add((1_157_000 as Weight).saturating_mul(r as Weight)) + (74_488_000 as Weight) + // Standard Error: 4_000 + .saturating_add((893_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64ctz(r: u32, ) -> Weight { - (53_908_000 as Weight) - // Standard Error: 9_000 - .saturating_add((1_305_000 as Weight).saturating_mul(r as Weight)) + (74_024_000 as Weight) + // Standard Error: 5_000 + .saturating_add((908_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64popcnt(r: u32, ) -> Weight { - (53_939_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_314_000 as Weight).saturating_mul(r as Weight)) + (74_084_000 as Weight) + // Standard Error: 1_000 + .saturating_add((895_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64eqz(r: u32, ) -> Weight { - (54_086_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_309_000 as Weight).saturating_mul(r as Weight)) + (74_250_000 as Weight) + // Standard Error: 2_000 + .saturating_add((916_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64extendsi32(r: u32, ) -> Weight { - (43_845_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_493_000 as Weight).saturating_mul(r as Weight)) + (74_027_000 as Weight) + // Standard Error: 1_000 + .saturating_add((883_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64extendui32(r: u32, ) -> Weight { - (43_518_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_501_000 as Weight).saturating_mul(r as Weight)) + (74_201_000 as Weight) + // Standard Error: 1_000 + .saturating_add((879_000 as Weight).saturating_mul(r as Weight)) } fn instr_i32wrapi64(r: u32, ) -> Weight { - (53_912_000 as Weight) - // Standard Error: 9_000 - .saturating_add((1_302_000 as Weight).saturating_mul(r as Weight)) + (74_116_000 as Weight) + // Standard Error: 1_000 + .saturating_add((892_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64eq(r: u32, ) -> Weight { - (49_594_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_890_000 as Weight).saturating_mul(r as Weight)) + (74_109_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_358_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64ne(r: u32, ) -> Weight { - (49_659_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_894_000 as Weight).saturating_mul(r as Weight)) + (73_962_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_363_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64lts(r: u32, ) -> Weight { - (49_401_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_902_000 as Weight).saturating_mul(r as Weight)) + (73_977_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_360_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64ltu(r: u32, ) -> Weight { - (49_880_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_885_000 as Weight).saturating_mul(r as Weight)) + (74_046_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_360_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64gts(r: u32, ) -> Weight { - (49_466_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_894_000 as Weight).saturating_mul(r as Weight)) + (73_912_000 as Weight) + // Standard Error: 0 + .saturating_add((1_362_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64gtu(r: u32, ) -> Weight { - (49_514_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_891_000 as Weight).saturating_mul(r as Weight)) + (73_918_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_367_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64les(r: u32, ) -> Weight { - (49_588_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_898_000 as Weight).saturating_mul(r as Weight)) + (73_953_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_363_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64leu(r: u32, ) -> Weight { - (49_589_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_891_000 as Weight).saturating_mul(r as Weight)) + (74_855_000 as Weight) + // Standard Error: 4_000 + .saturating_add((1_347_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64ges(r: u32, ) -> Weight { - (49_685_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_892_000 as Weight).saturating_mul(r as Weight)) + (73_917_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_364_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64geu(r: u32, ) -> Weight { - (49_601_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_891_000 as Weight).saturating_mul(r as Weight)) + (73_949_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_361_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64add(r: u32, ) -> Weight { - (49_430_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_894_000 as Weight).saturating_mul(r as Weight)) + (73_726_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_347_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64sub(r: u32, ) -> Weight { - (49_533_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_893_000 as Weight).saturating_mul(r as Weight)) + (73_921_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_345_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64mul(r: u32, ) -> Weight { - (49_766_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_888_000 as Weight).saturating_mul(r as Weight)) + (73_924_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_341_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64divs(r: u32, ) -> Weight { - (49_315_000 as Weight) - // Standard Error: 11_000 - .saturating_add((2_552_000 as Weight).saturating_mul(r as Weight)) + (73_842_000 as Weight) + // Standard Error: 2_000 + .saturating_add((2_011_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64divu(r: u32, ) -> Weight { - (49_786_000 as Weight) - // Standard Error: 11_000 - .saturating_add((2_203_000 as Weight).saturating_mul(r as Weight)) + (73_932_000 as Weight) + // Standard Error: 1_000 + .saturating_add((2_057_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64rems(r: u32, ) -> Weight { - (49_651_000 as Weight) - // Standard Error: 11_000 - .saturating_add((2_461_000 as Weight).saturating_mul(r as Weight)) + (74_028_000 as Weight) + // Standard Error: 2_000 + .saturating_add((2_001_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64remu(r: u32, ) -> Weight { - (49_747_000 as Weight) - // Standard Error: 10_000 - .saturating_add((2_196_000 as Weight).saturating_mul(r as Weight)) + (73_784_000 as Weight) + // Standard Error: 2_000 + .saturating_add((2_059_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64and(r: u32, ) -> Weight { - (49_719_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_892_000 as Weight).saturating_mul(r as Weight)) + (74_169_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_334_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64or(r: u32, ) -> Weight { - (49_463_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_896_000 as Weight).saturating_mul(r as Weight)) + (73_982_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_340_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64xor(r: u32, ) -> Weight { - (49_379_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_903_000 as Weight).saturating_mul(r as Weight)) + (74_310_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_329_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64shl(r: u32, ) -> Weight { - (49_404_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_902_000 as Weight).saturating_mul(r as Weight)) + (73_861_000 as Weight) + // Standard Error: 2_000 + .saturating_add((1_362_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64shrs(r: u32, ) -> Weight { - (49_498_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_900_000 as Weight).saturating_mul(r as Weight)) + (73_787_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_364_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64shru(r: u32, ) -> Weight { - (49_541_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_897_000 as Weight).saturating_mul(r as Weight)) + (73_886_000 as Weight) + // Standard Error: 7_000 + .saturating_add((1_372_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64rotl(r: u32, ) -> Weight { - (49_452_000 as Weight) - // Standard Error: 11_000 - .saturating_add((1_900_000 as Weight).saturating_mul(r as Weight)) + (73_860_000 as Weight) + // Standard Error: 3_000 + .saturating_add((1_362_000 as Weight).saturating_mul(r as Weight)) } fn instr_i64rotr(r: u32, ) -> Weight { - (49_350_000 as Weight) - // Standard Error: 10_000 - .saturating_add((1_902_000 as Weight).saturating_mul(r as Weight)) + (73_917_000 as Weight) + // Standard Error: 1_000 + .saturating_add((1_356_000 as Weight).saturating_mul(r as Weight)) } } diff --git a/frame/conviction-voting/Cargo.toml b/frame/conviction-voting/Cargo.toml new file mode 100644 index 0000000000000..7b51e3f8c91ad --- /dev/null +++ b/frame/conviction-voting/Cargo.toml @@ -0,0 +1,53 @@ +[package] +name = "pallet-conviction-voting" +version = "4.0.0-dev" +authors = ["Parity Technologies "] +edition = "2018" +license = "Apache-2.0" +homepage = "https://substrate.io" +repository = "https://github.com/paritytech/substrate/" +description = "FRAME pallet for conviction voting in referenda" +readme = "README.md" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +serde = { version = "1.0.136", optional = true, features = ["derive"] } +codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [ + "derive", +] } +scale-info = { version = "1.0", default-features = false, features = ["derive"] } +sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } +frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } +frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } +frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } +assert_matches = "1.3.0" + +[dev-dependencies] +sp-core = { version = "5.0.0", path = "../../primitives/core" } +pallet-balances = { version = "4.0.0-dev", path = "../balances" } +pallet-scheduler = { version = "4.0.0-dev", path = "../scheduler" } + +[features] +default = ["std"] +std = [ + "serde", + "codec/std", + "scale-info/std", + "sp-std/std", + "sp-io/std", + "frame-benchmarking/std", + "frame-support/std", + "sp-runtime/std", + "frame-system/std", +] +runtime-benchmarks = [ + "frame-benchmarking", + "frame-system/runtime-benchmarks", + "frame-support/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", +] +try-runtime = ["frame-support/try-runtime"] diff --git a/frame/conviction-voting/README.md b/frame/conviction-voting/README.md new file mode 100644 index 0000000000000..5dc5d526d5c23 --- /dev/null +++ b/frame/conviction-voting/README.md @@ -0,0 +1,8 @@ +# Voting Pallet + +- [`assembly::Config`](https://docs.rs/pallet-assembly/latest/pallet_assembly/trait.Config.html) +- [`Call`](https://docs.rs/pallet-assembly/latest/pallet_assembly/enum.Call.html) + +## Overview + +Pallet for voting in referenda. diff --git a/frame/conviction-voting/src/benchmarking.rs b/frame/conviction-voting/src/benchmarking.rs new file mode 100644 index 0000000000000..2beee4f3b49d2 --- /dev/null +++ b/frame/conviction-voting/src/benchmarking.rs @@ -0,0 +1,278 @@ +// This file is part of Substrate. + +// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! ConvictionVoting pallet benchmarking. + +use super::*; + +use assert_matches::assert_matches; +use frame_benchmarking::{account, benchmarks, whitelist_account}; +use frame_support::{ + dispatch::RawOrigin, + traits::{fungible, Currency, Get}, +}; +use sp_runtime::traits::Bounded; +use sp_std::collections::btree_map::BTreeMap; + +use crate::Pallet as ConvictionVoting; + +const SEED: u32 = 0; + +/// Fill all classes as much as possible up to `MaxVotes` and return the Class with the most votes +/// ongoing. +fn fill_voting() -> (ClassOf, BTreeMap, Vec>>) { + let mut r = BTreeMap::, Vec>>::new(); + for class in T::Polls::classes().into_iter() { + for _ in 0..T::MaxVotes::get() { + match T::Polls::create_ongoing(class.clone()) { + Ok(i) => r.entry(class.clone()).or_default().push(i), + Err(()) => break, + } + } + } + let c = r.iter().max_by_key(|(_, ref v)| v.len()).unwrap().0.clone(); + (c, r) +} + +fn funded_account(name: &'static str, index: u32) -> T::AccountId { + let caller: T::AccountId = account(name, index, SEED); + T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); + caller +} + +fn account_vote(b: BalanceOf) -> AccountVote> { + let v = Vote { aye: true, conviction: Conviction::Locked1x }; + + AccountVote::Standard { vote: v, balance: b } +} + +benchmarks! { + where_clause { where T::MaxVotes: core::fmt::Debug } + + vote_new { + let caller = funded_account::("caller", 0); + whitelist_account!(caller); + let account_vote = account_vote::(100u32.into()); + + let (class, all_polls) = fill_voting::(); + let polls = &all_polls[&class]; + let r = polls.len() - 1; + // We need to create existing votes + for i in polls.iter().skip(1) { + ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), *i, account_vote.clone())?; + } + let votes = match VotingFor::::get(&caller, &class) { + Voting::Casting(Casting { votes, .. }) => votes, + _ => return Err("Votes are not direct".into()), + }; + assert_eq!(votes.len(), r as usize, "Votes were not recorded."); + + let index = polls[0]; + }: vote(RawOrigin::Signed(caller.clone()), index, account_vote) + verify { + assert_matches!( + VotingFor::::get(&caller, &class), + Voting::Casting(Casting { votes, .. }) if votes.len() == (r + 1) as usize + ); + } + + vote_existing { + let caller = funded_account::("caller", 0); + whitelist_account!(caller); + let old_account_vote = account_vote::(100u32.into()); + + let (class, all_polls) = fill_voting::(); + let polls = &all_polls[&class]; + let r = polls.len(); + // We need to create existing votes + for i in polls.iter() { + ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), *i, old_account_vote.clone())?; + } + let votes = match VotingFor::::get(&caller, &class) { + Voting::Casting(Casting { votes, .. }) => votes, + _ => return Err("Votes are not direct".into()), + }; + assert_eq!(votes.len(), r, "Votes were not recorded."); + + let new_account_vote = account_vote::(200u32.into()); + let index = polls[0]; + }: vote(RawOrigin::Signed(caller.clone()), index, new_account_vote) + verify { + assert_matches!( + VotingFor::::get(&caller, &class), + Voting::Casting(Casting { votes, .. }) if votes.len() == r as usize + ); + } + + remove_vote { + let caller = funded_account::("caller", 0); + whitelist_account!(caller); + let old_account_vote = account_vote::(100u32.into()); + + let (class, all_polls) = fill_voting::(); + let polls = &all_polls[&class]; + let r = polls.len(); + // We need to create existing votes + for i in polls.iter() { + ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), *i, old_account_vote.clone())?; + } + let votes = match VotingFor::::get(&caller, &class) { + Voting::Casting(Casting { votes, .. }) => votes, + _ => return Err("Votes are not direct".into()), + }; + assert_eq!(votes.len(), r, "Votes were not recorded."); + + let index = polls[0]; + }: _(RawOrigin::Signed(caller.clone()), Some(class.clone()), index) + verify { + assert_matches!( + VotingFor::::get(&caller, &class), + Voting::Casting(Casting { votes, .. }) if votes.len() == (r - 1) as usize + ); + } + + remove_other_vote { + let caller = funded_account::("caller", 0); + let voter = funded_account::("caller", 0); + whitelist_account!(caller); + let old_account_vote = account_vote::(100u32.into()); + + let (class, all_polls) = fill_voting::(); + let polls = &all_polls[&class]; + let r = polls.len(); + // We need to create existing votes + for i in polls.iter() { + ConvictionVoting::::vote(RawOrigin::Signed(voter.clone()).into(), *i, old_account_vote.clone())?; + } + let votes = match VotingFor::::get(&caller, &class) { + Voting::Casting(Casting { votes, .. }) => votes, + _ => return Err("Votes are not direct".into()), + }; + assert_eq!(votes.len(), r, "Votes were not recorded."); + + let index = polls[0]; + assert!(T::Polls::end_ongoing(index, false).is_ok()); + }: _(RawOrigin::Signed(caller.clone()), voter.clone(), class.clone(), index) + verify { + assert_matches!( + VotingFor::::get(&voter, &class), + Voting::Casting(Casting { votes, .. }) if votes.len() == (r - 1) as usize + ); + } + + delegate { + let r in 0 .. T::MaxVotes::get().min(T::Polls::max_ongoing().1); + + let all_polls = fill_voting::().1; + let class = T::Polls::max_ongoing().0; + let polls = &all_polls[&class]; + let voter = funded_account::("voter", 0); + let caller = funded_account::("caller", 0); + whitelist_account!(caller); + + let delegated_balance: BalanceOf = 1000u32.into(); + let delegate_vote = account_vote::(delegated_balance); + + // We need to create existing delegations + for i in polls.iter().take(r as usize) { + ConvictionVoting::::vote(RawOrigin::Signed(voter.clone()).into(), *i, delegate_vote.clone())?; + } + assert_matches!( + VotingFor::::get(&voter, &class), + Voting::Casting(Casting { votes, .. }) if votes.len() == r as usize + ); + + }: _(RawOrigin::Signed(caller.clone()), class.clone(), voter.clone(), Conviction::Locked1x, delegated_balance) + verify { + assert_matches!(VotingFor::::get(&caller, &class), Voting::Delegating(_)); + } + + undelegate { + let r in 0 .. T::MaxVotes::get().min(T::Polls::max_ongoing().1); + + let all_polls = fill_voting::().1; + let class = T::Polls::max_ongoing().0; + let polls = &all_polls[&class]; + let voter = funded_account::("voter", 0); + let caller = funded_account::("caller", 0); + whitelist_account!(caller); + + let delegated_balance: BalanceOf = 1000u32.into(); + let delegate_vote = account_vote::(delegated_balance); + + ConvictionVoting::::delegate( + RawOrigin::Signed(caller.clone()).into(), + class.clone(), + voter.clone(), + Conviction::Locked1x, + delegated_balance, + )?; + + // We need to create delegations + for i in polls.iter().take(r as usize) { + ConvictionVoting::::vote(RawOrigin::Signed(voter.clone()).into(), *i, delegate_vote.clone())?; + } + assert_matches!( + VotingFor::::get(&voter, &class), + Voting::Casting(Casting { votes, .. }) if votes.len() == r as usize + ); + assert_matches!(VotingFor::::get(&caller, &class), Voting::Delegating(_)); + }: _(RawOrigin::Signed(caller.clone()), class.clone()) + verify { + assert_matches!(VotingFor::::get(&caller, &class), Voting::Casting(_)); + } + + unlock { + let caller = funded_account::("caller", 0); + whitelist_account!(caller); + let normal_account_vote = account_vote::(T::Currency::free_balance(&caller) - 100u32.into()); + let big_account_vote = account_vote::(T::Currency::free_balance(&caller)); + + // Fill everything up to the max by filling all classes with votes and voting on them all. + let (class, all_polls) = fill_voting::(); + assert!(all_polls.len() > 0); + for (class, polls) in all_polls.iter() { + assert!(polls.len() > 0); + for i in polls.iter() { + ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), *i, normal_account_vote.clone())?; + } + } + + let orig_usable = >::reducible_balance(&caller, false); + let polls = &all_polls[&class]; + + // Vote big on the class with the most ongoing votes of them to bump the lock and make it + // hard to recompute when removed. + ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), polls[0], big_account_vote.clone())?; + let now_usable = >::reducible_balance(&caller, false); + assert_eq!(orig_usable - now_usable, 100u32.into()); + + // Remove the vote + ConvictionVoting::::remove_vote(RawOrigin::Signed(caller.clone()).into(), Some(class.clone()), polls[0])?; + + // We can now unlock on `class` from 200 to 100... + }: _(RawOrigin::Signed(caller.clone()), class, caller.clone()) + verify { + assert_eq!(orig_usable, >::reducible_balance(&caller, false)); + } + + impl_benchmark_test_suite!( + ConvictionVoting, + crate::tests::new_test_ext(), + crate::tests::Test + ); +} diff --git a/frame/conviction-voting/src/conviction.rs b/frame/conviction-voting/src/conviction.rs new file mode 100644 index 0000000000000..129f2771124b5 --- /dev/null +++ b/frame/conviction-voting/src/conviction.rs @@ -0,0 +1,131 @@ +// This file is part of Substrate. + +// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The conviction datatype. + +use crate::types::Delegations; +use codec::{Decode, Encode, MaxEncodedLen}; +use scale_info::TypeInfo; +use sp_runtime::{ + traits::{Bounded, CheckedDiv, CheckedMul, Zero}, + RuntimeDebug, +}; +use sp_std::{convert::TryFrom, result::Result}; + +/// A value denoting the strength of conviction of a vote. +#[derive( + Encode, + Decode, + Copy, + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + RuntimeDebug, + TypeInfo, + MaxEncodedLen, +)] +pub enum Conviction { + /// 0.1x votes, unlocked. + None, + /// 1x votes, locked for an enactment period following a successful vote. + Locked1x, + /// 2x votes, locked for 2x enactment periods following a successful vote. + Locked2x, + /// 3x votes, locked for 4x... + Locked3x, + /// 4x votes, locked for 8x... + Locked4x, + /// 5x votes, locked for 16x... + Locked5x, + /// 6x votes, locked for 32x... + Locked6x, +} + +impl Default for Conviction { + fn default() -> Self { + Conviction::None + } +} + +impl From for u8 { + fn from(c: Conviction) -> u8 { + match c { + Conviction::None => 0, + Conviction::Locked1x => 1, + Conviction::Locked2x => 2, + Conviction::Locked3x => 3, + Conviction::Locked4x => 4, + Conviction::Locked5x => 5, + Conviction::Locked6x => 6, + } + } +} + +impl TryFrom for Conviction { + type Error = (); + fn try_from(i: u8) -> Result { + Ok(match i { + 0 => Conviction::None, + 1 => Conviction::Locked1x, + 2 => Conviction::Locked2x, + 3 => Conviction::Locked3x, + 4 => Conviction::Locked4x, + 5 => Conviction::Locked5x, + 6 => Conviction::Locked6x, + _ => return Err(()), + }) + } +} + +impl Conviction { + /// The amount of time (in number of periods) that our conviction implies a successful voter's + /// balance should be locked for. + pub fn lock_periods(self) -> u32 { + match self { + Conviction::None => 0, + Conviction::Locked1x => 1, + Conviction::Locked2x => 2, + Conviction::Locked3x => 4, + Conviction::Locked4x => 8, + Conviction::Locked5x => 16, + Conviction::Locked6x => 32, + } + } + + /// The votes of a voter of the given `balance` with our conviction. + pub fn votes + Zero + Copy + CheckedMul + CheckedDiv + Bounded>( + self, + capital: B, + ) -> Delegations { + let votes = match self { + Conviction::None => capital.checked_div(&10u8.into()).unwrap_or_else(Zero::zero), + x => capital.checked_mul(&u8::from(x).into()).unwrap_or_else(B::max_value), + }; + Delegations { votes, capital } + } +} + +impl Bounded for Conviction { + fn min_value() -> Self { + Conviction::None + } + fn max_value() -> Self { + Conviction::Locked6x + } +} diff --git a/frame/conviction-voting/src/lib.rs b/frame/conviction-voting/src/lib.rs new file mode 100644 index 0000000000000..8e7e0d91b1cf4 --- /dev/null +++ b/frame/conviction-voting/src/lib.rs @@ -0,0 +1,632 @@ +// This file is part of Substrate. + +// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! # Voting Pallet +//! +//! - [`Config`] +//! - [`Call`] +//! +//! ## Overview +//! +//! Pallet for managing actual voting in polls. + +#![recursion_limit = "256"] +#![cfg_attr(not(feature = "std"), no_std)] + +use frame_support::{ + ensure, + traits::{ + fungible, Currency, Get, LockIdentifier, LockableCurrency, PollStatus, Polling, + ReservableCurrency, WithdrawReasons, + }, +}; +use sp_runtime::{ + traits::{AtLeast32BitUnsigned, Saturating, Zero}, + ArithmeticError, DispatchError, DispatchResult, Perbill, +}; +use sp_std::prelude::*; + +mod conviction; +mod types; +mod vote; +pub mod weights; +pub use conviction::Conviction; +pub use pallet::*; +pub use types::{Delegations, Tally, UnvoteScope}; +pub use vote::{AccountVote, Casting, Delegating, Vote, Voting}; +pub use weights::WeightInfo; + +#[cfg(test)] +mod tests; + +#[cfg(feature = "runtime-benchmarks")] +pub mod benchmarking; + +const CONVICTION_VOTING_ID: LockIdentifier = *b"pyconvot"; + +type BalanceOf = + <::Currency as Currency<::AccountId>>::Balance; +type VotingOf = Voting< + BalanceOf, + ::AccountId, + ::BlockNumber, + PollIndexOf, + ::MaxVotes, +>; +#[allow(dead_code)] +type DelegatingOf = Delegating< + BalanceOf, + ::AccountId, + ::BlockNumber, +>; +pub type TallyOf = Tally, ::MaxTurnout>; +pub type VotesOf = BalanceOf; +type PollIndexOf = <::Polls as Polling>>::Index; +#[cfg(feature = "runtime-benchmarks")] +type IndexOf = <::Polls as Polling>>::Index; +type ClassOf = <::Polls as Polling>>::Class; + +#[frame_support::pallet] +pub mod pallet { + use super::*; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; + use sp_runtime::DispatchResult; + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + #[pallet::without_storage_info] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config + Sized { + // System level stuff. + type Event: From> + IsType<::Event>; + /// Weight information for extrinsics in this pallet. + type WeightInfo: WeightInfo; + /// Currency type with which voting happens. + type Currency: ReservableCurrency + + LockableCurrency + + fungible::Inspect; + + /// The implementation of the logic which conducts polls. + type Polls: Polling, Votes = BalanceOf, Moment = Self::BlockNumber>; + + /// The maximum amount of tokens which may be used for voting. May just be + /// `Currency::total_issuance`, but you might want to reduce this in order to account for + /// funds in the system which are unable to vote (e.g. parachain auction deposits). + type MaxTurnout: Get>; + + /// The maximum number of concurrent votes an account may have. + /// + /// Also used to compute weight, an overly large value can + /// lead to extrinsic with large weight estimation: see `delegate` for instance. + #[pallet::constant] + type MaxVotes: Get; + + /// The minimum period of vote locking. + /// + /// It should be no shorter than enactment period to ensure that in the case of an approval, + /// those successful voters are locked into the consequences that their votes entail. + #[pallet::constant] + type VoteLockingPeriod: Get; + } + + /// All voting for a particular voter in a particular voting class. We store the balance for the + /// number of votes that we have recorded. + #[pallet::storage] + pub type VotingFor = StorageDoubleMap< + _, + Twox64Concat, + T::AccountId, + Twox64Concat, + ClassOf, + VotingOf, + ValueQuery, + >; + + /// The voting classes which have a non-zero lock requirement and the lock amounts which they + /// require. The actual amount locked on behalf of this pallet should always be the maximum of + /// this list. + #[pallet::storage] + pub type ClassLocksFor = + StorageMap<_, Twox64Concat, T::AccountId, Vec<(ClassOf, BalanceOf)>, ValueQuery>; + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + /// An account has delegated their vote to another account. \[who, target\] + Delegated(T::AccountId, T::AccountId), + /// An \[account\] has cancelled a previous delegation operation. + Undelegated(T::AccountId), + } + + #[pallet::error] + pub enum Error { + /// Poll is not ongoing. + NotOngoing, + /// The given account did not vote on the poll. + NotVoter, + /// The actor has no permission to conduct the action. + NoPermission, + /// The actor has no permission to conduct the action right now but will do in the future. + NoPermissionYet, + /// The account is already delegating. + AlreadyDelegating, + /// The account currently has votes attached to it and the operation cannot succeed until + /// these are removed, either through `unvote` or `reap_vote`. + AlreadyVoting, + /// Too high a balance was provided that the account cannot afford. + InsufficientFunds, + /// The account is not currently delegating. + NotDelegating, + /// Delegation to oneself makes no sense. + Nonsense, + /// Maximum number of votes reached. + MaxVotesReached, + /// The class must be supplied since it is not easily determinable from the state. + ClassNeeded, + /// The class ID supplied is invalid. + BadClass, + } + + #[pallet::call] + impl Pallet { + /// Vote in a poll. If `vote.is_aye()`, the vote is to enact the proposal; + /// otherwise it is a vote to keep the status quo. + /// + /// The dispatch origin of this call must be _Signed_. + /// + /// - `poll_index`: The index of the poll to vote for. + /// - `vote`: The vote configuration. + /// + /// Weight: `O(R)` where R is the number of polls the voter has voted on. + #[pallet::weight(T::WeightInfo::vote_new().max(T::WeightInfo::vote_existing()))] + pub fn vote( + origin: OriginFor, + #[pallet::compact] poll_index: PollIndexOf, + vote: AccountVote>, + ) -> DispatchResult { + let who = ensure_signed(origin)?; + Self::try_vote(&who, poll_index, vote) + } + + /// Delegate the voting power (with some given conviction) of the sending account for a + /// particular class of polls. + /// + /// The balance delegated is locked for as long as it's delegated, and thereafter for the + /// time appropriate for the conviction's lock period. + /// + /// The dispatch origin of this call must be _Signed_, and the signing account must either: + /// - be delegating already; or + /// - have no voting activity (if there is, then it will need to be removed/consolidated + /// through `reap_vote` or `unvote`). + /// + /// - `to`: The account whose voting the `target` account's voting power will follow. + /// - `class`: The class of polls to delegate. To delegate multiple classes, multiple calls + /// to this function are required. + /// - `conviction`: The conviction that will be attached to the delegated votes. When the + /// account is undelegated, the funds will be locked for the corresponding period. + /// - `balance`: The amount of the account's balance to be used in delegating. This must not + /// be more than the account's current balance. + /// + /// Emits `Delegated`. + /// + /// Weight: `O(R)` where R is the number of polls the voter delegating to has + /// voted on. Weight is initially charged as if maximum votes, but is refunded later. + // NOTE: weight must cover an incorrect voting of origin with max votes, this is ensure + // because a valid delegation cover decoding a direct voting with max votes. + #[pallet::weight(T::WeightInfo::delegate(T::MaxVotes::get()))] + pub fn delegate( + origin: OriginFor, + class: ClassOf, + to: T::AccountId, + conviction: Conviction, + balance: BalanceOf, + ) -> DispatchResultWithPostInfo { + let who = ensure_signed(origin)?; + let votes = Self::try_delegate(who, class, to, conviction, balance)?; + + Ok(Some(T::WeightInfo::delegate(votes)).into()) + } + + /// Undelegate the voting power of the sending account for a particular class of polls. + /// + /// Tokens may be unlocked following once an amount of time consistent with the lock period + /// of the conviction with which the delegation was issued. + /// + /// The dispatch origin of this call must be _Signed_ and the signing account must be + /// currently delegating. + /// + /// - `class`: The class of polls to remove the delegation from. + /// + /// Emits `Undelegated`. + /// + /// Weight: `O(R)` where R is the number of polls the voter delegating to has + /// voted on. Weight is initially charged as if maximum votes, but is refunded later. + // NOTE: weight must cover an incorrect voting of origin with max votes, this is ensure + // because a valid delegation cover decoding a direct voting with max votes. + #[pallet::weight(T::WeightInfo::undelegate(T::MaxVotes::get().into()))] + pub fn undelegate(origin: OriginFor, class: ClassOf) -> DispatchResultWithPostInfo { + let who = ensure_signed(origin)?; + let votes = Self::try_undelegate(who, class)?; + Ok(Some(T::WeightInfo::undelegate(votes)).into()) + } + + /// Remove the lock caused prior voting/delegating which has expired within a particluar + /// class. + /// + /// The dispatch origin of this call must be _Signed_. + /// + /// - `class`: The class of polls to unlock. + /// - `target`: The account to remove the lock on. + /// + /// Weight: `O(R)` with R number of vote of target. + #[pallet::weight(T::WeightInfo::unlock())] + pub fn unlock( + origin: OriginFor, + class: ClassOf, + target: T::AccountId, + ) -> DispatchResult { + ensure_signed(origin)?; + Self::update_lock(&class, &target); + Ok(()) + } + + /// Remove a vote for a poll. + /// + /// If: + /// - the poll was cancelled, or + /// - the poll is ongoing, or + /// - the poll has ended such that + /// - the vote of the account was in opposition to the result; or + /// - there was no conviction to the account's vote; or + /// - the account made a split vote + /// ...then the vote is removed cleanly and a following call to `unlock` may result in more + /// funds being available. + /// + /// If, however, the poll has ended and: + /// - it finished corresponding to the vote of the account, and + /// - the account made a standard vote with conviction, and + /// - the lock period of the conviction is not over + /// ...then the lock will be aggregated into the overall account's lock, which may involve + /// *overlocking* (where the two locks are combined into a single lock that is the maximum + /// of both the amount locked and the time is it locked for). + /// + /// The dispatch origin of this call must be _Signed_, and the signer must have a vote + /// registered for poll `index`. + /// + /// - `index`: The index of poll of the vote to be removed. + /// - `class`: Optional parameter, if given it indicates the class of the poll. For polls + /// which have finished or are cancelled, this must be `Some`. + /// + /// Weight: `O(R + log R)` where R is the number of polls that `target` has voted on. + /// Weight is calculated for the maximum number of vote. + #[pallet::weight(T::WeightInfo::remove_vote())] + pub fn remove_vote( + origin: OriginFor, + class: Option>, + index: PollIndexOf, + ) -> DispatchResult { + let who = ensure_signed(origin)?; + Self::try_remove_vote(&who, index, class, UnvoteScope::Any) + } + + /// Remove a vote for a poll. + /// + /// If the `target` is equal to the signer, then this function is exactly equivalent to + /// `remove_vote`. If not equal to the signer, then the vote must have expired, + /// either because the poll was cancelled, because the voter lost the poll or + /// because the conviction period is over. + /// + /// The dispatch origin of this call must be _Signed_. + /// + /// - `target`: The account of the vote to be removed; this account must have voted for poll + /// `index`. + /// - `index`: The index of poll of the vote to be removed. + /// - `class`: The class of the poll. + /// + /// Weight: `O(R + log R)` where R is the number of polls that `target` has voted on. + /// Weight is calculated for the maximum number of vote. + #[pallet::weight(T::WeightInfo::remove_other_vote())] + pub fn remove_other_vote( + origin: OriginFor, + target: T::AccountId, + class: ClassOf, + index: PollIndexOf, + ) -> DispatchResult { + let who = ensure_signed(origin)?; + let scope = if target == who { UnvoteScope::Any } else { UnvoteScope::OnlyExpired }; + Self::try_remove_vote(&target, index, Some(class), scope)?; + Ok(()) + } + } +} + +impl Pallet { + /// Actually enact a vote, if legit. + fn try_vote( + who: &T::AccountId, + poll_index: PollIndexOf, + vote: AccountVote>, + ) -> DispatchResult { + ensure!(vote.balance() <= T::Currency::free_balance(who), Error::::InsufficientFunds); + T::Polls::try_access_poll(poll_index, |poll_status| { + let (tally, class) = poll_status.ensure_ongoing().ok_or(Error::::NotOngoing)?; + VotingFor::::try_mutate(who, &class, |voting| { + if let Voting::Casting(Casting { ref mut votes, delegations, .. }) = voting { + match votes.binary_search_by_key(&poll_index, |i| i.0) { + Ok(i) => { + // Shouldn't be possible to fail, but we handle it gracefully. + tally.remove(votes[i].1).ok_or(ArithmeticError::Underflow)?; + if let Some(approve) = votes[i].1.as_standard() { + tally.reduce(approve, *delegations); + } + votes[i].1 = vote; + }, + Err(i) => { + votes + .try_insert(i, (poll_index, vote)) + .map_err(|()| Error::::MaxVotesReached)?; + }, + } + // Shouldn't be possible to fail, but we handle it gracefully. + tally.add(vote).ok_or(ArithmeticError::Overflow)?; + if let Some(approve) = vote.as_standard() { + tally.increase(approve, *delegations); + } + } else { + return Err(Error::::AlreadyDelegating.into()) + } + // Extend the lock to `balance` (rather than setting it) since we don't know what + // other votes are in place. + Self::extend_lock(who, &class, vote.balance()); + Ok(()) + }) + }) + } + + /// Remove the account's vote for the given poll if possible. This is possible when: + /// - The poll has not finished. + /// - The poll has finished and the voter lost their direction. + /// - The poll has finished and the voter's lock period is up. + /// + /// This will generally be combined with a call to `unlock`. + fn try_remove_vote( + who: &T::AccountId, + poll_index: PollIndexOf, + class_hint: Option>, + scope: UnvoteScope, + ) -> DispatchResult { + let class = class_hint + .or_else(|| Some(T::Polls::as_ongoing(poll_index)?.1)) + .ok_or(Error::::ClassNeeded)?; + VotingFor::::try_mutate(who, class, |voting| { + if let Voting::Casting(Casting { ref mut votes, delegations, ref mut prior }) = voting { + let i = votes + .binary_search_by_key(&poll_index, |i| i.0) + .map_err(|_| Error::::NotVoter)?; + let v = votes.remove(i); + + T::Polls::try_access_poll(poll_index, |poll_status| match poll_status { + PollStatus::Ongoing(tally, _) => { + ensure!(matches!(scope, UnvoteScope::Any), Error::::NoPermission); + // Shouldn't be possible to fail, but we handle it gracefully. + tally.remove(v.1).ok_or(ArithmeticError::Underflow)?; + if let Some(approve) = v.1.as_standard() { + tally.reduce(approve, *delegations); + } + Ok(()) + }, + PollStatus::Completed(end, approved) => { + if let Some((lock_periods, balance)) = v.1.locked_if(approved) { + let unlock_at = end.saturating_add( + T::VoteLockingPeriod::get().saturating_mul(lock_periods.into()), + ); + let now = frame_system::Pallet::::block_number(); + if now < unlock_at { + ensure!( + matches!(scope, UnvoteScope::Any), + Error::::NoPermissionYet + ); + prior.accumulate(unlock_at, balance) + } + } + Ok(()) + }, + PollStatus::None => Ok(()), // Poll was cancelled. + }) + } else { + Ok(()) + } + }) + } + + /// Return the number of votes for `who` + fn increase_upstream_delegation( + who: &T::AccountId, + class: &ClassOf, + amount: Delegations>, + ) -> u32 { + VotingFor::::mutate(who, class, |voting| match voting { + Voting::Delegating(Delegating { delegations, .. }) => { + // We don't support second level delegating, so we don't need to do anything more. + *delegations = delegations.saturating_add(amount); + 1 + }, + Voting::Casting(Casting { votes, delegations, .. }) => { + *delegations = delegations.saturating_add(amount); + for &(poll_index, account_vote) in votes.iter() { + if let AccountVote::Standard { vote, .. } = account_vote { + T::Polls::access_poll(poll_index, |poll_status| { + if let PollStatus::Ongoing(tally, _) = poll_status { + tally.increase(vote.aye, amount); + } + }); + } + } + votes.len() as u32 + }, + }) + } + + /// Return the number of votes for `who` + fn reduce_upstream_delegation( + who: &T::AccountId, + class: &ClassOf, + amount: Delegations>, + ) -> u32 { + VotingFor::::mutate(who, class, |voting| match voting { + Voting::Delegating(Delegating { delegations, .. }) => { + // We don't support second level delegating, so we don't need to do anything more. + *delegations = delegations.saturating_sub(amount); + 1 + }, + Voting::Casting(Casting { votes, delegations, .. }) => { + *delegations = delegations.saturating_sub(amount); + for &(poll_index, account_vote) in votes.iter() { + if let AccountVote::Standard { vote, .. } = account_vote { + T::Polls::access_poll(poll_index, |poll_status| { + if let PollStatus::Ongoing(tally, _) = poll_status { + tally.reduce(vote.aye, amount); + } + }); + } + } + votes.len() as u32 + }, + }) + } + + /// Attempt to delegate `balance` times `conviction` of voting power from `who` to `target`. + /// + /// Return the upstream number of votes. + fn try_delegate( + who: T::AccountId, + class: ClassOf, + target: T::AccountId, + conviction: Conviction, + balance: BalanceOf, + ) -> Result { + ensure!(who != target, Error::::Nonsense); + T::Polls::classes().binary_search(&class).map_err(|_| Error::::BadClass)?; + ensure!(balance <= T::Currency::free_balance(&who), Error::::InsufficientFunds); + let votes = + VotingFor::::try_mutate(&who, &class, |voting| -> Result { + let old = sp_std::mem::replace( + voting, + Voting::Delegating(Delegating { + balance, + target: target.clone(), + conviction, + delegations: Default::default(), + prior: Default::default(), + }), + ); + match old { + Voting::Delegating(Delegating { .. }) => Err(Error::::AlreadyDelegating)?, + Voting::Casting(Casting { votes, delegations, prior }) => { + // here we just ensure that we're currently idling with no votes recorded. + ensure!(votes.is_empty(), Error::::AlreadyVoting); + voting.set_common(delegations, prior); + }, + } + + let votes = + Self::increase_upstream_delegation(&target, &class, conviction.votes(balance)); + // Extend the lock to `balance` (rather than setting it) since we don't know what + // other votes are in place. + Self::extend_lock(&who, &class, balance); + Ok(votes) + })?; + Self::deposit_event(Event::::Delegated(who, target)); + Ok(votes) + } + + /// Attempt to end the current delegation. + /// + /// Return the number of votes of upstream. + fn try_undelegate(who: T::AccountId, class: ClassOf) -> Result { + let votes = + VotingFor::::try_mutate(&who, &class, |voting| -> Result { + match sp_std::mem::replace(voting, Voting::default()) { + Voting::Delegating(Delegating { + balance, + target, + conviction, + delegations, + mut prior, + }) => { + // remove any delegation votes to our current target. + let votes = Self::reduce_upstream_delegation( + &target, + &class, + conviction.votes(balance), + ); + let now = frame_system::Pallet::::block_number(); + let lock_periods = conviction.lock_periods().into(); + prior.accumulate( + now.saturating_add( + T::VoteLockingPeriod::get().saturating_mul(lock_periods), + ), + balance, + ); + voting.set_common(delegations, prior); + + Ok(votes) + }, + Voting::Casting(_) => Err(Error::::NotDelegating.into()), + } + })?; + Self::deposit_event(Event::::Undelegated(who)); + Ok(votes) + } + + fn extend_lock(who: &T::AccountId, class: &ClassOf, amount: BalanceOf) { + ClassLocksFor::::mutate(who, |locks| match locks.iter().position(|x| &x.0 == class) { + Some(i) => locks[i].1 = locks[i].1.max(amount), + None => locks.push((class.clone(), amount)), + }); + T::Currency::extend_lock(CONVICTION_VOTING_ID, who, amount, WithdrawReasons::TRANSFER); + } + + /// Rejig the lock on an account. It will never get more stringent (since that would indicate + /// a security hole) but may be reduced from what they are currently. + fn update_lock(class: &ClassOf, who: &T::AccountId) { + let class_lock_needed = VotingFor::::mutate(who, class, |voting| { + voting.rejig(frame_system::Pallet::::block_number()); + voting.locked_balance() + }); + let lock_needed = ClassLocksFor::::mutate(who, |locks| { + locks.retain(|x| &x.0 != class); + if !class_lock_needed.is_zero() { + locks.push((class.clone(), class_lock_needed)); + } + locks.iter().map(|x| x.1).max().unwrap_or(Zero::zero()) + }); + if lock_needed.is_zero() { + T::Currency::remove_lock(CONVICTION_VOTING_ID, who); + } else { + T::Currency::set_lock( + CONVICTION_VOTING_ID, + who, + lock_needed, + WithdrawReasons::TRANSFER, + ); + } + } +} diff --git a/frame/conviction-voting/src/tests.rs b/frame/conviction-voting/src/tests.rs new file mode 100644 index 0000000000000..cedb23b02a8db --- /dev/null +++ b/frame/conviction-voting/src/tests.rs @@ -0,0 +1,820 @@ +// This file is part of Substrate. + +// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The crate's tests. + +use std::collections::BTreeMap; + +use super::*; +use crate as pallet_conviction_voting; +use frame_support::{ + assert_noop, assert_ok, parameter_types, + traits::{ConstU32, ConstU64, Contains, Polling}, +}; +use sp_core::H256; +use sp_runtime::{ + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, +}; + +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; + +frame_support::construct_runtime!( + pub enum Test where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event}, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, + Voting: pallet_conviction_voting::{Pallet, Call, Storage, Event}, + } +); + +// Test that a fitlered call can be dispatched. +pub struct BaseFilter; +impl Contains for BaseFilter { + fn contains(call: &Call) -> bool { + !matches!(call, &Call::Balances(pallet_balances::Call::set_balance { .. })) + } +} + +parameter_types! { + pub BlockWeights: frame_system::limits::BlockWeights = + frame_system::limits::BlockWeights::simple_max(1_000_000); +} +impl frame_system::Config for Test { + type BaseCallFilter = BaseFilter; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Origin = Origin; + type Index = u64; + type BlockNumber = u64; + type Call = Call; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = u64; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = ConstU64<250>; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = ConstU32<16>; +} + +impl pallet_balances::Config for Test { + type MaxReserves = (); + type ReserveIdentifier = [u8; 8]; + type MaxLocks = ConstU32<10>; + type Balance = u64; + type Event = Event; + type DustRemoval = (); + type ExistentialDeposit = ConstU64<1>; + type AccountStore = System; + type WeightInfo = (); +} + +#[derive(Clone, PartialEq, Eq, Debug)] +pub enum TestPollState { + Ongoing(TallyOf, u8), + Completed(u64, bool), +} +use TestPollState::*; + +parameter_types! { + pub static Polls: BTreeMap = vec![ + (1, Completed(1, true)), + (2, Completed(2, false)), + (3, Ongoing(Tally::from_parts(0, 0, 0), 0)), + ].into_iter().collect(); +} + +pub struct TestPolls; +impl Polling> for TestPolls { + type Index = u8; + type Votes = u64; + type Moment = u64; + type Class = u8; + fn classes() -> Vec { + vec![0, 1, 2] + } + fn as_ongoing(index: u8) -> Option<(TallyOf, Self::Class)> { + Polls::get().remove(&index).and_then(|x| { + if let TestPollState::Ongoing(t, c) = x { + Some((t, c)) + } else { + None + } + }) + } + fn access_poll( + index: Self::Index, + f: impl FnOnce(PollStatus<&mut TallyOf, u64, u8>) -> R, + ) -> R { + let mut polls = Polls::get(); + let entry = polls.get_mut(&index); + let r = match entry { + Some(Ongoing(ref mut tally_mut_ref, class)) => + f(PollStatus::Ongoing(tally_mut_ref, *class)), + Some(Completed(when, succeeded)) => f(PollStatus::Completed(*when, *succeeded)), + None => f(PollStatus::None), + }; + Polls::set(polls); + r + } + fn try_access_poll( + index: Self::Index, + f: impl FnOnce(PollStatus<&mut TallyOf, u64, u8>) -> Result, + ) -> Result { + let mut polls = Polls::get(); + let entry = polls.get_mut(&index); + let r = match entry { + Some(Ongoing(ref mut tally_mut_ref, class)) => + f(PollStatus::Ongoing(tally_mut_ref, *class)), + Some(Completed(when, succeeded)) => f(PollStatus::Completed(*when, *succeeded)), + None => f(PollStatus::None), + }?; + Polls::set(polls); + Ok(r) + } + + #[cfg(feature = "runtime-benchmarks")] + fn create_ongoing(class: Self::Class) -> Result { + let mut polls = Polls::get(); + let i = polls.keys().rev().next().map_or(0, |x| x + 1); + polls.insert(i, Ongoing(Tally::default(), class)); + Polls::set(polls); + Ok(i) + } + + #[cfg(feature = "runtime-benchmarks")] + fn end_ongoing(index: Self::Index, approved: bool) -> Result<(), ()> { + let mut polls = Polls::get(); + match polls.get(&index) { + Some(Ongoing(..)) => {}, + _ => return Err(()), + } + let now = frame_system::Pallet::::block_number(); + polls.insert(index, Completed(now, approved)); + Polls::set(polls); + Ok(()) + } +} + +impl Config for Test { + type Event = Event; + type Currency = pallet_balances::Pallet; + type VoteLockingPeriod = ConstU64<3>; + type MaxVotes = ConstU32<3>; + type WeightInfo = (); + type MaxTurnout = frame_support::traits::TotalIssuanceOf; + type Polls = TestPolls; +} + +pub fn new_test_ext() -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + pallet_balances::GenesisConfig:: { + balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)], + } + .assimilate_storage(&mut t) + .unwrap(); + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext +} + +#[test] +fn params_should_work() { + new_test_ext().execute_with(|| { + assert_eq!(Balances::free_balance(42), 0); + assert_eq!(Balances::total_issuance(), 210); + }); +} + +fn next_block() { + System::set_block_number(System::block_number() + 1); +} + +#[allow(dead_code)] +fn run_to(n: u64) { + while System::block_number() < n { + next_block(); + } +} + +fn aye(amount: u64, conviction: u8) -> AccountVote { + let vote = Vote { aye: true, conviction: conviction.try_into().unwrap() }; + AccountVote::Standard { vote, balance: amount } +} + +fn nay(amount: u64, conviction: u8) -> AccountVote { + let vote = Vote { aye: false, conviction: conviction.try_into().unwrap() }; + AccountVote::Standard { vote, balance: amount } +} + +fn tally(index: u8) -> TallyOf { + >>::as_ongoing(index).expect("No poll").0 +} + +fn class(index: u8) -> u8 { + >>::as_ongoing(index).expect("No poll").1 +} + +#[test] +#[ignore] +#[should_panic(expected = "No poll")] +fn unknown_poll_should_panic() { + let _ = tally(0); +} + +#[test] +#[ignore] +#[should_panic(expected = "No poll")] +fn completed_poll_should_panic() { + let _ = tally(1); +} + +#[test] +fn basic_stuff() { + new_test_ext().execute_with(|| { + assert_eq!(tally(3), Tally::from_parts(0, 0, 0)); + }); +} + +#[test] +fn basic_voting_works() { + new_test_ext().execute_with(|| { + assert_ok!(Voting::vote(Origin::signed(1), 3, aye(2, 5))); + assert_eq!(tally(3), Tally::from_parts(10, 0, 2)); + assert_ok!(Voting::vote(Origin::signed(1), 3, nay(2, 5))); + assert_eq!(tally(3), Tally::from_parts(0, 10, 2)); + assert_eq!(Balances::usable_balance(1), 8); + + assert_ok!(Voting::vote(Origin::signed(1), 3, aye(5, 1))); + assert_eq!(tally(3), Tally::from_parts(5, 0, 5)); + assert_ok!(Voting::vote(Origin::signed(1), 3, nay(5, 1))); + assert_eq!(tally(3), Tally::from_parts(0, 5, 5)); + assert_eq!(Balances::usable_balance(1), 5); + + assert_ok!(Voting::vote(Origin::signed(1), 3, aye(10, 0))); + assert_eq!(tally(3), Tally::from_parts(1, 0, 10)); + assert_ok!(Voting::vote(Origin::signed(1), 3, nay(10, 0))); + assert_eq!(tally(3), Tally::from_parts(0, 1, 10)); + assert_eq!(Balances::usable_balance(1), 0); + + assert_ok!(Voting::remove_vote(Origin::signed(1), None, 3)); + assert_eq!(tally(3), Tally::from_parts(0, 0, 0)); + + assert_ok!(Voting::unlock(Origin::signed(1), class(3), 1)); + assert_eq!(Balances::usable_balance(1), 10); + }); +} + +#[test] +fn voting_balance_gets_locked() { + new_test_ext().execute_with(|| { + assert_ok!(Voting::vote(Origin::signed(1), 3, aye(2, 5))); + assert_eq!(tally(3), Tally::from_parts(10, 0, 2)); + assert_ok!(Voting::vote(Origin::signed(1), 3, nay(2, 5))); + assert_eq!(tally(3), Tally::from_parts(0, 10, 2)); + assert_eq!(Balances::usable_balance(1), 8); + + assert_ok!(Voting::vote(Origin::signed(1), 3, aye(5, 1))); + assert_eq!(tally(3), Tally::from_parts(5, 0, 5)); + assert_ok!(Voting::vote(Origin::signed(1), 3, nay(5, 1))); + assert_eq!(tally(3), Tally::from_parts(0, 5, 5)); + assert_eq!(Balances::usable_balance(1), 5); + + assert_ok!(Voting::vote(Origin::signed(1), 3, aye(10, 0))); + assert_eq!(tally(3), Tally::from_parts(1, 0, 10)); + assert_ok!(Voting::vote(Origin::signed(1), 3, nay(10, 0))); + assert_eq!(tally(3), Tally::from_parts(0, 1, 10)); + assert_eq!(Balances::usable_balance(1), 0); + + assert_ok!(Voting::remove_vote(Origin::signed(1), None, 3)); + assert_eq!(tally(3), Tally::from_parts(0, 0, 0)); + + assert_ok!(Voting::unlock(Origin::signed(1), class(3), 1)); + assert_eq!(Balances::usable_balance(1), 10); + }); +} + +#[test] +fn successful_but_zero_conviction_vote_balance_can_be_unlocked() { + new_test_ext().execute_with(|| { + assert_ok!(Voting::vote(Origin::signed(1), 3, aye(1, 1))); + assert_ok!(Voting::vote(Origin::signed(2), 3, nay(20, 0))); + let c = class(3); + Polls::set(vec![(3, Completed(3, false))].into_iter().collect()); + assert_ok!(Voting::remove_vote(Origin::signed(2), Some(c), 3)); + assert_ok!(Voting::unlock(Origin::signed(2), c, 2)); + assert_eq!(Balances::usable_balance(2), 20); + }); +} + +#[test] +fn unsuccessful_conviction_vote_balance_can_be_unlocked() { + new_test_ext().execute_with(|| { + assert_ok!(Voting::vote(Origin::signed(1), 3, aye(1, 1))); + assert_ok!(Voting::vote(Origin::signed(2), 3, nay(20, 0))); + let c = class(3); + Polls::set(vec![(3, Completed(3, false))].into_iter().collect()); + assert_ok!(Voting::remove_vote(Origin::signed(1), Some(c), 3)); + assert_ok!(Voting::unlock(Origin::signed(1), c, 1)); + assert_eq!(Balances::usable_balance(1), 10); + }); +} + +#[test] +fn successful_conviction_vote_balance_stays_locked_for_correct_time() { + new_test_ext().execute_with(|| { + for i in 1..=5 { + assert_ok!(Voting::vote(Origin::signed(i), 3, aye(10, i as u8))); + } + let c = class(3); + Polls::set(vec![(3, Completed(3, true))].into_iter().collect()); + for i in 1..=5 { + assert_ok!(Voting::remove_vote(Origin::signed(i), Some(c), 3)); + } + for block in 1..=(3 + 5 * 3) { + run_to(block); + for i in 1..=5 { + assert_ok!(Voting::unlock(Origin::signed(i), c, i)); + let expired = block >= (3 << (i - 1)) + 3; + assert_eq!(Balances::usable_balance(i), i * 10 - if expired { 0 } else { 10 }); + } + } + }); +} + +#[test] +fn classwise_delegation_works() { + new_test_ext().execute_with(|| { + Polls::set( + vec![ + (0, Ongoing(Tally::default(), 0)), + (1, Ongoing(Tally::default(), 1)), + (2, Ongoing(Tally::default(), 2)), + (3, Ongoing(Tally::default(), 2)), + ] + .into_iter() + .collect(), + ); + assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 5)); + assert_ok!(Voting::delegate(Origin::signed(1), 1, 3, Conviction::Locked1x, 5)); + assert_ok!(Voting::delegate(Origin::signed(1), 2, 4, Conviction::Locked1x, 5)); + assert_eq!(Balances::usable_balance(1), 5); + + assert_ok!(Voting::vote(Origin::signed(2), 0, aye(10, 0))); + assert_ok!(Voting::vote(Origin::signed(2), 1, nay(10, 0))); + assert_ok!(Voting::vote(Origin::signed(2), 2, nay(10, 0))); + assert_ok!(Voting::vote(Origin::signed(3), 0, nay(10, 0))); + assert_ok!(Voting::vote(Origin::signed(3), 1, aye(10, 0))); + assert_ok!(Voting::vote(Origin::signed(3), 2, nay(10, 0))); + assert_ok!(Voting::vote(Origin::signed(4), 0, nay(10, 0))); + assert_ok!(Voting::vote(Origin::signed(4), 1, nay(10, 0))); + assert_ok!(Voting::vote(Origin::signed(4), 2, aye(10, 0))); + // 4 hasn't voted yet + + assert_eq!( + Polls::get(), + vec![ + (0, Ongoing(Tally::from_parts(6, 2, 35), 0)), + (1, Ongoing(Tally::from_parts(6, 2, 35), 1)), + (2, Ongoing(Tally::from_parts(6, 2, 35), 2)), + (3, Ongoing(Tally::from_parts(0, 0, 0), 2)), + ] + .into_iter() + .collect() + ); + + // 4 votes nay to 3. + assert_ok!(Voting::vote(Origin::signed(4), 3, nay(10, 0))); + assert_eq!( + Polls::get(), + vec![ + (0, Ongoing(Tally::from_parts(6, 2, 35), 0)), + (1, Ongoing(Tally::from_parts(6, 2, 35), 1)), + (2, Ongoing(Tally::from_parts(6, 2, 35), 2)), + (3, Ongoing(Tally::from_parts(0, 6, 15), 2)), + ] + .into_iter() + .collect() + ); + + // Redelegate for class 2 to account 3. + assert_ok!(Voting::undelegate(Origin::signed(1), 2)); + assert_ok!(Voting::delegate(Origin::signed(1), 2, 3, Conviction::Locked1x, 5)); + assert_eq!( + Polls::get(), + vec![ + (0, Ongoing(Tally::from_parts(6, 2, 35), 0)), + (1, Ongoing(Tally::from_parts(6, 2, 35), 1)), + (2, Ongoing(Tally::from_parts(1, 7, 35), 2)), + (3, Ongoing(Tally::from_parts(0, 1, 10), 2)), + ] + .into_iter() + .collect() + ); + + // Redelegating with a lower lock does not forget previous lock and updates correctly. + assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + assert_ok!(Voting::undelegate(Origin::signed(1), 1)); + assert_ok!(Voting::undelegate(Origin::signed(1), 2)); + assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 3)); + assert_ok!(Voting::delegate(Origin::signed(1), 1, 3, Conviction::Locked1x, 3)); + assert_ok!(Voting::delegate(Origin::signed(1), 2, 4, Conviction::Locked1x, 3)); + assert_eq!( + Polls::get(), + vec![ + (0, Ongoing(Tally::from_parts(4, 2, 33), 0)), + (1, Ongoing(Tally::from_parts(4, 2, 33), 1)), + (2, Ongoing(Tally::from_parts(4, 2, 33), 2)), + (3, Ongoing(Tally::from_parts(0, 4, 13), 2)), + ] + .into_iter() + .collect() + ); + assert_eq!(Balances::usable_balance(1), 5); + + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + // unlock does nothing since the delegation already took place. + assert_eq!(Balances::usable_balance(1), 5); + + // Redelegating with higher amount extends previous lock. + assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 6)); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 4); + assert_ok!(Voting::undelegate(Origin::signed(1), 1)); + assert_ok!(Voting::delegate(Origin::signed(1), 1, 3, Conviction::Locked1x, 7)); + assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); + assert_eq!(Balances::usable_balance(1), 3); + assert_ok!(Voting::undelegate(Origin::signed(1), 2)); + assert_ok!(Voting::delegate(Origin::signed(1), 2, 4, Conviction::Locked1x, 8)); + assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_eq!(Balances::usable_balance(1), 2); + assert_eq!( + Polls::get(), + vec![ + (0, Ongoing(Tally::from_parts(7, 2, 36), 0)), + (1, Ongoing(Tally::from_parts(8, 2, 37), 1)), + (2, Ongoing(Tally::from_parts(9, 2, 38), 2)), + (3, Ongoing(Tally::from_parts(0, 9, 18), 2)), + ] + .into_iter() + .collect() + ); + }); +} + +#[test] +fn redelegation_after_vote_ending_should_keep_lock() { + new_test_ext().execute_with(|| { + Polls::set(vec![(0, Ongoing(Tally::default(), 0))].into_iter().collect()); + assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 5)); + assert_ok!(Voting::vote(Origin::signed(2), 0, aye(10, 1))); + Polls::set(vec![(0, Completed(1, true))].into_iter().collect()); + assert_eq!(Balances::usable_balance(1), 5); + assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + assert_ok!(Voting::delegate(Origin::signed(1), 0, 3, Conviction::Locked1x, 3)); + assert_eq!(Balances::usable_balance(1), 5); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 5); + }); +} + +#[test] +fn lock_amalgamation_valid_with_multiple_removed_votes() { + new_test_ext().execute_with(|| { + Polls::set( + vec![ + (0, Ongoing(Tally::default(), 0)), + (1, Ongoing(Tally::default(), 0)), + (2, Ongoing(Tally::default(), 0)), + ] + .into_iter() + .collect(), + ); + assert_ok!(Voting::vote(Origin::signed(1), 0, aye(5, 1))); + assert_ok!(Voting::vote(Origin::signed(1), 1, aye(10, 1))); + assert_ok!(Voting::vote(Origin::signed(1), 2, aye(5, 2))); + assert_eq!(Balances::usable_balance(1), 0); + + Polls::set( + vec![(0, Completed(1, true)), (1, Completed(1, true)), (2, Completed(1, true))] + .into_iter() + .collect(), + ); + assert_ok!(Voting::remove_vote(Origin::signed(1), Some(0), 0)); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 0); + + assert_ok!(Voting::remove_vote(Origin::signed(1), Some(0), 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 0); + + assert_ok!(Voting::remove_vote(Origin::signed(1), Some(0), 2)); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 0); + + run_to(3); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 0); + + run_to(6); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert!(Balances::usable_balance(1) <= 5); + + run_to(7); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 10); + }); +} + +#[test] +fn lock_amalgamation_valid_with_multiple_delegations() { + new_test_ext().execute_with(|| { + assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 5)); + assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 10)); + assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked2x, 5)); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 0); + assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + + run_to(3); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 0); + + run_to(6); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert!(Balances::usable_balance(1) <= 5); + + run_to(7); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 10); + }); +} + +#[test] +fn lock_amalgamation_valid_with_move_roundtrip_to_delegation() { + new_test_ext().execute_with(|| { + Polls::set(vec![(0, Ongoing(Tally::default(), 0))].into_iter().collect()); + assert_ok!(Voting::vote(Origin::signed(1), 0, aye(5, 1))); + Polls::set(vec![(0, Completed(1, true))].into_iter().collect()); + assert_ok!(Voting::remove_vote(Origin::signed(1), Some(0), 0)); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 5); + + assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 10)); + assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 0); + + Polls::set(vec![(1, Ongoing(Tally::default(), 0))].into_iter().collect()); + assert_ok!(Voting::vote(Origin::signed(1), 1, aye(5, 2))); + Polls::set(vec![(1, Completed(1, true))].into_iter().collect()); + assert_ok!(Voting::remove_vote(Origin::signed(1), Some(0), 1)); + + run_to(3); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 0); + + run_to(6); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert!(Balances::usable_balance(1) <= 5); + + run_to(7); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 10); + }); +} + +#[test] +fn lock_amalgamation_valid_with_move_roundtrip_to_casting() { + new_test_ext().execute_with(|| { + assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 5)); + assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 5); + + Polls::set(vec![(0, Ongoing(Tally::default(), 0))].into_iter().collect()); + assert_ok!(Voting::vote(Origin::signed(1), 0, aye(10, 1))); + Polls::set(vec![(0, Completed(1, true))].into_iter().collect()); + assert_ok!(Voting::remove_vote(Origin::signed(1), Some(0), 0)); + + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 0); + + assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked2x, 10)); + assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + + run_to(3); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 0); + + run_to(6); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert!(Balances::usable_balance(1) <= 5); + + run_to(7); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_eq!(Balances::usable_balance(1), 10); + }); +} + +#[test] +fn lock_aggregation_over_different_classes_with_delegation_works() { + new_test_ext().execute_with(|| { + assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::Locked1x, 5)); + assert_ok!(Voting::delegate(Origin::signed(1), 1, 2, Conviction::Locked2x, 5)); + assert_ok!(Voting::delegate(Origin::signed(1), 2, 2, Conviction::Locked1x, 10)); + + assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + assert_ok!(Voting::undelegate(Origin::signed(1), 1)); + assert_ok!(Voting::undelegate(Origin::signed(1), 2)); + + run_to(3); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_eq!(Balances::usable_balance(1), 0); + + run_to(6); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_eq!(Balances::usable_balance(1), 5); + + run_to(7); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_eq!(Balances::usable_balance(1), 10); + }); +} + +#[test] +fn lock_aggregation_over_different_classes_with_casting_works() { + new_test_ext().execute_with(|| { + Polls::set( + vec![ + (0, Ongoing(Tally::default(), 0)), + (1, Ongoing(Tally::default(), 1)), + (2, Ongoing(Tally::default(), 2)), + ] + .into_iter() + .collect(), + ); + assert_ok!(Voting::vote(Origin::signed(1), 0, aye(5, 1))); + assert_ok!(Voting::vote(Origin::signed(1), 1, aye(10, 1))); + assert_ok!(Voting::vote(Origin::signed(1), 2, aye(5, 2))); + Polls::set( + vec![(0, Completed(1, true)), (1, Completed(1, true)), (2, Completed(1, true))] + .into_iter() + .collect(), + ); + assert_ok!(Voting::remove_vote(Origin::signed(1), Some(0), 0)); + assert_ok!(Voting::remove_vote(Origin::signed(1), Some(1), 1)); + assert_ok!(Voting::remove_vote(Origin::signed(1), Some(2), 2)); + + run_to(3); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_eq!(Balances::usable_balance(1), 0); + + run_to(6); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_eq!(Balances::usable_balance(1), 5); + + run_to(7); + assert_ok!(Voting::unlock(Origin::signed(1), 0, 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 1, 1)); + assert_ok!(Voting::unlock(Origin::signed(1), 2, 1)); + assert_eq!(Balances::usable_balance(1), 10); + }); +} + +#[test] +fn errors_with_vote_work() { + new_test_ext().execute_with(|| { + assert_noop!(Voting::vote(Origin::signed(1), 0, aye(10, 0)), Error::::NotOngoing); + assert_noop!(Voting::vote(Origin::signed(1), 1, aye(10, 0)), Error::::NotOngoing); + assert_noop!(Voting::vote(Origin::signed(1), 2, aye(10, 0)), Error::::NotOngoing); + assert_noop!( + Voting::vote(Origin::signed(1), 3, aye(11, 0)), + Error::::InsufficientFunds + ); + + assert_ok!(Voting::delegate(Origin::signed(1), 0, 2, Conviction::None, 10)); + assert_noop!( + Voting::vote(Origin::signed(1), 3, aye(10, 0)), + Error::::AlreadyDelegating + ); + + assert_ok!(Voting::undelegate(Origin::signed(1), 0)); + Polls::set( + vec![ + (0, Ongoing(Tally::default(), 0)), + (1, Ongoing(Tally::default(), 0)), + (2, Ongoing(Tally::default(), 0)), + (3, Ongoing(Tally::default(), 0)), + ] + .into_iter() + .collect(), + ); + assert_ok!(Voting::vote(Origin::signed(1), 0, aye(10, 0))); + assert_ok!(Voting::vote(Origin::signed(1), 1, aye(10, 0))); + assert_ok!(Voting::vote(Origin::signed(1), 2, aye(10, 0))); + assert_noop!( + Voting::vote(Origin::signed(1), 3, aye(10, 0)), + Error::::MaxVotesReached + ); + }); +} + +#[test] +fn errors_with_delegating_work() { + new_test_ext().execute_with(|| { + assert_noop!( + Voting::delegate(Origin::signed(1), 0, 2, Conviction::None, 11), + Error::::InsufficientFunds + ); + assert_noop!( + Voting::delegate(Origin::signed(1), 3, 2, Conviction::None, 10), + Error::::BadClass + ); + + assert_ok!(Voting::vote(Origin::signed(1), 3, aye(10, 0))); + assert_noop!( + Voting::delegate(Origin::signed(1), 0, 2, Conviction::None, 10), + Error::::AlreadyVoting + ); + + assert_noop!(Voting::undelegate(Origin::signed(1), 0), Error::::NotDelegating); + }); +} + +#[test] +fn remove_other_vote_works() { + new_test_ext().execute_with(|| { + assert_noop!( + Voting::remove_other_vote(Origin::signed(2), 1, 0, 3), + Error::::NotVoter + ); + assert_ok!(Voting::vote(Origin::signed(1), 3, aye(10, 2))); + assert_noop!( + Voting::remove_other_vote(Origin::signed(2), 1, 0, 3), + Error::::NoPermission + ); + Polls::set(vec![(3, Completed(1, true))].into_iter().collect()); + run_to(6); + assert_noop!( + Voting::remove_other_vote(Origin::signed(2), 1, 0, 3), + Error::::NoPermissionYet + ); + run_to(7); + assert_ok!(Voting::remove_other_vote(Origin::signed(2), 1, 0, 3)); + }); +} + +#[test] +fn errors_with_remove_vote_work() { + new_test_ext().execute_with(|| { + assert_noop!(Voting::remove_vote(Origin::signed(1), Some(0), 3), Error::::NotVoter); + assert_ok!(Voting::vote(Origin::signed(1), 3, aye(10, 2))); + Polls::set(vec![(3, Completed(1, true))].into_iter().collect()); + assert_noop!(Voting::remove_vote(Origin::signed(1), None, 3), Error::::ClassNeeded); + }); +} diff --git a/frame/conviction-voting/src/types.rs b/frame/conviction-voting/src/types.rs new file mode 100644 index 0000000000000..2ad1a164dd143 --- /dev/null +++ b/frame/conviction-voting/src/types.rs @@ -0,0 +1,236 @@ +// This file is part of Substrate. + +// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Miscellaneous additional datatypes. + +use sp_std::marker::PhantomData; + +use super::*; +use crate::{AccountVote, Conviction, Vote}; +use codec::{Codec, Decode, Encode, MaxEncodedLen}; +use frame_support::{ + traits::VoteTally, CloneNoBound, DefaultNoBound, EqNoBound, PartialEqNoBound, + RuntimeDebugNoBound, +}; +use scale_info::TypeInfo; +use sp_runtime::{ + traits::{Saturating, Zero}, + RuntimeDebug, +}; + +/// Info regarding an ongoing referendum. +#[derive( + CloneNoBound, + DefaultNoBound, + PartialEqNoBound, + EqNoBound, + RuntimeDebugNoBound, + TypeInfo, + Encode, + Decode, + MaxEncodedLen, +)] +#[scale_info(skip_type_params(Total))] +pub struct Tally< + Votes: Clone + Default + PartialEq + Eq + sp_std::fmt::Debug + TypeInfo + Codec, + Total, +> { + /// The number of aye votes, expressed in terms of post-conviction lock-vote. + pub ayes: Votes, + /// The number of nay votes, expressed in terms of post-conviction lock-vote. + pub nays: Votes, + /// The amount of funds currently expressing its opinion. Pre-conviction. + pub turnout: Votes, + /// Dummy. + dummy: PhantomData, +} + +impl< + Votes: Clone + + Default + + PartialEq + + Eq + + sp_std::fmt::Debug + + Copy + + AtLeast32BitUnsigned + + TypeInfo + + Codec, + Total: Get, + > VoteTally for Tally +{ + fn ayes(&self) -> Votes { + self.ayes + } + + fn turnout(&self) -> Perbill { + Perbill::from_rational(self.turnout, Total::get()) + } + + fn approval(&self) -> Perbill { + Perbill::from_rational(self.ayes, self.ayes.saturating_add(self.nays)) + } + + #[cfg(feature = "runtime-benchmarks")] + fn unanimity() -> Self { + Self { ayes: Total::get(), nays: Zero::zero(), turnout: Total::get(), dummy: PhantomData } + } + + #[cfg(feature = "runtime-benchmarks")] + fn from_requirements(turnout: Perbill, approval: Perbill) -> Self { + let turnout = turnout.mul_ceil(Total::get()); + let ayes = approval.mul_ceil(turnout); + Self { ayes, nays: turnout - ayes, turnout, dummy: PhantomData } + } +} + +impl< + Votes: Clone + + Default + + PartialEq + + Eq + + sp_std::fmt::Debug + + Copy + + AtLeast32BitUnsigned + + TypeInfo + + Codec, + Total: Get, + > Tally +{ + /// Create a new tally. + pub fn new(vote: Vote, balance: Votes) -> Self { + let Delegations { votes, capital } = vote.conviction.votes(balance); + Self { + ayes: if vote.aye { votes } else { Zero::zero() }, + nays: if vote.aye { Zero::zero() } else { votes }, + turnout: capital, + dummy: PhantomData, + } + } + + pub fn from_parts(ayes: Votes, nays: Votes, turnout: Votes) -> Self { + Self { ayes, nays, turnout, dummy: PhantomData } + } + + /// Add an account's vote into the tally. + pub fn add(&mut self, vote: AccountVote) -> Option<()> { + match vote { + AccountVote::Standard { vote, balance } => { + let Delegations { votes, capital } = vote.conviction.votes(balance); + self.turnout = self.turnout.checked_add(&capital)?; + match vote.aye { + true => self.ayes = self.ayes.checked_add(&votes)?, + false => self.nays = self.nays.checked_add(&votes)?, + } + }, + AccountVote::Split { aye, nay } => { + let aye = Conviction::None.votes(aye); + let nay = Conviction::None.votes(nay); + self.turnout = self.turnout.checked_add(&aye.capital)?.checked_add(&nay.capital)?; + self.ayes = self.ayes.checked_add(&aye.votes)?; + self.nays = self.nays.checked_add(&nay.votes)?; + }, + } + Some(()) + } + + /// Remove an account's vote from the tally. + pub fn remove(&mut self, vote: AccountVote) -> Option<()> { + match vote { + AccountVote::Standard { vote, balance } => { + let Delegations { votes, capital } = vote.conviction.votes(balance); + self.turnout = self.turnout.checked_sub(&capital)?; + match vote.aye { + true => self.ayes = self.ayes.checked_sub(&votes)?, + false => self.nays = self.nays.checked_sub(&votes)?, + } + }, + AccountVote::Split { aye, nay } => { + let aye = Conviction::None.votes(aye); + let nay = Conviction::None.votes(nay); + self.turnout = self.turnout.checked_sub(&aye.capital)?.checked_sub(&nay.capital)?; + self.ayes = self.ayes.checked_sub(&aye.votes)?; + self.nays = self.nays.checked_sub(&nay.votes)?; + }, + } + Some(()) + } + + /// Increment some amount of votes. + pub fn increase(&mut self, approve: bool, delegations: Delegations) { + self.turnout = self.turnout.saturating_add(delegations.capital); + match approve { + true => self.ayes = self.ayes.saturating_add(delegations.votes), + false => self.nays = self.nays.saturating_add(delegations.votes), + } + } + + /// Decrement some amount of votes. + pub fn reduce(&mut self, approve: bool, delegations: Delegations) { + self.turnout = self.turnout.saturating_sub(delegations.capital); + match approve { + true => self.ayes = self.ayes.saturating_sub(delegations.votes), + false => self.nays = self.nays.saturating_sub(delegations.votes), + } + } +} + +/// Amount of votes and capital placed in delegation for an account. +#[derive( + Encode, Decode, Default, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen, +)] +pub struct Delegations { + /// The number of votes (this is post-conviction). + pub votes: Balance, + /// The amount of raw capital, used for the turnout. + pub capital: Balance, +} + +impl Saturating for Delegations { + fn saturating_add(self, o: Self) -> Self { + Self { + votes: self.votes.saturating_add(o.votes), + capital: self.capital.saturating_add(o.capital), + } + } + + fn saturating_sub(self, o: Self) -> Self { + Self { + votes: self.votes.saturating_sub(o.votes), + capital: self.capital.saturating_sub(o.capital), + } + } + + fn saturating_mul(self, o: Self) -> Self { + Self { + votes: self.votes.saturating_mul(o.votes), + capital: self.capital.saturating_mul(o.capital), + } + } + + fn saturating_pow(self, exp: usize) -> Self { + Self { votes: self.votes.saturating_pow(exp), capital: self.capital.saturating_pow(exp) } + } +} + +/// Whether an `unvote` operation is able to make actions that are not strictly always in the +/// interest of an account. +pub enum UnvoteScope { + /// Permitted to do everything. + Any, + /// Permitted to do only the changes that do not need the owner's permission. + OnlyExpired, +} diff --git a/frame/conviction-voting/src/vote.rs b/frame/conviction-voting/src/vote.rs new file mode 100644 index 0000000000000..d7ca931de35a1 --- /dev/null +++ b/frame/conviction-voting/src/vote.rs @@ -0,0 +1,254 @@ +// This file is part of Substrate. + +// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The vote datatype. + +use crate::{Conviction, Delegations}; +use codec::{Decode, Encode, EncodeLike, Input, MaxEncodedLen, Output}; +use frame_support::{pallet_prelude::Get, BoundedVec}; +use scale_info::TypeInfo; +use sp_runtime::{ + traits::{Saturating, Zero}, + RuntimeDebug, +}; +use sp_std::{convert::TryFrom, prelude::*, result::Result}; + +/// A number of lock periods, plus a vote, one way or the other. +#[derive(Copy, Clone, Eq, PartialEq, Default, RuntimeDebug, MaxEncodedLen)] +pub struct Vote { + pub aye: bool, + pub conviction: Conviction, +} + +impl Encode for Vote { + fn encode_to(&self, output: &mut T) { + output.push_byte(u8::from(self.conviction) | if self.aye { 0b1000_0000 } else { 0 }); + } +} + +impl EncodeLike for Vote {} + +impl Decode for Vote { + fn decode(input: &mut I) -> Result { + let b = input.read_byte()?; + Ok(Vote { + aye: (b & 0b1000_0000) == 0b1000_0000, + conviction: Conviction::try_from(b & 0b0111_1111) + .map_err(|_| codec::Error::from("Invalid conviction"))?, + }) + } +} + +impl TypeInfo for Vote { + type Identity = Self; + + fn type_info() -> scale_info::Type { + scale_info::Type::builder() + .path(scale_info::Path::new("Vote", module_path!())) + .composite( + scale_info::build::Fields::unnamed() + .field(|f| f.ty::().docs(&["Raw vote byte, encodes aye + conviction"])), + ) + } +} + +/// A vote for a referendum of a particular account. +#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub enum AccountVote { + /// A standard vote, one-way (approve or reject) with a given amount of conviction. + Standard { vote: Vote, balance: Balance }, + /// A split vote with balances given for both ways, and with no conviction, useful for + /// parachains when voting. + Split { aye: Balance, nay: Balance }, +} + +impl AccountVote { + /// Returns `Some` of the lock periods that the account is locked for, assuming that the + /// referendum passed iff `approved` is `true`. + pub fn locked_if(self, approved: bool) -> Option<(u32, Balance)> { + // winning side: can only be removed after the lock period ends. + match self { + AccountVote::Standard { vote: Vote { conviction: Conviction::None, .. }, .. } => None, + AccountVote::Standard { vote, balance } if vote.aye == approved => + Some((vote.conviction.lock_periods(), balance)), + _ => None, + } + } + + /// The total balance involved in this vote. + pub fn balance(self) -> Balance { + match self { + AccountVote::Standard { balance, .. } => balance, + AccountVote::Split { aye, nay } => aye.saturating_add(nay), + } + } + + /// Returns `Some` with whether the vote is an aye vote if it is standard, otherwise `None` if + /// it is split. + pub fn as_standard(self) -> Option { + match self { + AccountVote::Standard { vote, .. } => Some(vote.aye), + _ => None, + } + } +} + +/// A "prior" lock, i.e. a lock for some now-forgotten reason. +#[derive( + Encode, + Decode, + Default, + Copy, + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + RuntimeDebug, + TypeInfo, + MaxEncodedLen, +)] +pub struct PriorLock(BlockNumber, Balance); + +impl PriorLock { + /// Accumulates an additional lock. + pub fn accumulate(&mut self, until: BlockNumber, amount: Balance) { + self.0 = self.0.max(until); + self.1 = self.1.max(amount); + } + + pub fn locked(&self) -> Balance { + self.1 + } + + pub fn rejig(&mut self, now: BlockNumber) { + if now >= self.0 { + self.0 = Zero::zero(); + self.1 = Zero::zero(); + } + } +} + +/// Information concerning the delegation of some voting power. +#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct Delegating { + /// The amount of balance delegated. + pub balance: Balance, + /// The account to which the voting power is delegated. + pub target: AccountId, + /// The conviction with which the voting power is delegated. When this gets undelegated, the + /// relevant lock begins. + pub conviction: Conviction, + /// The total amount of delegations that this account has received, post-conviction-weighting. + pub delegations: Delegations, + /// Any pre-existing locks from past voting/delegating activity. + pub prior: PriorLock, +} + +/// Information concerning the direct vote-casting of some voting power. +#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +#[scale_info(skip_type_params(MaxVotes))] +pub struct Casting +where + MaxVotes: Get, +{ + /// The current votes of the account. + pub votes: BoundedVec<(PollIndex, AccountVote), MaxVotes>, + /// The total amount of delegations that this account has received, post-conviction-weighting. + pub delegations: Delegations, + /// Any pre-existing locks from past voting/delegating activity. + pub prior: PriorLock, +} + +/// An indicator for what an account is doing; it can either be delegating or voting. +#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +#[scale_info(skip_type_params(MaxVotes))] +pub enum Voting +where + MaxVotes: Get, +{ + /// The account is voting directly. + Casting(Casting), + /// The account is delegating `balance` of its balance to a `target` account with `conviction`. + Delegating(Delegating), +} + +impl Default + for Voting +where + MaxVotes: Get, +{ + fn default() -> Self { + Voting::Casting(Casting { + votes: Default::default(), + delegations: Default::default(), + prior: PriorLock(Zero::zero(), Default::default()), + }) + } +} + +impl AsMut> + for Voting +where + MaxVotes: Get, +{ + fn as_mut(&mut self) -> &mut PriorLock { + match self { + Voting::Casting(Casting { prior, .. }) => prior, + Voting::Delegating(Delegating { prior, .. }) => prior, + } + } +} + +impl< + Balance: Saturating + Ord + Zero + Copy, + BlockNumber: Ord + Copy + Zero, + AccountId, + PollIndex, + MaxVotes, + > Voting +where + MaxVotes: Get, +{ + pub fn rejig(&mut self, now: BlockNumber) { + AsMut::>::as_mut(self).rejig(now); + } + + /// The amount of this account's balance that much currently be locked due to voting. + pub fn locked_balance(&self) -> Balance { + match self { + Voting::Casting(Casting { votes, prior, .. }) => + votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i)), + Voting::Delegating(Delegating { balance, prior, .. }) => *balance.max(&prior.locked()), + } + } + + pub fn set_common( + &mut self, + delegations: Delegations, + prior: PriorLock, + ) { + let (d, p) = match self { + Voting::Casting(Casting { ref mut delegations, ref mut prior, .. }) => + (delegations, prior), + Voting::Delegating(Delegating { ref mut delegations, ref mut prior, .. }) => + (delegations, prior), + }; + *d = delegations; + *p = prior; + } +} diff --git a/frame/conviction-voting/src/weights.rs b/frame/conviction-voting/src/weights.rs new file mode 100644 index 0000000000000..da15aac0b47ca --- /dev/null +++ b/frame/conviction-voting/src/weights.rs @@ -0,0 +1,201 @@ +// This file is part of Substrate. + +// Copyright (C) 2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Autogenerated weights for pallet_conviction_voting +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2022-01-09, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 + +// Executed Command: +// target/release/substrate +// benchmark +// --chain=dev +// --steps=50 +// --repeat=20 +// --pallet=pallet_conviction_voting +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --output=./frame/conviction-voting/src/weights.rs +// --template=./.maintain/frame-weight-template.hbs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use sp_std::marker::PhantomData; + +/// Weight functions needed for pallet_conviction_voting. +pub trait WeightInfo { + fn vote_new() -> Weight; + fn vote_existing() -> Weight; + fn remove_vote() -> Weight; + fn remove_other_vote() -> Weight; + fn delegate(r: u32, ) -> Weight; + fn undelegate(r: u32, ) -> Weight; + fn unlock() -> Weight; +} + +/// Weights for pallet_conviction_voting using the Substrate node and recommended hardware. +pub struct SubstrateWeight(PhantomData); +impl WeightInfo for SubstrateWeight { + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: ConvictionVoting VotingFor (r:1 w:1) + // Storage: ConvictionVoting ClassLocksFor (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn vote_new() -> Weight { + (159_647_000 as Weight) + .saturating_add(T::DbWeight::get().reads(6 as Weight)) + .saturating_add(T::DbWeight::get().writes(6 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: ConvictionVoting VotingFor (r:1 w:1) + // Storage: ConvictionVoting ClassLocksFor (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn vote_existing() -> Weight { + (339_851_000 as Weight) + .saturating_add(T::DbWeight::get().reads(6 as Weight)) + .saturating_add(T::DbWeight::get().writes(6 as Weight)) + } + // Storage: ConvictionVoting VotingFor (r:1 w:1) + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn remove_vote() -> Weight { + (317_673_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: ConvictionVoting VotingFor (r:1 w:1) + // Storage: Referenda ReferendumInfoFor (r:1 w:0) + fn remove_other_vote() -> Weight { + (52_222_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: ConvictionVoting VotingFor (r:2 w:2) + // Storage: ConvictionVoting ClassLocksFor (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn delegate(r: u32, ) -> Weight { + (61_553_000 as Weight) + // Standard Error: 123_000 + .saturating_add((33_092_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(r as Weight))) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(r as Weight))) + } + // Storage: ConvictionVoting VotingFor (r:2 w:2) + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn undelegate(r: u32, ) -> Weight { + (42_037_000 as Weight) + // Standard Error: 582_000 + .saturating_add((32_296_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(r as Weight))) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(r as Weight))) + } + // Storage: ConvictionVoting VotingFor (r:1 w:1) + // Storage: ConvictionVoting ClassLocksFor (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + fn unlock() -> Weight { + (69_017_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } +} + +// For backwards compatibility and tests +impl WeightInfo for () { + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: ConvictionVoting VotingFor (r:1 w:1) + // Storage: ConvictionVoting ClassLocksFor (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn vote_new() -> Weight { + (159_647_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(6 as Weight)) + .saturating_add(RocksDbWeight::get().writes(6 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: ConvictionVoting VotingFor (r:1 w:1) + // Storage: ConvictionVoting ClassLocksFor (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn vote_existing() -> Weight { + (339_851_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(6 as Weight)) + .saturating_add(RocksDbWeight::get().writes(6 as Weight)) + } + // Storage: ConvictionVoting VotingFor (r:1 w:1) + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn remove_vote() -> Weight { + (317_673_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: ConvictionVoting VotingFor (r:1 w:1) + // Storage: Referenda ReferendumInfoFor (r:1 w:0) + fn remove_other_vote() -> Weight { + (52_222_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: ConvictionVoting VotingFor (r:2 w:2) + // Storage: ConvictionVoting ClassLocksFor (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn delegate(r: u32, ) -> Weight { + (61_553_000 as Weight) + // Standard Error: 123_000 + .saturating_add((33_092_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(r as Weight))) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(r as Weight))) + } + // Storage: ConvictionVoting VotingFor (r:2 w:2) + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn undelegate(r: u32, ) -> Weight { + (42_037_000 as Weight) + // Standard Error: 582_000 + .saturating_add((32_296_000 as Weight).saturating_mul(r as Weight)) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(r as Weight))) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(r as Weight))) + } + // Storage: ConvictionVoting VotingFor (r:1 w:1) + // Storage: ConvictionVoting ClassLocksFor (r:1 w:1) + // Storage: Balances Locks (r:1 w:1) + fn unlock() -> Weight { + (69_017_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } +} diff --git a/frame/democracy/Cargo.toml b/frame/democracy/Cargo.toml index 730bc6fffbdf4..743cea074ee26 100644 --- a/frame/democracy/Cargo.toml +++ b/frame/democracy/Cargo.toml @@ -13,20 +13,20 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -serde = { version = "1.0.132", optional = true, features = ["derive"] } +serde = { version = "1.0.136", optional = true, features = ["derive"] } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [ "derive", ] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } pallet-scheduler = { version = "4.0.0-dev", path = "../scheduler" } diff --git a/frame/democracy/src/lib.rs b/frame/democracy/src/lib.rs index 3395b96016bcf..8588f1876d7e3 100644 --- a/frame/democracy/src/lib.rs +++ b/frame/democracy/src/lib.rs @@ -156,6 +156,7 @@ use codec::{Decode, Encode, Input}; use frame_support::{ ensure, traits::{ + defensive_prelude::*, schedule::{DispatchTime, Named as ScheduleNamed}, BalanceStatus, Currency, Get, LockIdentifier, LockableCurrency, OnUnbalanced, ReservableCurrency, WithdrawReasons, @@ -438,14 +439,6 @@ pub mod pallet { ValueQuery, >; - /// Accounts for which there are locks in action which may be removed at some point in the - /// future. The value is the block number at which the lock expires and may be removed. - /// - /// TWOX-NOTE: OK ― `AccountId` is a secure hash. - #[pallet::storage] - #[pallet::getter(fn locks)] - pub type Locks = StorageMap<_, Twox64Concat, T::AccountId, T::BlockNumber>; - /// True if the last referendum tabled was submitted externally. False if it was a public /// proposal. // TODO: There should be any number of tabling origins, not just public and "external" @@ -1650,7 +1643,7 @@ impl Pallet { let mut public_props = Self::public_props(); if let Some((winner_index, _)) = public_props.iter().enumerate().max_by_key( // defensive only: All current public proposals have an amount locked - |x| Self::backing_for((x.1).0).unwrap_or_else(Zero::zero), + |x| Self::backing_for((x.1).0).defensive_unwrap_or_else(Zero::zero), ) { let (prop_index, proposal, _) = public_props.swap_remove(winner_index); >::put(public_props); diff --git a/frame/democracy/src/weights.rs b/frame/democracy/src/weights.rs index aa8e68f57053c..19bf602c5d291 100644 --- a/frame/democracy/src/weights.rs +++ b/frame/democracy/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_democracy //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-09-30, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-30, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/democracy/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -81,15 +82,15 @@ impl WeightInfo for SubstrateWeight { // Storage: Democracy Blacklist (r:1 w:0) // Storage: Democracy DepositOf (r:0 w:1) fn propose() -> Weight { - (67_388_000 as Weight) + (42_560_000 as Weight) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } // Storage: Democracy DepositOf (r:1 w:1) fn second(s: u32, ) -> Weight { - (41_157_000 as Weight) - // Standard Error: 0 - .saturating_add((157_000 as Weight).saturating_mul(s as Weight)) + (25_603_000 as Weight) + // Standard Error: 1_000 + .saturating_add((167_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -97,9 +98,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Democracy VotingOf (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vote_new(r: u32, ) -> Weight { - (46_406_000 as Weight) - // Standard Error: 1_000 - .saturating_add((170_000 as Weight).saturating_mul(r as Weight)) + (34_248_000 as Weight) + // Standard Error: 2_000 + .saturating_add((135_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -107,16 +108,16 @@ impl WeightInfo for SubstrateWeight { // Storage: Democracy VotingOf (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vote_existing(r: u32, ) -> Weight { - (46_071_000 as Weight) - // Standard Error: 1_000 - .saturating_add((166_000 as Weight).saturating_mul(r as Weight)) + (33_927_000 as Weight) + // Standard Error: 2_000 + .saturating_add((138_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } // Storage: Democracy ReferendumInfoOf (r:1 w:1) // Storage: Democracy Cancellations (r:1 w:1) fn emergency_cancel() -> Weight { - (27_699_000 as Weight) + (14_714_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -127,45 +128,45 @@ impl WeightInfo for SubstrateWeight { // Storage: Democracy DepositOf (r:1 w:1) // Storage: System Account (r:1 w:1) fn blacklist(p: u32, ) -> Weight { - (82_703_000 as Weight) - // Standard Error: 4_000 - .saturating_add((500_000 as Weight).saturating_mul(p as Weight)) + (49_423_000 as Weight) + // Standard Error: 3_000 + .saturating_add((275_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(6 as Weight)) } // Storage: Democracy NextExternal (r:1 w:1) // Storage: Democracy Blacklist (r:1 w:0) fn external_propose(v: u32, ) -> Weight { - (13_747_000 as Weight) + (7_321_000 as Weight) // Standard Error: 0 - .saturating_add((76_000 as Weight).saturating_mul(v as Weight)) + .saturating_add((75_000 as Weight).saturating_mul(v as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Democracy NextExternal (r:0 w:1) fn external_propose_majority() -> Weight { - (3_070_000 as Weight) + (1_325_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Democracy NextExternal (r:0 w:1) fn external_propose_default() -> Weight { - (3_080_000 as Weight) + (1_283_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Democracy NextExternal (r:1 w:1) // Storage: Democracy ReferendumCount (r:1 w:1) // Storage: Democracy ReferendumInfoOf (r:0 w:1) fn fast_track() -> Weight { - (29_129_000 as Weight) + (15_355_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } // Storage: Democracy NextExternal (r:1 w:1) // Storage: Democracy Blacklist (r:1 w:1) fn veto_external(v: u32, ) -> Weight { - (30_105_000 as Weight) + (16_597_000 as Weight) // Standard Error: 0 - .saturating_add((104_000 as Weight).saturating_mul(v as Weight)) + .saturating_add((90_000 as Weight).saturating_mul(v as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -173,56 +174,58 @@ impl WeightInfo for SubstrateWeight { // Storage: Democracy DepositOf (r:1 w:1) // Storage: System Account (r:1 w:1) fn cancel_proposal(p: u32, ) -> Weight { - (55_228_000 as Weight) - // Standard Error: 1_000 - .saturating_add((457_000 as Weight).saturating_mul(p as Weight)) + (37_695_000 as Weight) + // Standard Error: 2_000 + .saturating_add((258_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } // Storage: Democracy ReferendumInfoOf (r:0 w:1) fn cancel_referendum() -> Weight { - (17_319_000 as Weight) + (9_456_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Scheduler Lookup (r:1 w:1) // Storage: Scheduler Agenda (r:1 w:1) fn cancel_queued(r: u32, ) -> Weight { - (29_738_000 as Weight) + (19_915_000 as Weight) // Standard Error: 1_000 - .saturating_add((1_153_000 as Weight).saturating_mul(r as Weight)) + .saturating_add((609_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } - // Storage: Democracy LowestUnbaked (r:1 w:0) + // Storage: Democracy LowestUnbaked (r:1 w:1) // Storage: Democracy ReferendumCount (r:1 w:0) // Storage: Democracy ReferendumInfoOf (r:1 w:0) fn on_initialize_base(r: u32, ) -> Weight { - (2_165_000 as Weight) - // Standard Error: 3_000 - .saturating_add((5_577_000 as Weight).saturating_mul(r as Weight)) + (3_787_000 as Weight) + // Standard Error: 2_000 + .saturating_add((2_852_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) } - // Storage: Democracy LowestUnbaked (r:1 w:0) + // Storage: Democracy LowestUnbaked (r:1 w:1) // Storage: Democracy ReferendumCount (r:1 w:0) // Storage: Democracy LastTabledWasExternal (r:1 w:0) // Storage: Democracy NextExternal (r:1 w:0) // Storage: Democracy PublicProps (r:1 w:0) // Storage: Democracy ReferendumInfoOf (r:1 w:0) fn on_initialize_base_with_launch_period(r: u32, ) -> Weight { - (9_396_000 as Weight) - // Standard Error: 4_000 - .saturating_add((5_604_000 as Weight).saturating_mul(r as Weight)) + (7_890_000 as Weight) + // Standard Error: 2_000 + .saturating_add((2_856_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Democracy VotingOf (r:3 w:3) // Storage: Democracy ReferendumInfoOf (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn delegate(r: u32, ) -> Weight { - (57_783_000 as Weight) - // Standard Error: 4_000 - .saturating_add((7_623_000 as Weight).saturating_mul(r as Weight)) + (31_190_000 as Weight) + // Standard Error: 3_000 + .saturating_add((3_753_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) .saturating_add(T::DbWeight::get().writes(4 as Weight)) @@ -231,9 +234,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Democracy VotingOf (r:2 w:2) // Storage: Democracy ReferendumInfoOf (r:1 w:1) fn undelegate(r: u32, ) -> Weight { - (26_027_000 as Weight) - // Standard Error: 4_000 - .saturating_add((7_593_000 as Weight).saturating_mul(r as Weight)) + (15_121_000 as Weight) + // Standard Error: 3_000 + .saturating_add((3_852_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) .saturating_add(T::DbWeight::get().writes(2 as Weight)) @@ -241,12 +244,12 @@ impl WeightInfo for SubstrateWeight { } // Storage: Democracy PublicProps (r:0 w:1) fn clear_public_proposals() -> Weight { - (2_780_000 as Weight) + (1_583_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Democracy Preimages (r:1 w:1) fn note_preimage(b: u32, ) -> Weight { - (46_416_000 as Weight) + (22_681_000 as Weight) // Standard Error: 0 .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) @@ -254,7 +257,7 @@ impl WeightInfo for SubstrateWeight { } // Storage: Democracy Preimages (r:1 w:1) fn note_imminent_preimage(b: u32, ) -> Weight { - (29_735_000 as Weight) + (15_599_000 as Weight) // Standard Error: 0 .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) @@ -263,7 +266,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Democracy Preimages (r:1 w:1) // Storage: System Account (r:1 w:0) fn reap_preimage(b: u32, ) -> Weight { - (41_276_000 as Weight) + (23_663_000 as Weight) // Standard Error: 0 .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) @@ -273,9 +276,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) fn unlock_remove(r: u32, ) -> Weight { - (40_348_000 as Weight) + (21_928_000 as Weight) // Standard Error: 1_000 - .saturating_add((60_000 as Weight).saturating_mul(r as Weight)) + .saturating_add((61_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -283,27 +286,27 @@ impl WeightInfo for SubstrateWeight { // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) fn unlock_set(r: u32, ) -> Weight { - (37_475_000 as Weight) + (21_548_000 as Weight) // Standard Error: 1_000 - .saturating_add((151_000 as Weight).saturating_mul(r as Weight)) + .saturating_add((123_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } // Storage: Democracy ReferendumInfoOf (r:1 w:1) // Storage: Democracy VotingOf (r:1 w:1) fn remove_vote(r: u32, ) -> Weight { - (19_970_000 as Weight) + (11_797_000 as Weight) // Standard Error: 1_000 - .saturating_add((153_000 as Weight).saturating_mul(r as Weight)) + .saturating_add((117_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Democracy ReferendumInfoOf (r:1 w:1) // Storage: Democracy VotingOf (r:1 w:1) fn remove_other_vote(r: u32, ) -> Weight { - (20_094_000 as Weight) + (11_930_000 as Weight) // Standard Error: 1_000 - .saturating_add((157_000 as Weight).saturating_mul(r as Weight)) + .saturating_add((122_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -316,15 +319,15 @@ impl WeightInfo for () { // Storage: Democracy Blacklist (r:1 w:0) // Storage: Democracy DepositOf (r:0 w:1) fn propose() -> Weight { - (67_388_000 as Weight) + (42_560_000 as Weight) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } // Storage: Democracy DepositOf (r:1 w:1) fn second(s: u32, ) -> Weight { - (41_157_000 as Weight) - // Standard Error: 0 - .saturating_add((157_000 as Weight).saturating_mul(s as Weight)) + (25_603_000 as Weight) + // Standard Error: 1_000 + .saturating_add((167_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -332,9 +335,9 @@ impl WeightInfo for () { // Storage: Democracy VotingOf (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vote_new(r: u32, ) -> Weight { - (46_406_000 as Weight) - // Standard Error: 1_000 - .saturating_add((170_000 as Weight).saturating_mul(r as Weight)) + (34_248_000 as Weight) + // Standard Error: 2_000 + .saturating_add((135_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } @@ -342,16 +345,16 @@ impl WeightInfo for () { // Storage: Democracy VotingOf (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vote_existing(r: u32, ) -> Weight { - (46_071_000 as Weight) - // Standard Error: 1_000 - .saturating_add((166_000 as Weight).saturating_mul(r as Weight)) + (33_927_000 as Weight) + // Standard Error: 2_000 + .saturating_add((138_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } // Storage: Democracy ReferendumInfoOf (r:1 w:1) // Storage: Democracy Cancellations (r:1 w:1) fn emergency_cancel() -> Weight { - (27_699_000 as Weight) + (14_714_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -362,45 +365,45 @@ impl WeightInfo for () { // Storage: Democracy DepositOf (r:1 w:1) // Storage: System Account (r:1 w:1) fn blacklist(p: u32, ) -> Weight { - (82_703_000 as Weight) - // Standard Error: 4_000 - .saturating_add((500_000 as Weight).saturating_mul(p as Weight)) + (49_423_000 as Weight) + // Standard Error: 3_000 + .saturating_add((275_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(6 as Weight)) } // Storage: Democracy NextExternal (r:1 w:1) // Storage: Democracy Blacklist (r:1 w:0) fn external_propose(v: u32, ) -> Weight { - (13_747_000 as Weight) + (7_321_000 as Weight) // Standard Error: 0 - .saturating_add((76_000 as Weight).saturating_mul(v as Weight)) + .saturating_add((75_000 as Weight).saturating_mul(v as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Democracy NextExternal (r:0 w:1) fn external_propose_majority() -> Weight { - (3_070_000 as Weight) + (1_325_000 as Weight) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Democracy NextExternal (r:0 w:1) fn external_propose_default() -> Weight { - (3_080_000 as Weight) + (1_283_000 as Weight) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Democracy NextExternal (r:1 w:1) // Storage: Democracy ReferendumCount (r:1 w:1) // Storage: Democracy ReferendumInfoOf (r:0 w:1) fn fast_track() -> Weight { - (29_129_000 as Weight) + (15_355_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } // Storage: Democracy NextExternal (r:1 w:1) // Storage: Democracy Blacklist (r:1 w:1) fn veto_external(v: u32, ) -> Weight { - (30_105_000 as Weight) + (16_597_000 as Weight) // Standard Error: 0 - .saturating_add((104_000 as Weight).saturating_mul(v as Weight)) + .saturating_add((90_000 as Weight).saturating_mul(v as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -408,56 +411,58 @@ impl WeightInfo for () { // Storage: Democracy DepositOf (r:1 w:1) // Storage: System Account (r:1 w:1) fn cancel_proposal(p: u32, ) -> Weight { - (55_228_000 as Weight) - // Standard Error: 1_000 - .saturating_add((457_000 as Weight).saturating_mul(p as Weight)) + (37_695_000 as Weight) + // Standard Error: 2_000 + .saturating_add((258_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } // Storage: Democracy ReferendumInfoOf (r:0 w:1) fn cancel_referendum() -> Weight { - (17_319_000 as Weight) + (9_456_000 as Weight) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Scheduler Lookup (r:1 w:1) // Storage: Scheduler Agenda (r:1 w:1) fn cancel_queued(r: u32, ) -> Weight { - (29_738_000 as Weight) + (19_915_000 as Weight) // Standard Error: 1_000 - .saturating_add((1_153_000 as Weight).saturating_mul(r as Weight)) + .saturating_add((609_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } - // Storage: Democracy LowestUnbaked (r:1 w:0) + // Storage: Democracy LowestUnbaked (r:1 w:1) // Storage: Democracy ReferendumCount (r:1 w:0) // Storage: Democracy ReferendumInfoOf (r:1 w:0) fn on_initialize_base(r: u32, ) -> Weight { - (2_165_000 as Weight) - // Standard Error: 3_000 - .saturating_add((5_577_000 as Weight).saturating_mul(r as Weight)) + (3_787_000 as Weight) + // Standard Error: 2_000 + .saturating_add((2_852_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } - // Storage: Democracy LowestUnbaked (r:1 w:0) + // Storage: Democracy LowestUnbaked (r:1 w:1) // Storage: Democracy ReferendumCount (r:1 w:0) // Storage: Democracy LastTabledWasExternal (r:1 w:0) // Storage: Democracy NextExternal (r:1 w:0) // Storage: Democracy PublicProps (r:1 w:0) // Storage: Democracy ReferendumInfoOf (r:1 w:0) fn on_initialize_base_with_launch_period(r: u32, ) -> Weight { - (9_396_000 as Weight) - // Standard Error: 4_000 - .saturating_add((5_604_000 as Weight).saturating_mul(r as Weight)) + (7_890_000 as Weight) + // Standard Error: 2_000 + .saturating_add((2_856_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Democracy VotingOf (r:3 w:3) // Storage: Democracy ReferendumInfoOf (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn delegate(r: u32, ) -> Weight { - (57_783_000 as Weight) - // Standard Error: 4_000 - .saturating_add((7_623_000 as Weight).saturating_mul(r as Weight)) + (31_190_000 as Weight) + // Standard Error: 3_000 + .saturating_add((3_753_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) @@ -466,9 +471,9 @@ impl WeightInfo for () { // Storage: Democracy VotingOf (r:2 w:2) // Storage: Democracy ReferendumInfoOf (r:1 w:1) fn undelegate(r: u32, ) -> Weight { - (26_027_000 as Weight) - // Standard Error: 4_000 - .saturating_add((7_593_000 as Weight).saturating_mul(r as Weight)) + (15_121_000 as Weight) + // Standard Error: 3_000 + .saturating_add((3_852_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) @@ -476,12 +481,12 @@ impl WeightInfo for () { } // Storage: Democracy PublicProps (r:0 w:1) fn clear_public_proposals() -> Weight { - (2_780_000 as Weight) + (1_583_000 as Weight) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Democracy Preimages (r:1 w:1) fn note_preimage(b: u32, ) -> Weight { - (46_416_000 as Weight) + (22_681_000 as Weight) // Standard Error: 0 .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) @@ -489,7 +494,7 @@ impl WeightInfo for () { } // Storage: Democracy Preimages (r:1 w:1) fn note_imminent_preimage(b: u32, ) -> Weight { - (29_735_000 as Weight) + (15_599_000 as Weight) // Standard Error: 0 .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) @@ -498,7 +503,7 @@ impl WeightInfo for () { // Storage: Democracy Preimages (r:1 w:1) // Storage: System Account (r:1 w:0) fn reap_preimage(b: u32, ) -> Weight { - (41_276_000 as Weight) + (23_663_000 as Weight) // Standard Error: 0 .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) @@ -508,9 +513,9 @@ impl WeightInfo for () { // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) fn unlock_remove(r: u32, ) -> Weight { - (40_348_000 as Weight) + (21_928_000 as Weight) // Standard Error: 1_000 - .saturating_add((60_000 as Weight).saturating_mul(r as Weight)) + .saturating_add((61_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } @@ -518,27 +523,27 @@ impl WeightInfo for () { // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) fn unlock_set(r: u32, ) -> Weight { - (37_475_000 as Weight) + (21_548_000 as Weight) // Standard Error: 1_000 - .saturating_add((151_000 as Weight).saturating_mul(r as Weight)) + .saturating_add((123_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } // Storage: Democracy ReferendumInfoOf (r:1 w:1) // Storage: Democracy VotingOf (r:1 w:1) fn remove_vote(r: u32, ) -> Weight { - (19_970_000 as Weight) + (11_797_000 as Weight) // Standard Error: 1_000 - .saturating_add((153_000 as Weight).saturating_mul(r as Weight)) + .saturating_add((117_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Democracy ReferendumInfoOf (r:1 w:1) // Storage: Democracy VotingOf (r:1 w:1) fn remove_other_vote(r: u32, ) -> Weight { - (20_094_000 as Weight) + (11_930_000 as Weight) // Standard Error: 1_000 - .saturating_add((157_000 as Weight).saturating_mul(r as Weight)) + .saturating_add((122_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } diff --git a/frame/election-provider-multi-phase/Cargo.toml b/frame/election-provider-multi-phase/Cargo.toml index 7add94dc76c80..c0d85737ec221 100644 --- a/frame/election-provider-multi-phase/Cargo.toml +++ b/frame/election-provider-multi-phase/Cargo.toml @@ -23,10 +23,10 @@ log = { version = "0.4.14", default-features = false } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-npos-elections = { version = "4.0.0-dev", default-features = false, path = "../../primitives/npos-elections" } sp-arithmetic = { version = "4.0.0", default-features = false, path = "../../primitives/arithmetic" } frame-election-provider-support = { version = "4.0.0-dev", default-features = false, path = "../election-provider-support" } @@ -37,14 +37,13 @@ rand = { version = "0.7.3", default-features = false, optional = true, features "alloc", "small_rng", ] } -strum = { optional = true, version = "0.22.0" } -strum_macros = { optional = true, version = "0.23.1" } +strum = { optional = true, default-features = false, version = "0.23.0", features = ["derive"] } [dev-dependencies] parking_lot = "0.11.2" rand = { version = "0.7.3" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } sp-npos-elections = { version = "4.0.0-dev", default-features = false, path = "../../primitives/npos-elections" } sp-tracing = { version = "4.0.0", path = "../../primitives/tracing" } frame-election-provider-support = { version = "4.0.0-dev", features = [ @@ -70,12 +69,15 @@ std = [ "sp-arithmetic/std", "frame-election-provider-support/std", "log/std", + + "frame-benchmarking/std", + "rand/std", + "strum/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-election-provider-support/runtime-benchmarks", "rand", "strum", - "strum_macros", ] try-runtime = ["frame-support/try-runtime"] diff --git a/frame/election-provider-multi-phase/src/benchmarking.rs b/frame/election-provider-multi-phase/src/benchmarking.rs index d605c5131cf77..d37b9451b770f 100644 --- a/frame/election-provider-multi-phase/src/benchmarking.rs +++ b/frame/election-provider-multi-phase/src/benchmarking.rs @@ -20,7 +20,11 @@ use super::*; use crate::{unsigned::IndexAssignmentOf, Pallet as MultiPhase}; use frame_benchmarking::account; -use frame_support::{assert_ok, traits::Hooks}; +use frame_support::{ + assert_ok, + traits::{Hooks, TryCollect}, + BoundedVec, +}; use frame_system::RawOrigin; use rand::{prelude::SliceRandom, rngs::SmallRng, SeedableRng}; use sp_arithmetic::{per_things::Percent, traits::One}; @@ -69,11 +73,12 @@ fn solution_with_size( let active_voters = (0..active_voters_count) .map(|i| { // chose a random subset of winners. - let winner_votes = winners + let winner_votes: BoundedVec<_, _> = winners .as_slice() .choose_multiple(&mut rng, >::LIMIT) .cloned() - .collect::>(); + .try_collect() + .expect(">::LIMIT is the correct bound; qed."); let voter = frame_benchmarking::account::("Voter", i, SEED); (voter, stake, winner_votes) }) @@ -87,10 +92,11 @@ fn solution_with_size( .collect::>(); let rest_voters = (active_voters_count..size.voters) .map(|i| { - let votes = (&non_winners) + let votes: BoundedVec<_, _> = (&non_winners) .choose_multiple(&mut rng, >::LIMIT) .cloned() - .collect::>(); + .try_collect() + .expect(">::LIMIT is the correct bound; qed."); let voter = frame_benchmarking::account::("Voter", i, SEED); (voter, stake, votes) }) @@ -152,7 +158,7 @@ fn set_up_data_provider(v: u32, t: u32) { info, "setting up with voters = {} [degree = {}], targets = {}", v, - T::DataProvider::MAXIMUM_VOTES_PER_VOTER, + ::MaxVotesPerVoter::get(), t ); @@ -165,14 +171,16 @@ fn set_up_data_provider(v: u32, t: u32) { }) .collect::>(); // we should always have enough voters to fill. - assert!(targets.len() > T::DataProvider::MAXIMUM_VOTES_PER_VOTER as usize); - targets.truncate(T::DataProvider::MAXIMUM_VOTES_PER_VOTER as usize); + assert!( + targets.len() > ::MaxVotesPerVoter::get() as usize + ); + targets.truncate(::MaxVotesPerVoter::get() as usize); // fill voters. (0..v).for_each(|i| { let voter = frame_benchmarking::account::("Voter", i, SEED); let weight = T::Currency::minimum_balance().saturated_into::() * 1000; - T::DataProvider::add_voter(voter, weight, targets.clone()); + T::DataProvider::add_voter(voter, weight, targets.clone().try_into().unwrap()); }); } diff --git a/frame/election-provider-multi-phase/src/helpers.rs b/frame/election-provider-multi-phase/src/helpers.rs index 9bd5b5dbabd25..48da194cc65d9 100644 --- a/frame/election-provider-multi-phase/src/helpers.rs +++ b/frame/election-provider-multi-phase/src/helpers.rs @@ -17,7 +17,7 @@ //! Some helper functions/macros for this crate. -use super::{Config, SolutionTargetIndexOf, SolutionVoterIndexOf, VoteWeight}; +use crate::{unsigned::VoterOf, Config, SolutionTargetIndexOf, SolutionVoterIndexOf, VoteWeight}; use sp_std::{collections::btree_map::BTreeMap, prelude::*}; #[macro_export] @@ -34,7 +34,7 @@ macro_rules! log { /// /// This can be used to efficiently build index getter closures. pub fn generate_voter_cache( - snapshot: &Vec<(T::AccountId, VoteWeight, Vec)>, + snapshot: &Vec>, ) -> BTreeMap { let mut cache: BTreeMap = BTreeMap::new(); snapshot.iter().enumerate().for_each(|(i, (x, _, _))| { @@ -97,7 +97,7 @@ pub fn voter_index_fn_usize( /// Not meant to be used in production. #[cfg(test)] pub fn voter_index_fn_linear( - snapshot: &Vec<(T::AccountId, VoteWeight, Vec)>, + snapshot: &Vec>, ) -> impl Fn(&T::AccountId) -> Option> + '_ { move |who| { snapshot @@ -148,7 +148,7 @@ pub fn target_index_fn_linear( /// Create a function that can map a voter index ([`SolutionVoterIndexOf`]) to the actual voter /// account using a linearly indexible snapshot. pub fn voter_at_fn( - snapshot: &Vec<(T::AccountId, VoteWeight, Vec)>, + snapshot: &Vec>, ) -> impl Fn(SolutionVoterIndexOf) -> Option + '_ { move |i| { as TryInto>::try_into(i) @@ -174,7 +174,7 @@ pub fn target_at_fn( /// This is not optimized and uses a linear search. #[cfg(test)] pub fn stake_of_fn_linear( - snapshot: &Vec<(T::AccountId, VoteWeight, Vec)>, + snapshot: &Vec>, ) -> impl Fn(&T::AccountId) -> VoteWeight + '_ { move |who| { snapshot @@ -192,7 +192,7 @@ pub fn stake_of_fn_linear( /// The cache need must be derived from the same snapshot. Zero is returned if a voter is /// non-existent. pub fn stake_of_fn<'a, T: Config>( - snapshot: &'a Vec<(T::AccountId, VoteWeight, Vec)>, + snapshot: &'a Vec>, cache: &'a BTreeMap, ) -> impl Fn(&T::AccountId) -> VoteWeight + 'a { move |who| { diff --git a/frame/election-provider-multi-phase/src/lib.rs b/frame/election-provider-multi-phase/src/lib.rs index 4716bcd6c859b..cad3d12605e48 100644 --- a/frame/election-provider-multi-phase/src/lib.rs +++ b/frame/election-provider-multi-phase/src/lib.rs @@ -230,7 +230,9 @@ #![cfg_attr(not(feature = "std"), no_std)] use codec::{Decode, Encode}; -use frame_election_provider_support::{ElectionDataProvider, ElectionProvider}; +use frame_election_provider_support::{ + ElectionDataProvider, ElectionProvider, InstantElectionProvider, +}; use frame_support::{ dispatch::DispatchResultWithPostInfo, ensure, @@ -253,7 +255,7 @@ use sp_runtime::{ InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity, TransactionValidityError, ValidTransaction, }, - DispatchError, PerThing, Perbill, RuntimeDebug, SaturatedConversion, + DispatchError, ModuleError, PerThing, Perbill, RuntimeDebug, SaturatedConversion, }; use sp_std::prelude::*; @@ -269,6 +271,7 @@ const LOG_TARGET: &'static str = "runtime::election-provider"; pub mod signed; pub mod unsigned; pub mod weights; +use unsigned::VoterOf; pub use weights::WeightInfo; pub use signed::{ @@ -321,6 +324,15 @@ impl ElectionProvider for NoFallback { } } +impl InstantElectionProvider for NoFallback { + fn instant_elect( + _: Option, + _: Option, + ) -> Result, Self::Error> { + Err("NoFallback.") + } +} + /// Current phase of the pallet. #[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, Debug, TypeInfo)] pub enum Phase { @@ -448,11 +460,13 @@ pub struct ReadySolution { /// /// These are stored together because they are often accessed together. #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, Default, TypeInfo)] -pub struct RoundSnapshot { +#[codec(mel_bound())] +#[scale_info(skip_type_params(T))] +pub struct RoundSnapshot { /// All of the voters. - pub voters: Vec<(A, VoteWeight, Vec)>, + pub voters: Vec>, /// All of the targets. - pub targets: Vec, + pub targets: Vec, } /// Encodes the length of a solution or a snapshot. @@ -474,7 +488,7 @@ pub struct SolutionOrSnapshotSize { /// /// Note that this is different from [`pallet::Error`]. #[derive(frame_support::DebugNoBound)] -#[cfg_attr(feature = "runtime-benchmarks", derive(strum_macros::IntoStaticStr))] +#[cfg_attr(feature = "runtime-benchmarks", derive(strum::IntoStaticStr))] pub enum ElectionError { /// An error happened in the feasibility check sub-system. Feasibility(FeasibilityError), @@ -519,7 +533,7 @@ impl From> for ElectionError { /// Errors that can happen in the feasibility check. #[derive(Debug, Eq, PartialEq)] -#[cfg_attr(feature = "runtime-benchmarks", derive(strum_macros::IntoStaticStr))] +#[cfg_attr(feature = "runtime-benchmarks", derive(strum::IntoStaticStr))] pub enum FeasibilityError { /// Wrong number of winners presented. WrongWinnerCount, @@ -552,7 +566,7 @@ pub use pallet::*; #[frame_support::pallet] pub mod pallet { use super::*; - use frame_election_provider_support::NposSolver; + use frame_election_provider_support::{InstantElectionProvider, NposSolver}; use frame_support::{pallet_prelude::*, traits::EstimateCallFee}; use frame_system::pallet_prelude::*; @@ -669,13 +683,23 @@ pub mod pallet { + NposSolution + TypeInfo; - /// Configuration for the fallback + /// Configuration for the fallback. type Fallback: ElectionProvider< AccountId = Self::AccountId, BlockNumber = Self::BlockNumber, DataProvider = Self::DataProvider, >; + /// Configuration of the governance-only fallback. + /// + /// As a side-note, it is recommend for test-nets to use `type ElectionProvider = + /// OnChainSeqPhragmen<_>` if the test-net is not expected to have thousands of nominators. + type GovernanceFallback: InstantElectionProvider< + AccountId = Self::AccountId, + BlockNumber = Self::BlockNumber, + DataProvider = Self::DataProvider, + >; + /// OCW election solution miner algorithm implementation. type Solver: NposSolver; @@ -820,7 +844,7 @@ pub mod pallet { // NOTE that this pallet does not really need to enforce this in runtime. The // solution cannot represent any voters more than `LIMIT` anyhow. assert_eq!( - ::MAXIMUM_VOTES_PER_VOTER, + ::MaxVotesPerVoter::get(), as NposSolution>::LIMIT as u32, ); } @@ -1010,6 +1034,37 @@ pub mod pallet { }); Ok(()) } + + /// Trigger the governance fallback. + /// + /// This can only be called when [`Phase::Emergency`] is enabled, as an alternative to + /// calling [`Call::set_emergency_election_result`]. + #[pallet::weight(T::DbWeight::get().reads_writes(1, 1))] + pub fn governance_fallback( + origin: OriginFor, + maybe_max_voters: Option, + maybe_max_targets: Option, + ) -> DispatchResult { + T::ForceOrigin::ensure_origin(origin)?; + ensure!(Self::current_phase().is_emergency(), >::CallNotAllowed); + + let maybe_max_voters = maybe_max_voters.map(|x| x as usize); + let maybe_max_targets = maybe_max_targets.map(|x| x as usize); + + let supports = + T::GovernanceFallback::instant_elect(maybe_max_voters, maybe_max_targets).map_err( + |e| { + log!(error, "GovernanceFallback failed: {:?}", e); + Error::::FallbackFailed + }, + )?; + + let solution = + ReadySolution { supports, score: [0, 0, 0], compute: ElectionCompute::Fallback }; + + >::put(solution); + Ok(()) + } } #[pallet::event] @@ -1060,6 +1115,8 @@ pub mod pallet { InvalidSubmissionIndex, /// The call is not allowed at this point. CallNotAllowed, + /// The fallback failed + FallbackFailed, } #[pallet::validate_unsigned] @@ -1140,7 +1197,7 @@ pub mod pallet { /// This is created at the beginning of the signed phase and cleared upon calling `elect`. #[pallet::storage] #[pallet::getter(fn snapshot)] - pub type Snapshot = StorageValue<_, RoundSnapshot>; + pub type Snapshot = StorageValue<_, RoundSnapshot>; /// Desired number of targets to elect for this round. /// @@ -1257,7 +1314,7 @@ impl Pallet { /// Extracted for easier weight calculation. fn create_snapshot_internal( targets: Vec, - voters: Vec>, + voters: Vec>, desired_targets: u32, ) { let metadata = @@ -1270,7 +1327,7 @@ impl Pallet { // instead of using storage APIs, we do a manual encoding into a fixed-size buffer. // `encoded_size` encodes it without storing it anywhere, this should not cause any // allocation. - let snapshot = RoundSnapshot { voters, targets }; + let snapshot = RoundSnapshot:: { voters, targets }; let size = snapshot.encoded_size(); log!(debug, "snapshot pre-calculated size {:?}", size); let mut buffer = Vec::with_capacity(size); @@ -1288,7 +1345,7 @@ impl Pallet { /// /// Extracted for easier weight calculation. fn create_snapshot_external( - ) -> Result<(Vec, Vec>, u32), ElectionError> { + ) -> Result<(Vec, Vec>, u32), ElectionError> { let target_limit = >::max_value().saturated_into::(); // for now we have just a single block snapshot. let voter_limit = T::VoterSnapshotPerBlock::get().saturated_into::(); @@ -1522,7 +1579,7 @@ impl ElectionProvider for Pallet { /// number. pub fn dispatch_error_to_invalid(error: DispatchError) -> InvalidTransaction { let error_number = match error { - DispatchError::Module { error, .. } => error, + DispatchError::Module(ModuleError { error, .. }) => error, _ => 0, }; InvalidTransaction::Custom(error_number) diff --git a/frame/election-provider-multi-phase/src/mock.rs b/frame/election-provider-multi-phase/src/mock.rs index 409ebd3f1e10d..9ac0ecfef5dce 100644 --- a/frame/election-provider-multi-phase/src/mock.rs +++ b/frame/election-provider-multi-phase/src/mock.rs @@ -22,11 +22,12 @@ use frame_election_provider_support::{ }; pub use frame_support::{assert_noop, assert_ok}; use frame_support::{ - parameter_types, + bounded_vec, parameter_types, traits::{ConstU32, Hooks}, weights::Weight, + BoundedVec, }; -use multi_phase::unsigned::{IndexAssignmentOf, Voter}; +use multi_phase::unsigned::{IndexAssignmentOf, VoterOf}; use parking_lot::RwLock; use sp_core::{ offchain::{ @@ -100,7 +101,7 @@ pub fn roll_to_with_ocw(n: BlockNumber) { } pub struct TrimHelpers { - pub voters: Vec>, + pub voters: Vec>, pub assignments: Vec>, pub encoded_size_of: Box]) -> Result>, @@ -131,13 +132,8 @@ pub fn trim_helpers() -> TrimHelpers { let desired_targets = MultiPhase::desired_targets().unwrap(); - let ElectionResult { mut assignments, .. } = seq_phragmen::<_, SolutionAccuracyOf>( - desired_targets as usize, - targets.clone(), - voters.clone(), - None, - ) - .unwrap(); + let ElectionResult::<_, SolutionAccuracyOf> { mut assignments, .. } = + seq_phragmen(desired_targets as usize, targets.clone(), voters.clone(), None).unwrap(); // sort by decreasing order of stake assignments.sort_unstable_by_key(|assignment| { @@ -163,14 +159,8 @@ pub fn raw_solution() -> RawSolution> { let RoundSnapshot { voters, targets } = MultiPhase::snapshot().unwrap(); let desired_targets = MultiPhase::desired_targets().unwrap(); - let ElectionResult { winners: _, assignments } = - seq_phragmen::<_, SolutionAccuracyOf>( - desired_targets as usize, - targets.clone(), - voters.clone(), - None, - ) - .unwrap(); + let ElectionResult::<_, SolutionAccuracyOf> { winners: _, assignments } = + seq_phragmen(desired_targets as usize, targets.clone(), voters.clone(), None).unwrap(); // closures let cache = helpers::generate_voter_cache::(&voters); @@ -246,16 +236,16 @@ impl pallet_balances::Config for Runtime { parameter_types! { pub static Targets: Vec = vec![10, 20, 30, 40]; - pub static Voters: Vec<(AccountId, VoteWeight, Vec)> = vec![ - (1, 10, vec![10, 20]), - (2, 10, vec![30, 40]), - (3, 10, vec![40]), - (4, 10, vec![10, 20, 30, 40]), + pub static Voters: Vec> = vec![ + (1, 10, bounded_vec![10, 20]), + (2, 10, bounded_vec![30, 40]), + (3, 10, bounded_vec![40]), + (4, 10, bounded_vec![10, 20, 30, 40]), // self votes. - (10, 10, vec![10]), - (20, 20, vec![20]), - (30, 30, vec![30]), - (40, 40, vec![40]), + (10, 10, bounded_vec![10]), + (20, 20, bounded_vec![20]), + (30, 30, bounded_vec![30]), + (40, 40, bounded_vec![40]), ]; pub static DesiredTargets: u32 = 2; @@ -420,6 +410,7 @@ impl crate::Config for Runtime { type WeightInfo = DualMockWeightInfo; type BenchmarkingConfig = TestBenchmarkingConfig; type Fallback = MockFallback; + type GovernanceFallback = NoFallback; type ForceOrigin = frame_system::EnsureRoot; type Solution = TestNposSolution; type VoterSnapshotPerBlock = VoterSnapshotPerBlock; @@ -436,6 +427,10 @@ where pub type Extrinsic = sp_runtime::testing::TestXt; +parameter_types! { + pub MaxNominations: u32 = ::LIMIT as u32; +} + #[derive(Default)] pub struct ExtBuilder {} @@ -443,7 +438,7 @@ pub struct StakingMock; impl ElectionDataProvider for StakingMock { type AccountId = AccountId; type BlockNumber = u64; - const MAXIMUM_VOTES_PER_VOTER: u32 = ::LIMIT as u32; + type MaxVotesPerVoter = MaxNominations; fn targets(maybe_max_len: Option) -> data_provider::Result> { let targets = Targets::get(); @@ -454,9 +449,7 @@ impl ElectionDataProvider for StakingMock { Ok(targets) } - fn voters( - maybe_max_len: Option, - ) -> data_provider::Result)>> { + fn voters(maybe_max_len: Option) -> data_provider::Result>> { let mut voters = Voters::get(); if let Some(max_len) = maybe_max_len { voters.truncate(max_len) @@ -475,7 +468,7 @@ impl ElectionDataProvider for StakingMock { #[cfg(feature = "runtime-benchmarks")] fn put_snapshot( - voters: Vec<(AccountId, VoteWeight, Vec)>, + voters: Vec>, targets: Vec, _target_stake: Option, ) { @@ -490,7 +483,11 @@ impl ElectionDataProvider for StakingMock { } #[cfg(feature = "runtime-benchmarks")] - fn add_voter(voter: AccountId, weight: VoteWeight, targets: Vec) { + fn add_voter( + voter: AccountId, + weight: VoteWeight, + targets: frame_support::BoundedVec, + ) { let mut current = Voters::get(); current.push((voter, weight, targets)); Voters::set(current); @@ -505,7 +502,7 @@ impl ElectionDataProvider for StakingMock { // to be on-par with staking, we add a self vote as well. the stake is really not that // important. let mut current = Voters::get(); - current.push((target, ExistentialDeposit::get() as u64, vec![target])); + current.push((target, ExistentialDeposit::get() as u64, bounded_vec![target])); Voters::set(current); } } @@ -540,7 +537,12 @@ impl ExtBuilder { ::set(t); self } - pub fn add_voter(self, who: AccountId, stake: Balance, targets: Vec) -> Self { + pub fn add_voter( + self, + who: AccountId, + stake: Balance, + targets: BoundedVec, + ) -> Self { VOTERS.with(|v| v.borrow_mut().push((who, stake, targets))); self } diff --git a/frame/election-provider-multi-phase/src/signed.rs b/frame/election-provider-multi-phase/src/signed.rs index c2cb5cf44823e..3b314bce80ffe 100644 --- a/frame/election-provider-multi-phase/src/signed.rs +++ b/frame/election-provider-multi-phase/src/signed.rs @@ -25,7 +25,7 @@ use crate::{ use codec::{Decode, Encode, HasCompact}; use frame_support::{ storage::bounded_btree_map::BoundedBTreeMap, - traits::{Currency, Get, OnUnbalanced, ReservableCurrency}, + traits::{defensive_prelude::*, Currency, Get, OnUnbalanced, ReservableCurrency}, }; use sp_arithmetic::traits::SaturatedConversion; use sp_npos_elections::{is_score_better, ElectionScore, NposSolution}; @@ -365,7 +365,7 @@ impl Pallet { let active_voters = raw_solution.solution.voter_count() as u32; let feasibility_weight = { // defensive only: at the end of signed phase, snapshot will exits. - let desired_targets = Self::desired_targets().unwrap_or_default(); + let desired_targets = Self::desired_targets().defensive_unwrap_or_default(); T::WeightInfo::feasibility_check(voters, targets, active_voters, desired_targets) }; // the feasibility check itself has some weight diff --git a/frame/election-provider-multi-phase/src/unsigned.rs b/frame/election-provider-multi-phase/src/unsigned.rs index da56dd4d073df..196147f8a4706 100644 --- a/frame/election-provider-multi-phase/src/unsigned.rs +++ b/frame/election-provider-multi-phase/src/unsigned.rs @@ -47,11 +47,7 @@ pub(crate) const OFFCHAIN_CACHED_CALL: &[u8] = b"parity/multi-phase-unsigned-ele /// A voter's fundamental data: their ID, their stake, and the list of candidates for whom they /// voted. -pub type Voter = ( - ::AccountId, - sp_npos_elections::VoteWeight, - Vec<::AccountId>, -); +pub type VoterOf = frame_election_provider_support::VoterOf<::DataProvider>; /// The relative distribution of a voter's stake among the winning targets. pub type Assignment = @@ -749,12 +745,14 @@ mod tests { }; use codec::Decode; use frame_benchmarking::Zero; - use frame_support::{assert_noop, assert_ok, dispatch::Dispatchable, traits::OffchainWorker}; + use frame_support::{ + assert_noop, assert_ok, bounded_vec, dispatch::Dispatchable, traits::OffchainWorker, + }; use sp_npos_elections::IndexAssignment; use sp_runtime::{ offchain::storage_lock::{BlockAndTime, StorageLock}, traits::ValidateUnsigned, - PerU16, + ModuleError, PerU16, }; type Assignment = crate::unsigned::Assignment; @@ -924,8 +922,8 @@ mod tests { #[test] #[should_panic(expected = "Invalid unsigned submission must produce invalid block and \ deprive validator from their authoring reward.: \ - Module { index: 2, error: 1, message: \ - Some(\"PreDispatchWrongWinnerCount\") }")] + Module(ModuleError { index: 2, error: 1, message: \ + Some(\"PreDispatchWrongWinnerCount\") })")] fn unfeasible_solution_panics() { ExtBuilder::default().build_and_execute(|| { roll_to(25); @@ -1035,11 +1033,11 @@ mod tests { assert_eq!( MultiPhase::mine_check_save_submit().unwrap_err(), - MinerError::PreDispatchChecksFailed(DispatchError::Module { + MinerError::PreDispatchChecksFailed(DispatchError::Module(ModuleError { index: 2, error: 1, message: Some("PreDispatchWrongWinnerCount"), - }), + })), ); }) } @@ -1048,8 +1046,8 @@ mod tests { fn unsigned_per_dispatch_checks_can_only_submit_threshold_better() { ExtBuilder::default() .desired_targets(1) - .add_voter(7, 2, vec![10]) - .add_voter(8, 5, vec![10]) + .add_voter(7, 2, bounded_vec![10]) + .add_voter(8, 5, bounded_vec![10]) .solution_improvement_threshold(Perbill::from_percent(50)) .build_and_execute(|| { roll_to(25); diff --git a/frame/election-provider-multi-phase/src/weights.rs b/frame/election-provider-multi-phase/src/weights.rs index 7bb3303cba2ef..99e149eff2410 100644 --- a/frame/election-provider-multi-phase/src/weights.rs +++ b/frame/election-provider-multi-phase/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_election_provider_multi_phase //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-09-22, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-30, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/election-provider-multi-phase/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -69,33 +70,33 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking ForceEra (r:1 w:0) // Storage: ElectionProviderMultiPhase CurrentPhase (r:1 w:0) fn on_initialize_nothing() -> Weight { - (22_784_000 as Weight) + (12_763_000 as Weight) .saturating_add(T::DbWeight::get().reads(8 as Weight)) } // Storage: ElectionProviderMultiPhase Round (r:1 w:0) // Storage: ElectionProviderMultiPhase CurrentPhase (r:0 w:1) fn on_initialize_open_signed() -> Weight { - (32_763_000 as Weight) + (13_195_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: ElectionProviderMultiPhase Round (r:1 w:0) // Storage: ElectionProviderMultiPhase CurrentPhase (r:0 w:1) fn on_initialize_open_unsigned() -> Weight { - (29_117_000 as Weight) + (12_782_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: System Account (r:1 w:1) // Storage: ElectionProviderMultiPhase QueuedSolution (r:0 w:1) fn finalize_signed_phase_accept_solution() -> Weight { - (48_996_000 as Weight) + (27_421_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: System Account (r:1 w:1) fn finalize_signed_phase_reject_solution() -> Weight { - (32_508_000 as Weight) + (21_325_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -103,11 +104,11 @@ impl WeightInfo for SubstrateWeight { // Storage: ElectionProviderMultiPhase DesiredTargets (r:0 w:1) // Storage: ElectionProviderMultiPhase Snapshot (r:0 w:1) fn create_snapshot_internal(v: u32, t: u32, ) -> Weight { - (96_001_000 as Weight) + (0 as Weight) // Standard Error: 1_000 - .saturating_add((307_000 as Weight).saturating_mul(v as Weight)) - // Standard Error: 2_000 - .saturating_add((133_000 as Weight).saturating_mul(t as Weight)) + .saturating_add((216_000 as Weight).saturating_mul(v as Weight)) + // Standard Error: 3_000 + .saturating_add((51_000 as Weight).saturating_mul(t as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } // Storage: ElectionProviderMultiPhase SignedSubmissionIndices (r:1 w:1) @@ -120,11 +121,11 @@ impl WeightInfo for SubstrateWeight { // Storage: ElectionProviderMultiPhase Snapshot (r:0 w:1) // Storage: ElectionProviderMultiPhase CurrentPhase (r:0 w:1) fn elect_queued(a: u32, d: u32, ) -> Weight { - (100_505_000 as Weight) - // Standard Error: 6_000 - .saturating_add((1_665_000 as Weight).saturating_mul(a as Weight)) - // Standard Error: 10_000 - .saturating_add((443_000 as Weight).saturating_mul(d as Weight)) + (38_368_000 as Weight) + // Standard Error: 4_000 + .saturating_add((1_414_000 as Weight).saturating_mul(a as Weight)) + // Standard Error: 7_000 + .saturating_add((175_000 as Weight).saturating_mul(d as Weight)) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(8 as Weight)) } @@ -135,9 +136,9 @@ impl WeightInfo for SubstrateWeight { // Storage: ElectionProviderMultiPhase SignedSubmissionNextIndex (r:1 w:1) // Storage: ElectionProviderMultiPhase SignedSubmissionsMap (r:0 w:1) fn submit(c: u32, ) -> Weight { - (74_088_000 as Weight) - // Standard Error: 59_000 - .saturating_add((187_000 as Weight).saturating_mul(c as Weight)) + (39_488_000 as Weight) + // Standard Error: 22_000 + .saturating_add((230_000 as Weight).saturating_mul(c as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -150,14 +151,14 @@ impl WeightInfo for SubstrateWeight { // Storage: ElectionProviderMultiPhase Snapshot (r:1 w:0) fn submit_unsigned(v: u32, t: u32, a: u32, d: u32, ) -> Weight { (0 as Weight) + // Standard Error: 2_000 + .saturating_add((1_544_000 as Weight).saturating_mul(v as Weight)) // Standard Error: 5_000 - .saturating_add((1_970_000 as Weight).saturating_mul(v as Weight)) - // Standard Error: 10_000 - .saturating_add((173_000 as Weight).saturating_mul(t as Weight)) - // Standard Error: 18_000 - .saturating_add((9_783_000 as Weight).saturating_mul(a as Weight)) - // Standard Error: 27_000 - .saturating_add((2_224_000 as Weight).saturating_mul(d as Weight)) + .saturating_add((60_000 as Weight).saturating_mul(t as Weight)) + // Standard Error: 9_000 + .saturating_add((6_555_000 as Weight).saturating_mul(a as Weight)) + // Standard Error: 14_000 + .saturating_add((1_318_000 as Weight).saturating_mul(d as Weight)) .saturating_add(T::DbWeight::get().reads(7 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -168,13 +169,13 @@ impl WeightInfo for SubstrateWeight { fn feasibility_check(v: u32, t: u32, a: u32, d: u32, ) -> Weight { (0 as Weight) // Standard Error: 3_000 - .saturating_add((1_910_000 as Weight).saturating_mul(v as Weight)) - // Standard Error: 7_000 - .saturating_add((111_000 as Weight).saturating_mul(t as Weight)) - // Standard Error: 13_000 - .saturating_add((7_741_000 as Weight).saturating_mul(a as Weight)) - // Standard Error: 19_000 - .saturating_add((1_844_000 as Weight).saturating_mul(d as Weight)) + .saturating_add((1_527_000 as Weight).saturating_mul(v as Weight)) + // Standard Error: 6_000 + .saturating_add((151_000 as Weight).saturating_mul(t as Weight)) + // Standard Error: 10_000 + .saturating_add((5_433_000 as Weight).saturating_mul(a as Weight)) + // Standard Error: 15_000 + .saturating_add((1_420_000 as Weight).saturating_mul(d as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) } } @@ -190,33 +191,33 @@ impl WeightInfo for () { // Storage: Staking ForceEra (r:1 w:0) // Storage: ElectionProviderMultiPhase CurrentPhase (r:1 w:0) fn on_initialize_nothing() -> Weight { - (22_784_000 as Weight) + (12_763_000 as Weight) .saturating_add(RocksDbWeight::get().reads(8 as Weight)) } // Storage: ElectionProviderMultiPhase Round (r:1 w:0) // Storage: ElectionProviderMultiPhase CurrentPhase (r:0 w:1) fn on_initialize_open_signed() -> Weight { - (32_763_000 as Weight) + (13_195_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: ElectionProviderMultiPhase Round (r:1 w:0) // Storage: ElectionProviderMultiPhase CurrentPhase (r:0 w:1) fn on_initialize_open_unsigned() -> Weight { - (29_117_000 as Weight) + (12_782_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: System Account (r:1 w:1) // Storage: ElectionProviderMultiPhase QueuedSolution (r:0 w:1) fn finalize_signed_phase_accept_solution() -> Weight { - (48_996_000 as Weight) + (27_421_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: System Account (r:1 w:1) fn finalize_signed_phase_reject_solution() -> Weight { - (32_508_000 as Weight) + (21_325_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -224,11 +225,11 @@ impl WeightInfo for () { // Storage: ElectionProviderMultiPhase DesiredTargets (r:0 w:1) // Storage: ElectionProviderMultiPhase Snapshot (r:0 w:1) fn create_snapshot_internal(v: u32, t: u32, ) -> Weight { - (96_001_000 as Weight) + (0 as Weight) // Standard Error: 1_000 - .saturating_add((307_000 as Weight).saturating_mul(v as Weight)) - // Standard Error: 2_000 - .saturating_add((133_000 as Weight).saturating_mul(t as Weight)) + .saturating_add((216_000 as Weight).saturating_mul(v as Weight)) + // Standard Error: 3_000 + .saturating_add((51_000 as Weight).saturating_mul(t as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } // Storage: ElectionProviderMultiPhase SignedSubmissionIndices (r:1 w:1) @@ -241,11 +242,11 @@ impl WeightInfo for () { // Storage: ElectionProviderMultiPhase Snapshot (r:0 w:1) // Storage: ElectionProviderMultiPhase CurrentPhase (r:0 w:1) fn elect_queued(a: u32, d: u32, ) -> Weight { - (100_505_000 as Weight) - // Standard Error: 6_000 - .saturating_add((1_665_000 as Weight).saturating_mul(a as Weight)) - // Standard Error: 10_000 - .saturating_add((443_000 as Weight).saturating_mul(d as Weight)) + (38_368_000 as Weight) + // Standard Error: 4_000 + .saturating_add((1_414_000 as Weight).saturating_mul(a as Weight)) + // Standard Error: 7_000 + .saturating_add((175_000 as Weight).saturating_mul(d as Weight)) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(8 as Weight)) } @@ -256,9 +257,9 @@ impl WeightInfo for () { // Storage: ElectionProviderMultiPhase SignedSubmissionNextIndex (r:1 w:1) // Storage: ElectionProviderMultiPhase SignedSubmissionsMap (r:0 w:1) fn submit(c: u32, ) -> Weight { - (74_088_000 as Weight) - // Standard Error: 59_000 - .saturating_add((187_000 as Weight).saturating_mul(c as Weight)) + (39_488_000 as Weight) + // Standard Error: 22_000 + .saturating_add((230_000 as Weight).saturating_mul(c as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } @@ -271,14 +272,14 @@ impl WeightInfo for () { // Storage: ElectionProviderMultiPhase Snapshot (r:1 w:0) fn submit_unsigned(v: u32, t: u32, a: u32, d: u32, ) -> Weight { (0 as Weight) + // Standard Error: 2_000 + .saturating_add((1_544_000 as Weight).saturating_mul(v as Weight)) // Standard Error: 5_000 - .saturating_add((1_970_000 as Weight).saturating_mul(v as Weight)) - // Standard Error: 10_000 - .saturating_add((173_000 as Weight).saturating_mul(t as Weight)) - // Standard Error: 18_000 - .saturating_add((9_783_000 as Weight).saturating_mul(a as Weight)) - // Standard Error: 27_000 - .saturating_add((2_224_000 as Weight).saturating_mul(d as Weight)) + .saturating_add((60_000 as Weight).saturating_mul(t as Weight)) + // Standard Error: 9_000 + .saturating_add((6_555_000 as Weight).saturating_mul(a as Weight)) + // Standard Error: 14_000 + .saturating_add((1_318_000 as Weight).saturating_mul(d as Weight)) .saturating_add(RocksDbWeight::get().reads(7 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -289,13 +290,13 @@ impl WeightInfo for () { fn feasibility_check(v: u32, t: u32, a: u32, d: u32, ) -> Weight { (0 as Weight) // Standard Error: 3_000 - .saturating_add((1_910_000 as Weight).saturating_mul(v as Weight)) - // Standard Error: 7_000 - .saturating_add((111_000 as Weight).saturating_mul(t as Weight)) - // Standard Error: 13_000 - .saturating_add((7_741_000 as Weight).saturating_mul(a as Weight)) - // Standard Error: 19_000 - .saturating_add((1_844_000 as Weight).saturating_mul(d as Weight)) + .saturating_add((1_527_000 as Weight).saturating_mul(v as Weight)) + // Standard Error: 6_000 + .saturating_add((151_000 as Weight).saturating_mul(t as Weight)) + // Standard Error: 10_000 + .saturating_add((5_433_000 as Weight).saturating_mul(a as Weight)) + // Standard Error: 15_000 + .saturating_add((1_420_000 as Weight).saturating_mul(d as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) } } diff --git a/frame/election-provider-support/Cargo.toml b/frame/election-provider-support/Cargo.toml index 1cb477d6c79c7..662762ef63068 100644 --- a/frame/election-provider-support/Cargo.toml +++ b/frame/election-provider-support/Cargo.toml @@ -23,9 +23,9 @@ frame-system = { version = "4.0.0-dev", default-features = false, path = "../sys [dev-dependencies] sp-npos-elections = { version = "4.0.0-dev", path = "../../primitives/npos-elections" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } [features] default = ["std"] diff --git a/frame/election-provider-support/src/lib.rs b/frame/election-provider-support/src/lib.rs index d10504c88cc67..26efe5107b670 100644 --- a/frame/election-provider-support/src/lib.rs +++ b/frame/election-provider-support/src/lib.rs @@ -80,6 +80,7 @@ //! ```rust //! # use frame_election_provider_support::{*, data_provider}; //! # use sp_npos_elections::{Support, Assignment}; +//! # use frame_support::traits::ConstU32; //! //! type AccountId = u64; //! type Balance = u64; @@ -101,13 +102,13 @@ //! impl ElectionDataProvider for Pallet { //! type AccountId = AccountId; //! type BlockNumber = BlockNumber; -//! const MAXIMUM_VOTES_PER_VOTER: u32 = 1; +//! type MaxVotesPerVoter = ConstU32<1>; //! //! fn desired_targets() -> data_provider::Result { //! Ok(1) //! } //! fn voters(maybe_max_len: Option) -//! -> data_provider::Result)>> +//! -> data_provider::Result>> //! { //! Ok(Default::default()) //! } @@ -166,7 +167,7 @@ #![cfg_attr(not(feature = "std"), no_std)] pub mod onchain; -use frame_support::traits::Get; +use frame_support::{traits::Get, BoundedVec}; use sp_std::{fmt::Debug, prelude::*}; /// Re-export some type as they are used in the interface. @@ -191,7 +192,7 @@ pub trait ElectionDataProvider { type BlockNumber; /// Maximum number of votes per voter that this data provider is providing. - const MAXIMUM_VOTES_PER_VOTER: u32; + type MaxVotesPerVoter: Get; /// All possible targets for the election, i.e. the candidates. /// @@ -211,9 +212,7 @@ pub trait ElectionDataProvider { /// /// This should be implemented as a self-weighing function. The implementor should register its /// appropriate weight at the end of execution with the system pallet directly. - fn voters( - maybe_max_len: Option, - ) -> data_provider::Result)>>; + fn voters(maybe_max_len: Option) -> data_provider::Result>>; /// The number of targets to elect. /// @@ -233,7 +232,7 @@ pub trait ElectionDataProvider { /// else a noop. #[cfg(any(feature = "runtime-benchmarks", test))] fn put_snapshot( - _voters: Vec<(Self::AccountId, VoteWeight, Vec)>, + _voters: Vec>, _targets: Vec, _target_stake: Option, ) { @@ -244,7 +243,12 @@ pub trait ElectionDataProvider { /// /// Same as `put_snapshot`, but can add a single voter one by one. #[cfg(any(feature = "runtime-benchmarks", test))] - fn add_voter(_voter: Self::AccountId, _weight: VoteWeight, _targets: Vec) {} + fn add_voter( + _voter: Self::AccountId, + _weight: VoteWeight, + _targets: BoundedVec, + ) { + } /// Utility function only to be used in benchmarking scenarios, to be implemented optionally, /// else a noop. @@ -266,19 +270,20 @@ pub struct TestDataProvider(sp_std::marker::PhantomData); impl ElectionDataProvider for TestDataProvider<(AccountId, BlockNumber)> { type AccountId = AccountId; type BlockNumber = BlockNumber; + type MaxVotesPerVoter = (); - const MAXIMUM_VOTES_PER_VOTER: u32 = 0; fn targets(_maybe_max_len: Option) -> data_provider::Result> { Ok(Default::default()) } - fn voters( - _maybe_max_len: Option, - ) -> data_provider::Result)>> { + + fn voters(_maybe_max_len: Option) -> data_provider::Result>> { Ok(Default::default()) } + fn desired_targets() -> data_provider::Result { Ok(Default::default()) } + fn next_election_prediction(now: BlockNumber) -> BlockNumber { now } @@ -314,6 +319,22 @@ pub trait ElectionProvider { fn elect() -> Result, Self::Error>; } +/// A sub-trait of the [`ElectionProvider`] for cases where we need to be sure an election needs to +/// happen instantly, not asynchronously. +/// +/// The same `DataProvider` is assumed to be used. +/// +/// Consequently, allows for control over the amount of data that is being fetched from the +/// [`ElectionProvider::DataProvider`]. +pub trait InstantElectionProvider: ElectionProvider { + /// Elect a new set of winners, instantly, with the given given limits set on the + /// `DataProvider`. + fn instant_elect( + maybe_max_voters: Option, + maybe_max_targets: Option, + ) -> Result, Self::Error>; +} + /// An election provider to be used only for testing. #[cfg(feature = "std")] pub struct NoElection(sp_std::marker::PhantomData); @@ -343,7 +364,7 @@ impl ElectionProvider for NoElection<(AccountId, BlockNu /// used on the implementing side of [`ElectionDataProvider`]. pub trait SortedListProvider { /// The list's error type. - type Error; + type Error: sp_std::fmt::Debug; /// An iterator over the list, which can have `take` called on it. fn iter() -> Box>; @@ -421,7 +442,7 @@ pub trait NposSolver { fn solve( to_elect: usize, targets: Vec, - voters: Vec<(Self::AccountId, VoteWeight, Vec)>, + voters: Vec<(Self::AccountId, VoteWeight, impl IntoIterator)>, ) -> Result, Self::Error>; } @@ -443,7 +464,7 @@ impl< fn solve( winners: usize, targets: Vec, - voters: Vec<(Self::AccountId, VoteWeight, Vec)>, + voters: Vec<(Self::AccountId, VoteWeight, impl IntoIterator)>, ) -> Result, Self::Error> { sp_npos_elections::seq_phragmen(winners, targets, voters, Balancing::get()) } @@ -467,8 +488,15 @@ impl< fn solve( winners: usize, targets: Vec, - voters: Vec<(Self::AccountId, VoteWeight, Vec)>, + voters: Vec<(Self::AccountId, VoteWeight, impl IntoIterator)>, ) -> Result, Self::Error> { sp_npos_elections::phragmms(winners, targets, voters, Balancing::get()) } } + +/// A voter, at the level of abstraction of this crate. +pub type Voter = (AccountId, VoteWeight, BoundedVec); + +/// Same as [`Voter`], but parameterized by an [`ElectionDataProvider`]. +pub type VoterOf = + Voter<::AccountId, ::MaxVotesPerVoter>; diff --git a/frame/election-provider-support/src/onchain.rs b/frame/election-provider-support/src/onchain.rs index d325daf514757..41245f67fb02c 100644 --- a/frame/election-provider-support/src/onchain.rs +++ b/frame/election-provider-support/src/onchain.rs @@ -17,7 +17,7 @@ //! An implementation of [`ElectionProvider`] that does an on-chain sequential phragmen. -use crate::{ElectionDataProvider, ElectionProvider}; +use crate::{ElectionDataProvider, ElectionProvider, InstantElectionProvider}; use frame_support::{traits::Get, weights::DispatchClass}; use sp_npos_elections::*; use sp_std::{collections::btree_map::BTreeMap, marker::PhantomData, prelude::*}; @@ -47,8 +47,14 @@ impl From for Error { /// implementation ignores the additional data of the election data provider and gives no insight on /// how much weight was consumed. /// -/// Finally, this implementation does not impose any limits on the number of voters and targets that -/// are provided. +/// Finally, the [`ElectionProvider`] implementation of this type does not impose any limits on the +/// number of voters and targets that are fetched. This could potentially make this unsuitable for +/// execution onchain. On the other hand, the [`InstantElectionProvider`] implementation does limit +/// these inputs. +/// +/// It is advisable to use the former ([`ElectionProvider::elect`]) only at genesis, or for testing, +/// the latter [`InstantElectionProvider::instant_elect`] for onchain operations, with thoughtful +/// bounds. pub struct OnChainSequentialPhragmen(PhantomData); /// Configuration trait of [`OnChainSequentialPhragmen`]. @@ -68,16 +74,17 @@ pub trait Config: frame_system::Config { >; } -impl ElectionProvider for OnChainSequentialPhragmen { - type AccountId = T::AccountId; - type BlockNumber = T::BlockNumber; - type Error = Error; - type DataProvider = T::DataProvider; - - fn elect() -> Result, Self::Error> { - let voters = Self::DataProvider::voters(None).map_err(Error::DataProvider)?; - let targets = Self::DataProvider::targets(None).map_err(Error::DataProvider)?; - let desired_targets = Self::DataProvider::desired_targets().map_err(Error::DataProvider)?; +impl OnChainSequentialPhragmen { + fn elect_with( + maybe_max_voters: Option, + maybe_max_targets: Option, + ) -> Result, Error> { + let voters = ::DataProvider::voters(maybe_max_voters) + .map_err(Error::DataProvider)?; + let targets = ::DataProvider::targets(maybe_max_targets) + .map_err(Error::DataProvider)?; + let desired_targets = ::DataProvider::desired_targets() + .map_err(Error::DataProvider)?; let stake_map: BTreeMap = voters .iter() @@ -87,9 +94,8 @@ impl ElectionProvider for OnChainSequentialPhragmen { let stake_of = |w: &T::AccountId| -> VoteWeight { stake_map.get(w).cloned().unwrap_or_default() }; - let ElectionResult { winners: _, assignments } = - seq_phragmen::<_, T::Accuracy>(desired_targets as usize, targets, voters, None) - .map_err(Error::from)?; + let ElectionResult::<_, T::Accuracy> { winners: _, assignments } = + seq_phragmen(desired_targets as usize, targets, voters, None).map_err(Error::from)?; let staked = assignment_ratio_to_staked_normalized(assignments, &stake_of)?; @@ -103,6 +109,26 @@ impl ElectionProvider for OnChainSequentialPhragmen { } } +impl ElectionProvider for OnChainSequentialPhragmen { + type AccountId = T::AccountId; + type BlockNumber = T::BlockNumber; + type Error = Error; + type DataProvider = T::DataProvider; + + fn elect() -> Result, Self::Error> { + Self::elect_with(None, None) + } +} + +impl InstantElectionProvider for OnChainSequentialPhragmen { + fn instant_elect( + maybe_max_voters: Option, + maybe_max_targets: Option, + ) -> Result, Self::Error> { + Self::elect_with(maybe_max_voters, maybe_max_targets) + } +} + #[cfg(test)] mod tests { use super::*; @@ -161,18 +187,22 @@ mod tests { type OnChainPhragmen = OnChainSequentialPhragmen; mod mock_data_provider { + use frame_support::{bounded_vec, traits::ConstU32}; + use super::*; - use crate::data_provider; + use crate::{data_provider, VoterOf}; pub struct DataProvider; impl ElectionDataProvider for DataProvider { type AccountId = AccountId; type BlockNumber = BlockNumber; - const MAXIMUM_VOTES_PER_VOTER: u32 = 2; - fn voters( - _: Option, - ) -> data_provider::Result)>> { - Ok(vec![(1, 10, vec![10, 20]), (2, 20, vec![30, 20]), (3, 30, vec![10, 30])]) + type MaxVotesPerVoter = ConstU32<2>; + fn voters(_: Option) -> data_provider::Result>> { + Ok(vec![ + (1, 10, bounded_vec![10, 20]), + (2, 20, bounded_vec![30, 20]), + (3, 30, bounded_vec![10, 30]), + ]) } fn targets(_: Option) -> data_provider::Result> { diff --git a/frame/elections-phragmen/Cargo.toml b/frame/elections-phragmen/Cargo.toml index 867b1627272a7..f70eb568349b4 100644 --- a/frame/elections-phragmen/Cargo.toml +++ b/frame/elections-phragmen/Cargo.toml @@ -17,19 +17,19 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = "derive", ] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-npos-elections = { version = "4.0.0-dev", default-features = false, path = "../../primitives/npos-elections" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } log = { version = "0.4.14", default-features = false } [dev-dependencies] pallet-balances = { version = "4.0.0-dev", path = "../balances" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } substrate-test-utils = { version = "4.0.0-dev", path = "../../test-utils" } [features] diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 7f576144d1368..4758c793cfefd 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -102,9 +102,9 @@ use codec::{Decode, Encode}; use frame_support::{ dispatch::WithPostDispatchInfo, traits::{ - ChangeMembers, Contains, ContainsLengthBound, Currency, CurrencyToVote, Get, - InitializeMembers, LockIdentifier, LockableCurrency, OnUnbalanced, ReservableCurrency, - SortedMembers, StorageVersion, WithdrawReasons, + defensive_prelude::*, ChangeMembers, Contains, ContainsLengthBound, Currency, + CurrencyToVote, Get, InitializeMembers, LockIdentifier, LockableCurrency, OnUnbalanced, + ReservableCurrency, SortedMembers, StorageVersion, WithdrawReasons, }, weights::Weight, }; @@ -926,13 +926,13 @@ impl Pallet { let weight_candidates = candidates_and_deposit.len() as u32; let weight_voters = voters_and_votes.len() as u32; let weight_edges = num_edges; - let _ = sp_npos_elections::seq_phragmen::( + let _ = sp_npos_elections::seq_phragmen( num_to_elect, candidate_ids, voters_and_votes.clone(), None, ) - .map(|ElectionResult { winners, assignments: _ }| { + .map(|ElectionResult:: { winners, assignments: _ }| { // this is already sorted by id. let old_members_ids_sorted = >::take().into_iter().map(|m| m.who).collect::>(); @@ -1028,7 +1028,7 @@ impl Pallet { candidates_and_deposit .iter() .find_map(|(c, d)| if c == x { Some(*d) } else { None }) - .unwrap_or_default() + .defensive_unwrap_or_default() }; // fetch deposits from the one recorded one. This will make sure that a candidate who // submitted candidacy before a change to candidacy deposit will have the correct amount @@ -1132,7 +1132,7 @@ mod tests { use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, - BuildStorage, + BuildStorage, ModuleError, }; use substrate_test_utils::assert_eq_uvec; @@ -2514,7 +2514,7 @@ mod tests { let unwrapped_error = Elections::remove_member(Origin::root(), 4, true).unwrap_err(); assert!(matches!( unwrapped_error.error, - DispatchError::Module { message: Some("InvalidReplacement"), .. } + DispatchError::Module(ModuleError { message: Some("InvalidReplacement"), .. }) )); assert!(unwrapped_error.post_info.actual_weight.is_some()); }); @@ -2537,7 +2537,7 @@ mod tests { let unwrapped_error = Elections::remove_member(Origin::root(), 4, false).unwrap_err(); assert!(matches!( unwrapped_error.error, - DispatchError::Module { message: Some("InvalidReplacement"), .. } + DispatchError::Module(ModuleError { message: Some("InvalidReplacement"), .. }) )); assert!(unwrapped_error.post_info.actual_weight.is_some()); }); diff --git a/frame/elections-phragmen/src/weights.rs b/frame/elections-phragmen/src/weights.rs index 0bfc3d2ea87a7..22c1c1cbeb406 100644 --- a/frame/elections-phragmen/src/weights.rs +++ b/frame/elections-phragmen/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_elections_phragmen //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-30, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/elections-phragmen/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -53,8 +54,8 @@ pub trait WeightInfo { fn renounce_candidacy_candidate(c: u32, ) -> Weight; fn renounce_candidacy_members() -> Weight; fn renounce_candidacy_runners_up() -> Weight; - fn remove_member_with_replacement() -> Weight; fn remove_member_without_replacement() -> Weight; + fn remove_member_with_replacement() -> Weight; fn remove_member_wrong_refund() -> Weight; fn clean_defunct_voters(v: u32, d: u32, ) -> Weight; fn election_phragmen(c: u32, v: u32, e: u32, ) -> Weight; @@ -69,9 +70,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Elections Voting (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vote_equal(v: u32, ) -> Weight { - (42_509_000 as Weight) - // Standard Error: 4_000 - .saturating_add((372_000 as Weight).saturating_mul(v as Weight)) + (23_406_000 as Weight) + // Standard Error: 6_000 + .saturating_add((270_000 as Weight).saturating_mul(v as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -81,9 +82,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Elections Voting (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vote_more(v: u32, ) -> Weight { - (65_311_000 as Weight) + (35_660_000 as Weight) // Standard Error: 6_000 - .saturating_add((419_000 as Weight).saturating_mul(v as Weight)) + .saturating_add((316_000 as Weight).saturating_mul(v as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -93,16 +94,16 @@ impl WeightInfo for SubstrateWeight { // Storage: Elections Voting (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vote_less(v: u32, ) -> Weight { - (65_444_000 as Weight) - // Standard Error: 5_000 - .saturating_add((376_000 as Weight).saturating_mul(v as Weight)) + (35_999_000 as Weight) + // Standard Error: 6_000 + .saturating_add((299_000 as Weight).saturating_mul(v as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Elections Voting (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn remove_voter() -> Weight { - (61_585_000 as Weight) + (33_692_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -110,53 +111,54 @@ impl WeightInfo for SubstrateWeight { // Storage: Elections Members (r:1 w:0) // Storage: Elections RunnersUp (r:1 w:0) fn submit_candidacy(c: u32, ) -> Weight { - (53_333_000 as Weight) + (35_506_000 as Weight) // Standard Error: 1_000 - .saturating_add((267_000 as Weight).saturating_mul(c as Weight)) + .saturating_add((192_000 as Weight).saturating_mul(c as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Elections Candidates (r:1 w:1) fn renounce_candidacy_candidate(c: u32, ) -> Weight { - (49_128_000 as Weight) + (31_402_000 as Weight) // Standard Error: 1_000 - .saturating_add((144_000 as Weight).saturating_mul(c as Weight)) + .saturating_add((113_000 as Weight).saturating_mul(c as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Elections Members (r:1 w:1) // Storage: Elections RunnersUp (r:1 w:1) - // Storage: Instance1Collective Prime (r:1 w:1) - // Storage: Instance1Collective Proposals (r:1 w:0) - // Storage: Instance1Collective Members (r:0 w:1) + // Storage: Council Prime (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: Council Members (r:0 w:1) fn renounce_candidacy_members() -> Weight { - (70_685_000 as Weight) + (42_727_000 as Weight) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } // Storage: Elections RunnersUp (r:1 w:1) fn renounce_candidacy_runners_up() -> Weight { - (49_766_000 as Weight) + (30_638_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } + // Storage: Benchmark Override (r:0 w:0) + fn remove_member_without_replacement() -> Weight { + (2_000_000_000_000 as Weight) + } // Storage: Elections RunnersUp (r:1 w:1) // Storage: Elections Members (r:1 w:1) // Storage: System Account (r:1 w:1) - // Storage: Instance1Collective Prime (r:1 w:1) - // Storage: Instance1Collective Proposals (r:1 w:0) - // Storage: Instance1Collective Members (r:0 w:1) + // Storage: Council Prime (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: Council Members (r:0 w:1) fn remove_member_with_replacement() -> Weight { - (76_153_000 as Weight) + (49_317_000 as Weight) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(5 as Weight)) } - fn remove_member_without_replacement() -> Weight { - T::BlockWeights::get().max_block - } // Storage: Elections RunnersUp (r:1 w:0) fn remove_member_wrong_refund() -> Weight { - (6_697_000 as Weight) + (4_688_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) } // Storage: Elections Voting (r:251 w:250) @@ -167,8 +169,8 @@ impl WeightInfo for SubstrateWeight { // Storage: System Account (r:250 w:250) fn clean_defunct_voters(v: u32, _d: u32, ) -> Weight { (0 as Weight) - // Standard Error: 60_000 - .saturating_add((107_467_000 as Weight).saturating_mul(v as Weight)) + // Standard Error: 36_000 + .saturating_add((51_016_000 as Weight).saturating_mul(v as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(v as Weight))) .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(v as Weight))) @@ -177,19 +179,19 @@ impl WeightInfo for SubstrateWeight { // Storage: Elections Members (r:1 w:1) // Storage: Elections RunnersUp (r:1 w:1) // Storage: Elections Voting (r:502 w:0) - // Storage: Instance1Collective Proposals (r:1 w:0) + // Storage: Council Proposals (r:1 w:0) // Storage: Elections ElectionRounds (r:1 w:1) - // Storage: Instance1Collective Members (r:0 w:1) - // Storage: Instance1Collective Prime (r:0 w:1) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) // Storage: System Account (r:2 w:2) fn election_phragmen(c: u32, v: u32, e: u32, ) -> Weight { (0 as Weight) - // Standard Error: 1_846_000 - .saturating_add((39_843_000 as Weight).saturating_mul(c as Weight)) - // Standard Error: 768_000 - .saturating_add((60_623_000 as Weight).saturating_mul(v as Weight)) - // Standard Error: 52_000 - .saturating_add((3_884_000 as Weight).saturating_mul(e as Weight)) + // Standard Error: 1_760_000 + .saturating_add((29_569_000 as Weight).saturating_mul(c as Weight)) + // Standard Error: 732_000 + .saturating_add((51_842_000 as Weight).saturating_mul(v as Weight)) + // Standard Error: 49_000 + .saturating_add((3_546_000 as Weight).saturating_mul(e as Weight)) .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(v as Weight))) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(c as Weight))) @@ -204,9 +206,9 @@ impl WeightInfo for () { // Storage: Elections Voting (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vote_equal(v: u32, ) -> Weight { - (42_509_000 as Weight) - // Standard Error: 4_000 - .saturating_add((372_000 as Weight).saturating_mul(v as Weight)) + (23_406_000 as Weight) + // Standard Error: 6_000 + .saturating_add((270_000 as Weight).saturating_mul(v as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -216,9 +218,9 @@ impl WeightInfo for () { // Storage: Elections Voting (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vote_more(v: u32, ) -> Weight { - (65_311_000 as Weight) + (35_660_000 as Weight) // Standard Error: 6_000 - .saturating_add((419_000 as Weight).saturating_mul(v as Weight)) + .saturating_add((316_000 as Weight).saturating_mul(v as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -228,16 +230,16 @@ impl WeightInfo for () { // Storage: Elections Voting (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vote_less(v: u32, ) -> Weight { - (65_444_000 as Weight) - // Standard Error: 5_000 - .saturating_add((376_000 as Weight).saturating_mul(v as Weight)) + (35_999_000 as Weight) + // Standard Error: 6_000 + .saturating_add((299_000 as Weight).saturating_mul(v as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Elections Voting (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn remove_voter() -> Weight { - (61_585_000 as Weight) + (33_692_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -245,55 +247,54 @@ impl WeightInfo for () { // Storage: Elections Members (r:1 w:0) // Storage: Elections RunnersUp (r:1 w:0) fn submit_candidacy(c: u32, ) -> Weight { - (53_333_000 as Weight) + (35_506_000 as Weight) // Standard Error: 1_000 - .saturating_add((267_000 as Weight).saturating_mul(c as Weight)) + .saturating_add((192_000 as Weight).saturating_mul(c as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Elections Candidates (r:1 w:1) fn renounce_candidacy_candidate(c: u32, ) -> Weight { - (49_128_000 as Weight) + (31_402_000 as Weight) // Standard Error: 1_000 - .saturating_add((144_000 as Weight).saturating_mul(c as Weight)) + .saturating_add((113_000 as Weight).saturating_mul(c as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Elections Members (r:1 w:1) // Storage: Elections RunnersUp (r:1 w:1) - // Storage: Instance1Collective Prime (r:1 w:1) - // Storage: Instance1Collective Proposals (r:1 w:0) - // Storage: Instance1Collective Members (r:0 w:1) + // Storage: Council Prime (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: Council Members (r:0 w:1) fn renounce_candidacy_members() -> Weight { - (70_685_000 as Weight) + (42_727_000 as Weight) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } // Storage: Elections RunnersUp (r:1 w:1) fn renounce_candidacy_runners_up() -> Weight { - (49_766_000 as Weight) + (30_638_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } + // Storage: Benchmark Override (r:0 w:0) + fn remove_member_without_replacement() -> Weight { + (2_000_000_000_000 as Weight) + } // Storage: Elections RunnersUp (r:1 w:1) // Storage: Elections Members (r:1 w:1) // Storage: System Account (r:1 w:1) - // Storage: Instance1Collective Prime (r:1 w:1) - // Storage: Instance1Collective Proposals (r:1 w:0) - // Storage: Instance1Collective Members (r:0 w:1) + // Storage: Council Prime (r:1 w:1) + // Storage: Council Proposals (r:1 w:0) + // Storage: Council Members (r:0 w:1) fn remove_member_with_replacement() -> Weight { - (76_153_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(5 as Weight)) - } - fn remove_member_without_replacement() -> Weight { - (76_153_000 as Weight) + (49_317_000 as Weight) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(5 as Weight)) } // Storage: Elections RunnersUp (r:1 w:0) fn remove_member_wrong_refund() -> Weight { - (6_697_000 as Weight) + (4_688_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) } // Storage: Elections Voting (r:251 w:250) @@ -304,8 +305,8 @@ impl WeightInfo for () { // Storage: System Account (r:250 w:250) fn clean_defunct_voters(v: u32, _d: u32, ) -> Weight { (0 as Weight) - // Standard Error: 60_000 - .saturating_add((107_467_000 as Weight).saturating_mul(v as Weight)) + // Standard Error: 36_000 + .saturating_add((51_016_000 as Weight).saturating_mul(v as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(v as Weight))) .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(v as Weight))) @@ -314,19 +315,19 @@ impl WeightInfo for () { // Storage: Elections Members (r:1 w:1) // Storage: Elections RunnersUp (r:1 w:1) // Storage: Elections Voting (r:502 w:0) - // Storage: Instance1Collective Proposals (r:1 w:0) + // Storage: Council Proposals (r:1 w:0) // Storage: Elections ElectionRounds (r:1 w:1) - // Storage: Instance1Collective Members (r:0 w:1) - // Storage: Instance1Collective Prime (r:0 w:1) + // Storage: Council Members (r:0 w:1) + // Storage: Council Prime (r:0 w:1) // Storage: System Account (r:2 w:2) fn election_phragmen(c: u32, v: u32, e: u32, ) -> Weight { (0 as Weight) - // Standard Error: 1_846_000 - .saturating_add((39_843_000 as Weight).saturating_mul(c as Weight)) - // Standard Error: 768_000 - .saturating_add((60_623_000 as Weight).saturating_mul(v as Weight)) - // Standard Error: 52_000 - .saturating_add((3_884_000 as Weight).saturating_mul(e as Weight)) + // Standard Error: 1_760_000 + .saturating_add((29_569_000 as Weight).saturating_mul(c as Weight)) + // Standard Error: 732_000 + .saturating_add((51_842_000 as Weight).saturating_mul(v as Weight)) + // Standard Error: 49_000 + .saturating_add((3_546_000 as Weight).saturating_mul(e as Weight)) .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(c as Weight))) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(v as Weight))) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(c as Weight))) diff --git a/frame/examples/basic/Cargo.toml b/frame/examples/basic/Cargo.toml index 894b9b4d5010d..73c11475fdf61 100644 --- a/frame/examples/basic/Cargo.toml +++ b/frame/examples/basic/Cargo.toml @@ -21,12 +21,12 @@ frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = " frame-support = { version = "4.0.0-dev", default-features = false, path = "../../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../../system" } pallet-balances = { version = "4.0.0-dev", default-features = false, path = "../../balances" } -sp-io = { version = "4.0.0", default-features = false, path = "../../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } +sp-io = { version = "5.0.0", default-features = false, path = "../../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../../primitives/std" } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core", default-features = false } +sp-core = { version = "5.0.0", path = "../../../primitives/core", default-features = false } [features] default = ["std"] diff --git a/frame/examples/offchain-worker/Cargo.toml b/frame/examples/offchain-worker/Cargo.toml index 68ad2125eef42..e7ae323050ee1 100644 --- a/frame/examples/offchain-worker/Cargo.toml +++ b/frame/examples/offchain-worker/Cargo.toml @@ -20,10 +20,10 @@ scale-info = { version = "1.0", default-features = false, features = ["derive"] frame-support = { version = "4.0.0-dev", default-features = false, path = "../../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../../system" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/core" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/io" } -sp-keystore = { version = "0.10.0", path = "../../../primitives/keystore", optional = true } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../../primitives/io" } +sp-keystore = { version = "0.11.0", path = "../../../primitives/keystore", optional = true } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../../primitives/std" } [features] diff --git a/frame/examples/offchain-worker/src/lib.rs b/frame/examples/offchain-worker/src/lib.rs index 08f449f8d51d0..3cf718217b062 100644 --- a/frame/examples/offchain-worker/src/lib.rs +++ b/frame/examples/offchain-worker/src/lib.rs @@ -154,11 +154,14 @@ pub mod pallet { /// multiple pallets send unsigned transactions. #[pallet::constant] type UnsignedPriority: Get; + + /// Maximum number of prices. + #[pallet::constant] + type MaxPrices: Get; } #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] pub struct Pallet(_); #[pallet::hooks] @@ -330,7 +333,7 @@ pub mod pallet { /// This is used to calculate average price, should have bounded size. #[pallet::storage] #[pallet::getter(fn prices)] - pub(super) type Prices = StorageValue<_, Vec, ValueQuery>; + pub(super) type Prices = StorageValue<_, BoundedVec, ValueQuery>; /// Defines the block when next unsigned transaction will be accepted. /// @@ -645,12 +648,8 @@ impl Pallet { fn add_price(maybe_who: Option, price: u32) { log::info!("Adding to the average: {}", price); >::mutate(|prices| { - const MAX_LEN: usize = 64; - - if prices.len() < MAX_LEN { - prices.push(price); - } else { - prices[price as usize % MAX_LEN] = price; + if prices.try_push(price).is_err() { + prices[(price % T::MaxPrices::get()) as usize] = price; } }); diff --git a/frame/examples/offchain-worker/src/tests.rs b/frame/examples/offchain-worker/src/tests.rs index 76f80deb12f90..e5bd9fabc629b 100644 --- a/frame/examples/offchain-worker/src/tests.rs +++ b/frame/examples/offchain-worker/src/tests.rs @@ -123,6 +123,7 @@ impl Config for Test { type GracePeriod = ConstU64<5>; type UnsignedInterval = ConstU64<128>; type UnsignedPriority = UnsignedPriority; + type MaxPrices = ConstU32<64>; } fn test_pub() -> sp_core::sr25519::Public { diff --git a/frame/examples/parallel/Cargo.toml b/frame/examples/parallel/Cargo.toml index b3ec1a72506b4..8d291df191368 100644 --- a/frame/examples/parallel/Cargo.toml +++ b/frame/examples/parallel/Cargo.toml @@ -17,9 +17,9 @@ scale-info = { version = "1.0", default-features = false, features = ["derive"] frame-support = { version = "4.0.0-dev", default-features = false, path = "../../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../../system" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/core" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../../primitives/std" } sp-tasks = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/tasks" } diff --git a/frame/executive/Cargo.toml b/frame/executive/Cargo.toml index 1b6a237f3b93f..b261aecdf9262 100644 --- a/frame/executive/Cargo.toml +++ b/frame/executive/Cargo.toml @@ -19,16 +19,16 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-tracing = { version = "4.0.0", default-features = false, path = "../../primitives/tracing" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } [dev-dependencies] hex-literal = "0.3.4" -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } pallet-transaction-payment = { version = "4.0.0-dev", path = "../transaction-payment" } sp-version = { version = "4.0.0-dev", path = "../../primitives/version" } diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index 520c3894690c1..d19ea8127bad3 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -665,7 +665,7 @@ mod tests { #[pallet::weight(0)] pub fn calculate_storage_root(_origin: OriginFor) -> DispatchResult { - let root = sp_io::storage::root(); + let root = sp_io::storage::root(sp_runtime::StateVersion::V1); sp_io::storage::set("storage_root".as_bytes(), &root); Ok(()) } diff --git a/frame/gilt/Cargo.toml b/frame/gilt/Cargo.toml index b958b7ba337fe..7ed17d152a01e 100644 --- a/frame/gilt/Cargo.toml +++ b/frame/gilt/Cargo.toml @@ -16,15 +16,15 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-arithmetic = { version = "4.0.0", default-features = false, path = "../../primitives/arithmetic" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } [dev-dependencies] -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } [features] diff --git a/frame/gilt/src/lib.rs b/frame/gilt/src/lib.rs index 6211b15d8c8c3..8956e04857f2c 100644 --- a/frame/gilt/src/lib.rs +++ b/frame/gilt/src/lib.rs @@ -79,7 +79,7 @@ pub mod pallet { pub use crate::weights::WeightInfo; use frame_support::{ pallet_prelude::*, - traits::{Currency, OnUnbalanced, ReservableCurrency}, + traits::{Currency, DefensiveSaturating, OnUnbalanced, ReservableCurrency}, }; use frame_system::pallet_prelude::*; use sp_arithmetic::{PerThing, Perquintill}; @@ -112,7 +112,8 @@ pub mod pallet { + sp_std::fmt::Debug + Default + From - + TypeInfo; + + TypeInfo + + MaxEncodedLen; /// Origin required for setting the target proportion to be under gilt. type AdminOrigin: EnsureOrigin; @@ -178,11 +179,12 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] pub struct Pallet(_); /// A single bid on a gilt, an item of a *queue* in `Queues`. - #[derive(Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo)] + #[derive( + Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen, + )] pub struct GiltBid { /// The amount bid. pub amount: Balance, @@ -191,7 +193,9 @@ pub mod pallet { } /// Information representing an active gilt. - #[derive(Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo)] + #[derive( + Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen, + )] pub struct ActiveGilt { /// The proportion of the effective total issuance (i.e. accounting for any eventual gilt /// expansion or contraction that may eventually be claimed). @@ -215,7 +219,9 @@ pub mod pallet { /// `issuance - frozen + proportion * issuance` /// /// where `issuance = total_issuance - IgnoredIssuance` - #[derive(Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo)] + #[derive( + Clone, Eq, PartialEq, Default, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen, + )] pub struct ActiveGiltsTotal { /// The total amount of funds held in reserve for all active gilts. pub frozen: Balance, @@ -233,12 +239,18 @@ pub mod pallet { /// The vector is indexed by duration in `Period`s, offset by one, so information on the queue /// whose duration is one `Period` would be storage `0`. #[pallet::storage] - pub type QueueTotals = StorageValue<_, Vec<(u32, BalanceOf)>, ValueQuery>; + pub type QueueTotals = + StorageValue<_, BoundedVec<(u32, BalanceOf), T::QueueCount>, ValueQuery>; /// The queues of bids ready to become gilts. Indexed by duration (in `Period`s). #[pallet::storage] - pub type Queues = - StorageMap<_, Blake2_128Concat, u32, Vec, T::AccountId>>, ValueQuery>; + pub type Queues = StorageMap< + _, + Blake2_128Concat, + u32, + BoundedVec, T::AccountId>, T::MaxQueueLen>, + ValueQuery, + >; /// Information relating to the gilts currently active. #[pallet::storage] @@ -265,7 +277,11 @@ pub mod pallet { #[pallet::genesis_build] impl GenesisBuild for GenesisConfig { fn build(&self) { - QueueTotals::::put(vec![(0, BalanceOf::::zero()); T::QueueCount::get() as usize]); + let unbounded = vec![(0, BalanceOf::::zero()); T::QueueCount::get() as usize]; + let bounded: BoundedVec<_, _> = unbounded + .try_into() + .expect("QueueTotals should support up to QueueCount items. qed"); + QueueTotals::::put(bounded); } } @@ -366,7 +382,7 @@ pub mod pallet { T::Currency::unreserve(&bid.who, bid.amount); (0, amount - bid.amount) } else { - q.insert(0, bid); + q.try_insert(0, bid).expect("verified queue was not full above. qed."); (1, amount) }; @@ -379,7 +395,7 @@ pub mod pallet { }, )?; QueueTotals::::mutate(|qs| { - qs.resize(queue_count, (0, Zero::zero())); + qs.bounded_resize(queue_count, (0, Zero::zero())); qs[queue_index].0 += net.0; qs[queue_index].1 = qs[queue_index].1.saturating_add(net.1); }); @@ -415,7 +431,7 @@ pub mod pallet { })?; QueueTotals::::mutate(|qs| { - qs.resize(queue_count, (0, Zero::zero())); + qs.bounded_resize(queue_count, (0, Zero::zero())); qs[queue_index].0 = new_len; qs[queue_index].1 = qs[queue_index].1.saturating_sub(bid.amount); }); @@ -592,17 +608,20 @@ pub mod pallet { if remaining < bid.amount { let overflow = bid.amount - remaining; bid.amount = remaining; - q.push(GiltBid { amount: overflow, who: bid.who.clone() }); + q.try_push(GiltBid { amount: overflow, who: bid.who.clone() }) + .expect("just popped, so there must be space. qed"); } let amount = bid.amount; // Can never overflow due to block above. remaining -= amount; // Should never underflow since it should track the total of the // bids exactly, but we'll be defensive. - qs[queue_index].1 = qs[queue_index].1.saturating_sub(bid.amount); + qs[queue_index].1 = + qs[queue_index].1.defensive_saturating_sub(bid.amount); // Now to activate the bid... - let nongilt_issuance = total_issuance.saturating_sub(totals.frozen); + let nongilt_issuance = + total_issuance.defensive_saturating_sub(totals.frozen); let effective_issuance = totals .proportion .left_from_one() @@ -613,7 +632,8 @@ pub mod pallet { let who = bid.who; let index = totals.index; totals.frozen += bid.amount; - totals.proportion = totals.proportion.saturating_add(proportion); + totals.proportion = + totals.proportion.defensive_saturating_add(proportion); totals.index += 1; let e = Event::GiltIssued { index, expiry, who: who.clone(), amount }; diff --git a/frame/gilt/src/weights.rs b/frame/gilt/src/weights.rs index fd4dcd1b5d5ae..6084d494c5c3a 100644 --- a/frame/gilt/src/weights.rs +++ b/frame/gilt/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_gilt //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/gilt/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -61,44 +62,44 @@ impl WeightInfo for SubstrateWeight { // Storage: Gilt Queues (r:1 w:1) // Storage: Gilt QueueTotals (r:1 w:1) fn place_bid(l: u32, ) -> Weight { - (59_219_000 as Weight) + (32_753_000 as Weight) // Standard Error: 0 - .saturating_add((156_000 as Weight).saturating_mul(l as Weight)) + .saturating_add((96_000 as Weight).saturating_mul(l as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Gilt Queues (r:1 w:1) // Storage: Gilt QueueTotals (r:1 w:1) fn place_bid_max() -> Weight { - (184_943_000 as Weight) + (124_814_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Gilt Queues (r:1 w:1) // Storage: Gilt QueueTotals (r:1 w:1) fn retract_bid(l: u32, ) -> Weight { - (59_352_000 as Weight) + (33_544_000 as Weight) // Standard Error: 0 - .saturating_add((129_000 as Weight).saturating_mul(l as Weight)) + .saturating_add((86_000 as Weight).saturating_mul(l as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Gilt ActiveTotal (r:1 w:1) fn set_target() -> Weight { - (5_444_000 as Weight) + (2_648_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Gilt Active (r:1 w:1) // Storage: Gilt ActiveTotal (r:1 w:1) fn thaw() -> Weight { - (71_399_000 as Weight) + (41_549_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Gilt ActiveTotal (r:1 w:0) fn pursue_target_noop() -> Weight { - (3_044_000 as Weight) + (1_583_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) } // Storage: Gilt ActiveTotal (r:1 w:1) @@ -106,9 +107,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Gilt Queues (r:1 w:1) // Storage: Gilt Active (r:0 w:1) fn pursue_target_per_item(b: u32, ) -> Weight { - (54_478_000 as Weight) - // Standard Error: 2_000 - .saturating_add((10_150_000 as Weight).saturating_mul(b as Weight)) + (35_836_000 as Weight) + // Standard Error: 1_000 + .saturating_add((4_008_000 as Weight).saturating_mul(b as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(b as Weight))) @@ -118,9 +119,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Gilt Queues (r:1 w:1) // Storage: Gilt Active (r:0 w:1) fn pursue_target_per_queue(q: u32, ) -> Weight { - (20_099_000 as Weight) - // Standard Error: 7_000 - .saturating_add((16_603_000 as Weight).saturating_mul(q as Weight)) + (12_139_000 as Weight) + // Standard Error: 6_000 + .saturating_add((7_819_000 as Weight).saturating_mul(q as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(q as Weight))) .saturating_add(T::DbWeight::get().writes(2 as Weight)) @@ -133,44 +134,44 @@ impl WeightInfo for () { // Storage: Gilt Queues (r:1 w:1) // Storage: Gilt QueueTotals (r:1 w:1) fn place_bid(l: u32, ) -> Weight { - (59_219_000 as Weight) + (32_753_000 as Weight) // Standard Error: 0 - .saturating_add((156_000 as Weight).saturating_mul(l as Weight)) + .saturating_add((96_000 as Weight).saturating_mul(l as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Gilt Queues (r:1 w:1) // Storage: Gilt QueueTotals (r:1 w:1) fn place_bid_max() -> Weight { - (184_943_000 as Weight) + (124_814_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Gilt Queues (r:1 w:1) // Storage: Gilt QueueTotals (r:1 w:1) fn retract_bid(l: u32, ) -> Weight { - (59_352_000 as Weight) + (33_544_000 as Weight) // Standard Error: 0 - .saturating_add((129_000 as Weight).saturating_mul(l as Weight)) + .saturating_add((86_000 as Weight).saturating_mul(l as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Gilt ActiveTotal (r:1 w:1) fn set_target() -> Weight { - (5_444_000 as Weight) + (2_648_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Gilt Active (r:1 w:1) // Storage: Gilt ActiveTotal (r:1 w:1) fn thaw() -> Weight { - (71_399_000 as Weight) + (41_549_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Gilt ActiveTotal (r:1 w:0) fn pursue_target_noop() -> Weight { - (3_044_000 as Weight) + (1_583_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) } // Storage: Gilt ActiveTotal (r:1 w:1) @@ -178,9 +179,9 @@ impl WeightInfo for () { // Storage: Gilt Queues (r:1 w:1) // Storage: Gilt Active (r:0 w:1) fn pursue_target_per_item(b: u32, ) -> Weight { - (54_478_000 as Weight) - // Standard Error: 2_000 - .saturating_add((10_150_000 as Weight).saturating_mul(b as Weight)) + (35_836_000 as Weight) + // Standard Error: 1_000 + .saturating_add((4_008_000 as Weight).saturating_mul(b as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(b as Weight))) @@ -190,9 +191,9 @@ impl WeightInfo for () { // Storage: Gilt Queues (r:1 w:1) // Storage: Gilt Active (r:0 w:1) fn pursue_target_per_queue(q: u32, ) -> Weight { - (20_099_000 as Weight) - // Standard Error: 7_000 - .saturating_add((16_603_000 as Weight).saturating_mul(q as Weight)) + (12_139_000 as Weight) + // Standard Error: 6_000 + .saturating_add((7_819_000 as Weight).saturating_mul(q as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(q as Weight))) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) diff --git a/frame/grandpa/Cargo.toml b/frame/grandpa/Cargo.toml index 4b2ab7eca8712..eda9d630d4f99 100644 --- a/frame/grandpa/Cargo.toml +++ b/frame/grandpa/Cargo.toml @@ -15,13 +15,13 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -sp-application-crypto = { version = "4.0.0", default-features = false, path = "../../primitives/application-crypto" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } +sp-application-crypto = { version = "5.0.0", default-features = false, path = "../../primitives/application-crypto" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } sp-finality-grandpa = { version = "4.0.0-dev", default-features = false, path = "../../primitives/finality-grandpa" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } sp-session = { version = "4.0.0-dev", default-features = false, path = "../../primitives/session" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-staking = { version = "4.0.0-dev", default-features = false, path = "../../primitives/staking" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } @@ -33,7 +33,7 @@ log = { version = "0.4.14", default-features = false } [dev-dependencies] frame-benchmarking = { version = "4.0.0-dev", path = "../benchmarking" } grandpa = { package = "finality-grandpa", version = "0.14.1", features = ["derive-codec"] } -sp-keyring = { version = "4.1.0-dev", path = "../../primitives/keyring" } +sp-keyring = { version = "5.0.0", path = "../../primitives/keyring" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } pallet-offences = { version = "4.0.0-dev", path = "../offences" } pallet-staking = { version = "4.0.0-dev", path = "../staking" } diff --git a/frame/grandpa/src/lib.rs b/frame/grandpa/src/lib.rs index 0aaf0f679ce11..68d4cf26a2e23 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -364,13 +364,9 @@ pub type BoundedAuthorityList = WeakBoundedVec<(AuthorityId, AuthorityWei /// A stored pending change. /// `Limit` is the bound for `next_authorities` #[derive(Encode, Decode, TypeInfo, MaxEncodedLen)] -#[codec(mel_bound(Limit: Get))] +#[codec(mel_bound(N: MaxEncodedLen, Limit: Get))] #[scale_info(skip_type_params(Limit))] -pub struct StoredPendingChange -where - Limit: Get, - N: MaxEncodedLen, -{ +pub struct StoredPendingChange { /// The block number this was scheduled at. pub scheduled_at: N, /// The delay in blocks until it will be applied. diff --git a/frame/grandpa/src/mock.rs b/frame/grandpa/src/mock.rs index 34787c93bb9ce..d07f3136d9a0d 100644 --- a/frame/grandpa/src/mock.rs +++ b/frame/grandpa/src/mock.rs @@ -186,7 +186,7 @@ impl onchain::Config for Test { } impl pallet_staking::Config for Test { - const MAX_NOMINATIONS: u32 = 16; + type MaxNominations = ConstU32<16>; type RewardRemainder = (); type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; type Event = Event; diff --git a/frame/identity/Cargo.toml b/frame/identity/Cargo.toml index 00be4d767ec2b..209896ec0e557 100644 --- a/frame/identity/Cargo.toml +++ b/frame/identity/Cargo.toml @@ -17,14 +17,14 @@ codec = { package = "parity-scale-codec", version = "2.2.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } enumflags2 = { version = "0.6.2" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } [features] diff --git a/frame/identity/src/benchmarking.rs b/frame/identity/src/benchmarking.rs index 2f52aff394b7e..2145779ecf541 100644 --- a/frame/identity/src/benchmarking.rs +++ b/frame/identity/src/benchmarking.rs @@ -75,7 +75,7 @@ fn create_sub_accounts( } // Set identity so `set_subs` does not fail. - let _ = T::Currency::make_free_balance_be(&who, BalanceOf::::max_value()); + let _ = T::Currency::make_free_balance_be(&who, BalanceOf::::max_value() / 2u32.into()); let info = create_identity_info::(1); Identity::::set_identity(who_origin.clone().into(), Box::new(info))?; diff --git a/frame/identity/src/types.rs b/frame/identity/src/types.rs index ed3caafd3a114..cb79ace98d81c 100644 --- a/frame/identity/src/types.rs +++ b/frame/identity/src/types.rs @@ -245,7 +245,7 @@ pub enum IdentityField { /// Wrapper type for `BitFlags` that implements `Codec`. #[derive(Clone, Copy, PartialEq, Default, RuntimeDebug)] -pub struct IdentityFields(pub(crate) BitFlags); +pub struct IdentityFields(pub BitFlags); impl MaxEncodedLen for IdentityFields { fn max_encoded_len() -> usize { @@ -283,7 +283,7 @@ impl TypeInfo for IdentityFields { #[derive( CloneNoBound, Encode, Decode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo, )] -#[codec(mel_bound(FieldLimit: Get))] +#[codec(mel_bound())] #[cfg_attr(test, derive(frame_support::DefaultNoBound))] #[scale_info(skip_type_params(FieldLimit))] pub struct IdentityInfo> { @@ -339,11 +339,7 @@ pub struct IdentityInfo> { #[derive( CloneNoBound, Encode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo, )] -#[codec(mel_bound( - Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq + Zero + Add, - MaxJudgements: Get, - MaxAdditionalFields: Get, -))] +#[codec(mel_bound())] #[scale_info(skip_type_params(MaxJudgements, MaxAdditionalFields))] pub struct Registration< Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq, diff --git a/frame/identity/src/weights.rs b/frame/identity/src/weights.rs index 9f04007431be8..cf164d3cbd73f 100644 --- a/frame/identity/src/weights.rs +++ b/frame/identity/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_identity //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-11-17, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,7 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/identity/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -67,19 +69,19 @@ pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { // Storage: Identity Registrars (r:1 w:1) fn add_registrar(r: u32, ) -> Weight { - (19_176_000 as Weight) - // Standard Error: 5_000 - .saturating_add((313_000 as Weight).saturating_mul(r as Weight)) + (13_150_000 as Weight) + // Standard Error: 3_000 + .saturating_add((253_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Identity IdentityOf (r:1 w:1) fn set_identity(r: u32, x: u32, ) -> Weight { - (44_668_000 as Weight) - // Standard Error: 12_000 - .saturating_add((244_000 as Weight).saturating_mul(r as Weight)) + (27_745_000 as Weight) + // Standard Error: 7_000 + .saturating_add((210_000 as Weight).saturating_mul(r as Weight)) // Standard Error: 1_000 - .saturating_add((811_000 as Weight).saturating_mul(x as Weight)) + .saturating_add((289_000 as Weight).saturating_mul(x as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -87,9 +89,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Identity SubsOf (r:1 w:1) // Storage: Identity SuperOf (r:1 w:1) fn set_subs_new(s: u32, ) -> Weight { - (38_917_000 as Weight) - // Standard Error: 3_000 - .saturating_add((5_331_000 as Weight).saturating_mul(s as Weight)) + (25_184_000 as Weight) + // Standard Error: 1_000 + .saturating_add((2_722_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) .saturating_add(T::DbWeight::get().writes(1 as Weight)) @@ -99,9 +101,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Identity SubsOf (r:1 w:1) // Storage: Identity SuperOf (r:0 w:1) fn set_subs_old(p: u32, ) -> Weight { - (36_057_000 as Weight) - // Standard Error: 1_000 - .saturating_add((1_756_000 as Weight).saturating_mul(p as Weight)) + (24_144_000 as Weight) + // Standard Error: 0 + .saturating_add((890_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) @@ -110,13 +112,13 @@ impl WeightInfo for SubstrateWeight { // Storage: Identity IdentityOf (r:1 w:1) // Storage: Identity SuperOf (r:0 w:100) fn clear_identity(r: u32, s: u32, x: u32, ) -> Weight { - (44_348_000 as Weight) - // Standard Error: 9_000 - .saturating_add((183_000 as Weight).saturating_mul(r as Weight)) - // Standard Error: 1_000 - .saturating_add((1_724_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 1_000 - .saturating_add((439_000 as Weight).saturating_mul(x as Weight)) + (32_167_000 as Weight) + // Standard Error: 8_000 + .saturating_add((46_000 as Weight).saturating_mul(r as Weight)) + // Standard Error: 0 + .saturating_add((875_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((184_000 as Weight).saturating_mul(x as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) @@ -124,56 +126,56 @@ impl WeightInfo for SubstrateWeight { // Storage: Identity Registrars (r:1 w:0) // Storage: Identity IdentityOf (r:1 w:1) fn request_judgement(r: u32, x: u32, ) -> Weight { - (46_592_000 as Weight) - // Standard Error: 5_000 - .saturating_add((321_000 as Weight).saturating_mul(r as Weight)) + (30_009_000 as Weight) + // Standard Error: 3_000 + .saturating_add((287_000 as Weight).saturating_mul(r as Weight)) // Standard Error: 0 - .saturating_add((858_000 as Weight).saturating_mul(x as Weight)) + .saturating_add((331_000 as Weight).saturating_mul(x as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Identity IdentityOf (r:1 w:1) fn cancel_request(r: u32, x: u32, ) -> Weight { - (43_556_000 as Weight) - // Standard Error: 6_000 - .saturating_add((174_000 as Weight).saturating_mul(r as Weight)) + (28_195_000 as Weight) + // Standard Error: 3_000 + .saturating_add((137_000 as Weight).saturating_mul(r as Weight)) // Standard Error: 0 - .saturating_add((850_000 as Weight).saturating_mul(x as Weight)) + .saturating_add((328_000 as Weight).saturating_mul(x as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Identity Registrars (r:1 w:1) fn set_fee(r: u32, ) -> Weight { - (7_971_000 as Weight) - // Standard Error: 4_000 - .saturating_add((283_000 as Weight).saturating_mul(r as Weight)) + (5_080_000 as Weight) + // Standard Error: 2_000 + .saturating_add((202_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Identity Registrars (r:1 w:1) fn set_account_id(r: u32, ) -> Weight { - (8_234_000 as Weight) - // Standard Error: 4_000 - .saturating_add((280_000 as Weight).saturating_mul(r as Weight)) + (5_298_000 as Weight) + // Standard Error: 2_000 + .saturating_add((195_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Identity Registrars (r:1 w:1) fn set_fields(r: u32, ) -> Weight { - (8_126_000 as Weight) - // Standard Error: 4_000 - .saturating_add((275_000 as Weight).saturating_mul(r as Weight)) + (5_263_000 as Weight) + // Standard Error: 2_000 + .saturating_add((191_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Identity Registrars (r:1 w:0) // Storage: Identity IdentityOf (r:1 w:1) fn provide_judgement(r: u32, x: u32, ) -> Weight { - (30_949_000 as Weight) - // Standard Error: 5_000 - .saturating_add((286_000 as Weight).saturating_mul(r as Weight)) + (21_511_000 as Weight) + // Standard Error: 3_000 + .saturating_add((219_000 as Weight).saturating_mul(r as Weight)) // Standard Error: 0 - .saturating_add((856_000 as Weight).saturating_mul(x as Weight)) + .saturating_add((327_000 as Weight).saturating_mul(x as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -182,11 +184,11 @@ impl WeightInfo for SubstrateWeight { // Storage: System Account (r:1 w:1) // Storage: Identity SuperOf (r:0 w:100) fn kill_identity(r: u32, s: u32, _x: u32, ) -> Weight { - (63_792_000 as Weight) - // Standard Error: 11_000 - .saturating_add((242_000 as Weight).saturating_mul(r as Weight)) - // Standard Error: 1_000 - .saturating_add((1_738_000 as Weight).saturating_mul(s as Weight)) + (40_654_000 as Weight) + // Standard Error: 6_000 + .saturating_add((179_000 as Weight).saturating_mul(r as Weight)) + // Standard Error: 0 + .saturating_add((908_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) @@ -195,18 +197,18 @@ impl WeightInfo for SubstrateWeight { // Storage: Identity SuperOf (r:1 w:1) // Storage: Identity SubsOf (r:1 w:1) fn add_sub(s: u32, ) -> Weight { - (48_751_000 as Weight) + (31_573_000 as Weight) // Standard Error: 1_000 - .saturating_add((193_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((151_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Identity IdentityOf (r:1 w:0) // Storage: Identity SuperOf (r:1 w:1) fn rename_sub(s: u32, ) -> Weight { - (15_892_000 as Weight) + (10_452_000 as Weight) // Standard Error: 0 - .saturating_add((49_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((45_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -214,18 +216,18 @@ impl WeightInfo for SubstrateWeight { // Storage: Identity SuperOf (r:1 w:1) // Storage: Identity SubsOf (r:1 w:1) fn remove_sub(s: u32, ) -> Weight { - (49_746_000 as Weight) + (32_711_000 as Weight) // Standard Error: 1_000 - .saturating_add((181_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((150_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Identity SuperOf (r:1 w:1) // Storage: Identity SubsOf (r:1 w:1) fn quit_sub(s: u32, ) -> Weight { - (32_286_000 as Weight) - // Standard Error: 1_000 - .saturating_add((166_000 as Weight).saturating_mul(s as Weight)) + (21_975_000 as Weight) + // Standard Error: 0 + .saturating_add((149_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -235,19 +237,19 @@ impl WeightInfo for SubstrateWeight { impl WeightInfo for () { // Storage: Identity Registrars (r:1 w:1) fn add_registrar(r: u32, ) -> Weight { - (19_176_000 as Weight) - // Standard Error: 5_000 - .saturating_add((313_000 as Weight).saturating_mul(r as Weight)) + (13_150_000 as Weight) + // Standard Error: 3_000 + .saturating_add((253_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Identity IdentityOf (r:1 w:1) fn set_identity(r: u32, x: u32, ) -> Weight { - (44_668_000 as Weight) - // Standard Error: 12_000 - .saturating_add((244_000 as Weight).saturating_mul(r as Weight)) + (27_745_000 as Weight) + // Standard Error: 7_000 + .saturating_add((210_000 as Weight).saturating_mul(r as Weight)) // Standard Error: 1_000 - .saturating_add((811_000 as Weight).saturating_mul(x as Weight)) + .saturating_add((289_000 as Weight).saturating_mul(x as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -255,9 +257,9 @@ impl WeightInfo for () { // Storage: Identity SubsOf (r:1 w:1) // Storage: Identity SuperOf (r:1 w:1) fn set_subs_new(s: u32, ) -> Weight { - (38_917_000 as Weight) - // Standard Error: 3_000 - .saturating_add((5_331_000 as Weight).saturating_mul(s as Weight)) + (25_184_000 as Weight) + // Standard Error: 1_000 + .saturating_add((2_722_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) @@ -267,9 +269,9 @@ impl WeightInfo for () { // Storage: Identity SubsOf (r:1 w:1) // Storage: Identity SuperOf (r:0 w:1) fn set_subs_old(p: u32, ) -> Weight { - (36_057_000 as Weight) - // Standard Error: 1_000 - .saturating_add((1_756_000 as Weight).saturating_mul(p as Weight)) + (24_144_000 as Weight) + // Standard Error: 0 + .saturating_add((890_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) @@ -278,13 +280,13 @@ impl WeightInfo for () { // Storage: Identity IdentityOf (r:1 w:1) // Storage: Identity SuperOf (r:0 w:100) fn clear_identity(r: u32, s: u32, x: u32, ) -> Weight { - (44_348_000 as Weight) - // Standard Error: 9_000 - .saturating_add((183_000 as Weight).saturating_mul(r as Weight)) - // Standard Error: 1_000 - .saturating_add((1_724_000 as Weight).saturating_mul(s as Weight)) - // Standard Error: 1_000 - .saturating_add((439_000 as Weight).saturating_mul(x as Weight)) + (32_167_000 as Weight) + // Standard Error: 8_000 + .saturating_add((46_000 as Weight).saturating_mul(r as Weight)) + // Standard Error: 0 + .saturating_add((875_000 as Weight).saturating_mul(s as Weight)) + // Standard Error: 0 + .saturating_add((184_000 as Weight).saturating_mul(x as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) @@ -292,56 +294,56 @@ impl WeightInfo for () { // Storage: Identity Registrars (r:1 w:0) // Storage: Identity IdentityOf (r:1 w:1) fn request_judgement(r: u32, x: u32, ) -> Weight { - (46_592_000 as Weight) - // Standard Error: 5_000 - .saturating_add((321_000 as Weight).saturating_mul(r as Weight)) + (30_009_000 as Weight) + // Standard Error: 3_000 + .saturating_add((287_000 as Weight).saturating_mul(r as Weight)) // Standard Error: 0 - .saturating_add((858_000 as Weight).saturating_mul(x as Weight)) + .saturating_add((331_000 as Weight).saturating_mul(x as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Identity IdentityOf (r:1 w:1) fn cancel_request(r: u32, x: u32, ) -> Weight { - (43_556_000 as Weight) - // Standard Error: 6_000 - .saturating_add((174_000 as Weight).saturating_mul(r as Weight)) + (28_195_000 as Weight) + // Standard Error: 3_000 + .saturating_add((137_000 as Weight).saturating_mul(r as Weight)) // Standard Error: 0 - .saturating_add((850_000 as Weight).saturating_mul(x as Weight)) + .saturating_add((328_000 as Weight).saturating_mul(x as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Identity Registrars (r:1 w:1) fn set_fee(r: u32, ) -> Weight { - (7_971_000 as Weight) - // Standard Error: 4_000 - .saturating_add((283_000 as Weight).saturating_mul(r as Weight)) + (5_080_000 as Weight) + // Standard Error: 2_000 + .saturating_add((202_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Identity Registrars (r:1 w:1) fn set_account_id(r: u32, ) -> Weight { - (8_234_000 as Weight) - // Standard Error: 4_000 - .saturating_add((280_000 as Weight).saturating_mul(r as Weight)) + (5_298_000 as Weight) + // Standard Error: 2_000 + .saturating_add((195_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Identity Registrars (r:1 w:1) fn set_fields(r: u32, ) -> Weight { - (8_126_000 as Weight) - // Standard Error: 4_000 - .saturating_add((275_000 as Weight).saturating_mul(r as Weight)) + (5_263_000 as Weight) + // Standard Error: 2_000 + .saturating_add((191_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Identity Registrars (r:1 w:0) // Storage: Identity IdentityOf (r:1 w:1) fn provide_judgement(r: u32, x: u32, ) -> Weight { - (30_949_000 as Weight) - // Standard Error: 5_000 - .saturating_add((286_000 as Weight).saturating_mul(r as Weight)) + (21_511_000 as Weight) + // Standard Error: 3_000 + .saturating_add((219_000 as Weight).saturating_mul(r as Weight)) // Standard Error: 0 - .saturating_add((856_000 as Weight).saturating_mul(x as Weight)) + .saturating_add((327_000 as Weight).saturating_mul(x as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -350,11 +352,11 @@ impl WeightInfo for () { // Storage: System Account (r:1 w:1) // Storage: Identity SuperOf (r:0 w:100) fn kill_identity(r: u32, s: u32, _x: u32, ) -> Weight { - (63_792_000 as Weight) - // Standard Error: 11_000 - .saturating_add((242_000 as Weight).saturating_mul(r as Weight)) - // Standard Error: 1_000 - .saturating_add((1_738_000 as Weight).saturating_mul(s as Weight)) + (40_654_000 as Weight) + // Standard Error: 6_000 + .saturating_add((179_000 as Weight).saturating_mul(r as Weight)) + // Standard Error: 0 + .saturating_add((908_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) @@ -363,18 +365,18 @@ impl WeightInfo for () { // Storage: Identity SuperOf (r:1 w:1) // Storage: Identity SubsOf (r:1 w:1) fn add_sub(s: u32, ) -> Weight { - (48_751_000 as Weight) + (31_573_000 as Weight) // Standard Error: 1_000 - .saturating_add((193_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((151_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Identity IdentityOf (r:1 w:0) // Storage: Identity SuperOf (r:1 w:1) fn rename_sub(s: u32, ) -> Weight { - (15_892_000 as Weight) + (10_452_000 as Weight) // Standard Error: 0 - .saturating_add((49_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((45_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -382,18 +384,18 @@ impl WeightInfo for () { // Storage: Identity SuperOf (r:1 w:1) // Storage: Identity SubsOf (r:1 w:1) fn remove_sub(s: u32, ) -> Weight { - (49_746_000 as Weight) + (32_711_000 as Weight) // Standard Error: 1_000 - .saturating_add((181_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((150_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Identity SuperOf (r:1 w:1) // Storage: Identity SubsOf (r:1 w:1) fn quit_sub(s: u32, ) -> Weight { - (32_286_000 as Weight) - // Standard Error: 1_000 - .saturating_add((166_000 as Weight).saturating_mul(s as Weight)) + (21_975_000 as Weight) + // Standard Error: 0 + .saturating_add((149_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } diff --git a/frame/im-online/Cargo.toml b/frame/im-online/Cargo.toml index 9d659d304dbbe..d223e5e8502d3 100644 --- a/frame/im-online/Cargo.toml +++ b/frame/im-online/Cargo.toml @@ -13,14 +13,14 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-application-crypto = { version = "4.0.0", default-features = false, path = "../../primitives/application-crypto" } +sp-application-crypto = { version = "5.0.0", default-features = false, path = "../../primitives/application-crypto" } pallet-authorship = { version = "4.0.0-dev", default-features = false, path = "../authorship" } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-staking = { version = "4.0.0-dev", default-features = false, path = "../../primitives/staking" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } diff --git a/frame/im-online/src/lib.rs b/frame/im-online/src/lib.rs index 5ad27850a2c1f..e2213ef4169b1 100644 --- a/frame/im-online/src/lib.rs +++ b/frame/im-online/src/lib.rs @@ -238,8 +238,7 @@ where /// `MultiAddrEncodingLimit` represents the size limit of the encoding of `MultiAddr` /// `AddressesLimit` represents the size limit of the vector of peers connected #[derive(Clone, Eq, PartialEq, Encode, Decode, MaxEncodedLen, TypeInfo)] -#[codec(mel_bound(PeerIdEncodingLimit: Get, - MultiAddrEncodingLimit: Get, AddressesLimit: Get))] +#[codec(mel_bound())] #[scale_info(skip_type_params(PeerIdEncodingLimit, MultiAddrEncodingLimit, AddressesLimit))] pub struct BoundedOpaqueNetworkState where diff --git a/frame/im-online/src/weights.rs b/frame/im-online/src/weights.rs index 19ac7e8ffc0fc..f7d4d1441da27 100644 --- a/frame/im-online/src/weights.rs +++ b/frame/im-online/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_im_online //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/im-online/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -57,11 +58,11 @@ impl WeightInfo for SubstrateWeight { // Storage: ImOnline AuthoredBlocks (r:1 w:0) // Storage: ImOnline Keys (r:1 w:0) fn validate_unsigned_and_then_heartbeat(k: u32, e: u32, ) -> Weight { - (93_400_000 as Weight) + (74_137_000 as Weight) // Standard Error: 0 - .saturating_add((144_000 as Weight).saturating_mul(k as Weight)) + .saturating_add((125_000 as Weight).saturating_mul(k as Weight)) // Standard Error: 0 - .saturating_add((335_000 as Weight).saturating_mul(e as Weight)) + .saturating_add((291_000 as Weight).saturating_mul(e as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -75,11 +76,11 @@ impl WeightInfo for () { // Storage: ImOnline AuthoredBlocks (r:1 w:0) // Storage: ImOnline Keys (r:1 w:0) fn validate_unsigned_and_then_heartbeat(k: u32, e: u32, ) -> Weight { - (93_400_000 as Weight) + (74_137_000 as Weight) // Standard Error: 0 - .saturating_add((144_000 as Weight).saturating_mul(k as Weight)) + .saturating_add((125_000 as Weight).saturating_mul(k as Weight)) // Standard Error: 0 - .saturating_add((335_000 as Weight).saturating_mul(e as Weight)) + .saturating_add((291_000 as Weight).saturating_mul(e as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } diff --git a/frame/indices/Cargo.toml b/frame/indices/Cargo.toml index a2998c7cfae94..28a6427f520b8 100644 --- a/frame/indices/Cargo.toml +++ b/frame/indices/Cargo.toml @@ -15,11 +15,11 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -sp-keyring = { version = "4.1.0-dev", optional = true, path = "../../primitives/keyring" } +sp-keyring = { version = "5.0.0", optional = true, path = "../../primitives/keyring" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } diff --git a/frame/indices/src/lib.rs b/frame/indices/src/lib.rs index 7d23fa5e8c7f1..9c9e3580f2c04 100644 --- a/frame/indices/src/lib.rs +++ b/frame/indices/src/lib.rs @@ -56,7 +56,8 @@ pub mod pallet { + Codec + Default + AtLeast32Bit - + Copy; + + Copy + + MaxEncodedLen; /// The currency trait. type Currency: ReservableCurrency; @@ -74,7 +75,6 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] pub struct Pallet(PhantomData); #[pallet::call] diff --git a/frame/indices/src/weights.rs b/frame/indices/src/weights.rs index 590aa11dec840..1687237394fbd 100644 --- a/frame/indices/src/weights.rs +++ b/frame/indices/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_indices //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/indices/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -57,33 +58,33 @@ pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { // Storage: Indices Accounts (r:1 w:1) fn claim() -> Weight { - (38_814_000 as Weight) + (21_121_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Indices Accounts (r:1 w:1) // Storage: System Account (r:1 w:1) fn transfer() -> Weight { - (47_274_000 as Weight) + (26_843_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Indices Accounts (r:1 w:1) fn free() -> Weight { - (39_692_000 as Weight) + (22_174_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Indices Accounts (r:1 w:1) // Storage: System Account (r:1 w:1) fn force_transfer() -> Weight { - (40_250_000 as Weight) + (22_191_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Indices Accounts (r:1 w:1) fn freeze() -> Weight { - (37_358_000 as Weight) + (24_813_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -93,33 +94,33 @@ impl WeightInfo for SubstrateWeight { impl WeightInfo for () { // Storage: Indices Accounts (r:1 w:1) fn claim() -> Weight { - (38_814_000 as Weight) + (21_121_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Indices Accounts (r:1 w:1) // Storage: System Account (r:1 w:1) fn transfer() -> Weight { - (47_274_000 as Weight) + (26_843_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Indices Accounts (r:1 w:1) fn free() -> Weight { - (39_692_000 as Weight) + (22_174_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Indices Accounts (r:1 w:1) // Storage: System Account (r:1 w:1) fn force_transfer() -> Weight { - (40_250_000 as Weight) + (22_191_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Indices Accounts (r:1 w:1) fn freeze() -> Weight { - (37_358_000 as Weight) + (24_813_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } diff --git a/frame/lottery/Cargo.toml b/frame/lottery/Cargo.toml index cef152a185880..2e2c2287a2ab6 100644 --- a/frame/lottery/Cargo.toml +++ b/frame/lottery/Cargo.toml @@ -18,7 +18,7 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = ] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } @@ -27,8 +27,8 @@ frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = " [dev-dependencies] frame-support-test = { version = "3.0.0", path = "../support/test" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } [features] default = ["std"] diff --git a/frame/lottery/src/weights.rs b/frame/lottery/src/weights.rs index 53ec2aa231568..3b6114a73cfaa 100644 --- a/frame/lottery/src/weights.rs +++ b/frame/lottery/src/weights.rs @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_lottery //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2022-01-11, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,7 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/lottery/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -63,28 +65,28 @@ impl WeightInfo for SubstrateWeight { // Storage: System Account (r:1 w:1) // Storage: Lottery Tickets (r:0 w:1) fn buy_ticket() -> Weight { - (52_219_000 as Weight) + (37_257_000 as Weight) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } // Storage: Lottery CallIndices (r:0 w:1) fn set_calls(n: u32, ) -> Weight { - (13_249_000 as Weight) - // Standard Error: 7_000 - .saturating_add((378_000 as Weight).saturating_mul(n as Weight)) + (8_966_000 as Weight) + // Standard Error: 5_000 + .saturating_add((302_000 as Weight).saturating_mul(n as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Lottery Lottery (r:1 w:1) // Storage: Lottery LotteryIndex (r:1 w:1) // Storage: System Account (r:1 w:1) fn start_lottery() -> Weight { - (44_636_000 as Weight) + (32_282_000 as Weight) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } // Storage: Lottery Lottery (r:1 w:1) fn stop_repeat() -> Weight { - (5_654_000 as Weight) + (3_903_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -94,7 +96,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Lottery TicketsCount (r:1 w:1) // Storage: Lottery Tickets (r:1 w:0) fn on_initialize_end() -> Weight { - (72_990_000 as Weight) + (51_489_000 as Weight) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } @@ -105,7 +107,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Lottery Tickets (r:1 w:0) // Storage: Lottery LotteryIndex (r:1 w:1) fn on_initialize_repeat() -> Weight { - (75_323_000 as Weight) + (53_046_000 as Weight) .saturating_add(T::DbWeight::get().reads(7 as Weight)) .saturating_add(T::DbWeight::get().writes(5 as Weight)) } @@ -121,28 +123,28 @@ impl WeightInfo for () { // Storage: System Account (r:1 w:1) // Storage: Lottery Tickets (r:0 w:1) fn buy_ticket() -> Weight { - (52_219_000 as Weight) + (37_257_000 as Weight) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } // Storage: Lottery CallIndices (r:0 w:1) fn set_calls(n: u32, ) -> Weight { - (13_249_000 as Weight) - // Standard Error: 7_000 - .saturating_add((378_000 as Weight).saturating_mul(n as Weight)) + (8_966_000 as Weight) + // Standard Error: 5_000 + .saturating_add((302_000 as Weight).saturating_mul(n as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Lottery Lottery (r:1 w:1) // Storage: Lottery LotteryIndex (r:1 w:1) // Storage: System Account (r:1 w:1) fn start_lottery() -> Weight { - (44_636_000 as Weight) + (32_282_000 as Weight) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } // Storage: Lottery Lottery (r:1 w:1) fn stop_repeat() -> Weight { - (5_654_000 as Weight) + (3_903_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -152,7 +154,7 @@ impl WeightInfo for () { // Storage: Lottery TicketsCount (r:1 w:1) // Storage: Lottery Tickets (r:1 w:0) fn on_initialize_end() -> Weight { - (72_990_000 as Weight) + (51_489_000 as Weight) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } @@ -163,7 +165,7 @@ impl WeightInfo for () { // Storage: Lottery Tickets (r:1 w:0) // Storage: Lottery LotteryIndex (r:1 w:1) fn on_initialize_repeat() -> Weight { - (75_323_000 as Weight) + (53_046_000 as Weight) .saturating_add(RocksDbWeight::get().reads(7 as Weight)) .saturating_add(RocksDbWeight::get().writes(5 as Weight)) } diff --git a/frame/membership/Cargo.toml b/frame/membership/Cargo.toml index 7ded2fd586e19..f2f7607ce9a52 100644 --- a/frame/membership/Cargo.toml +++ b/frame/membership/Cargo.toml @@ -17,9 +17,9 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } log = { version = "0.4.0", default-features = false } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } diff --git a/frame/membership/src/weights.rs b/frame/membership/src/weights.rs index 5b34529c7c182..0d4936cfba1f9 100644 --- a/frame/membership/src/weights.rs +++ b/frame/membership/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_membership //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/membership/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -57,162 +58,162 @@ pub trait WeightInfo { /// Weights for pallet_membership using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - // Storage: Instance1Membership Members (r:1 w:1) - // Storage: Instance2Collective Proposals (r:1 w:0) - // Storage: Instance2Collective Members (r:0 w:1) - // Storage: Instance2Collective Prime (r:0 w:1) + // Storage: TechnicalMembership Members (r:1 w:1) + // Storage: TechnicalCommittee Proposals (r:1 w:0) + // Storage: TechnicalCommittee Members (r:0 w:1) + // Storage: TechnicalCommittee Prime (r:0 w:1) fn add_member(m: u32, ) -> Weight { - (23_668_000 as Weight) - // Standard Error: 3_000 - .saturating_add((142_000 as Weight).saturating_mul(m as Weight)) + (14_884_000 as Weight) + // Standard Error: 0 + .saturating_add((95_000 as Weight).saturating_mul(m as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Membership Members (r:1 w:1) - // Storage: Instance2Collective Proposals (r:1 w:0) - // Storage: Instance1Membership Prime (r:1 w:0) - // Storage: Instance2Collective Members (r:0 w:1) - // Storage: Instance2Collective Prime (r:0 w:1) + // Storage: TechnicalMembership Members (r:1 w:1) + // Storage: TechnicalCommittee Proposals (r:1 w:0) + // Storage: TechnicalMembership Prime (r:1 w:0) + // Storage: TechnicalCommittee Members (r:0 w:1) + // Storage: TechnicalCommittee Prime (r:0 w:1) fn remove_member(m: u32, ) -> Weight { - (29_149_000 as Weight) + (17_612_000 as Weight) // Standard Error: 0 - .saturating_add((111_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((86_000 as Weight).saturating_mul(m as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Membership Members (r:1 w:1) - // Storage: Instance2Collective Proposals (r:1 w:0) - // Storage: Instance1Membership Prime (r:1 w:0) - // Storage: Instance2Collective Members (r:0 w:1) - // Storage: Instance2Collective Prime (r:0 w:1) + // Storage: TechnicalMembership Members (r:1 w:1) + // Storage: TechnicalCommittee Proposals (r:1 w:0) + // Storage: TechnicalMembership Prime (r:1 w:0) + // Storage: TechnicalCommittee Members (r:0 w:1) + // Storage: TechnicalCommittee Prime (r:0 w:1) fn swap_member(m: u32, ) -> Weight { - (29_289_000 as Weight) + (17_580_000 as Weight) // Standard Error: 0 - .saturating_add((126_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((98_000 as Weight).saturating_mul(m as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Membership Members (r:1 w:1) - // Storage: Instance2Collective Proposals (r:1 w:0) - // Storage: Instance1Membership Prime (r:1 w:0) - // Storage: Instance2Collective Members (r:0 w:1) - // Storage: Instance2Collective Prime (r:0 w:1) + // Storage: TechnicalMembership Members (r:1 w:1) + // Storage: TechnicalCommittee Proposals (r:1 w:0) + // Storage: TechnicalMembership Prime (r:1 w:0) + // Storage: TechnicalCommittee Members (r:0 w:1) + // Storage: TechnicalCommittee Prime (r:0 w:1) fn reset_member(m: u32, ) -> Weight { - (30_178_000 as Weight) - // Standard Error: 1_000 - .saturating_add((286_000 as Weight).saturating_mul(m as Weight)) + (17_610_000 as Weight) + // Standard Error: 0 + .saturating_add((199_000 as Weight).saturating_mul(m as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Membership Members (r:1 w:1) - // Storage: Instance2Collective Proposals (r:1 w:0) - // Storage: Instance1Membership Prime (r:1 w:1) - // Storage: Instance2Collective Members (r:0 w:1) - // Storage: Instance2Collective Prime (r:0 w:1) + // Storage: TechnicalMembership Members (r:1 w:1) + // Storage: TechnicalCommittee Proposals (r:1 w:0) + // Storage: TechnicalMembership Prime (r:1 w:1) + // Storage: TechnicalCommittee Members (r:0 w:1) + // Storage: TechnicalCommittee Prime (r:0 w:1) fn change_key(m: u32, ) -> Weight { - (31_049_000 as Weight) + (18_208_000 as Weight) // Standard Error: 0 - .saturating_add((121_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((96_000 as Weight).saturating_mul(m as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } - // Storage: Instance1Membership Members (r:1 w:0) - // Storage: Instance1Membership Prime (r:0 w:1) - // Storage: Instance2Collective Prime (r:0 w:1) + // Storage: TechnicalMembership Members (r:1 w:0) + // Storage: TechnicalMembership Prime (r:0 w:1) + // Storage: TechnicalCommittee Prime (r:0 w:1) fn set_prime(m: u32, ) -> Weight { - (8_006_000 as Weight) + (4_661_000 as Weight) // Standard Error: 0 - .saturating_add((89_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((70_000 as Weight).saturating_mul(m as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } - // Storage: Instance1Membership Prime (r:0 w:1) - // Storage: Instance2Collective Prime (r:0 w:1) + // Storage: TechnicalMembership Prime (r:0 w:1) + // Storage: TechnicalCommittee Prime (r:0 w:1) fn clear_prime(m: u32, ) -> Weight { - (3_452_000 as Weight) + (1_574_000 as Weight) // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((1_000 as Weight).saturating_mul(m as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } } // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Instance1Membership Members (r:1 w:1) - // Storage: Instance2Collective Proposals (r:1 w:0) - // Storage: Instance2Collective Members (r:0 w:1) - // Storage: Instance2Collective Prime (r:0 w:1) + // Storage: TechnicalMembership Members (r:1 w:1) + // Storage: TechnicalCommittee Proposals (r:1 w:0) + // Storage: TechnicalCommittee Members (r:0 w:1) + // Storage: TechnicalCommittee Prime (r:0 w:1) fn add_member(m: u32, ) -> Weight { - (23_668_000 as Weight) - // Standard Error: 3_000 - .saturating_add((142_000 as Weight).saturating_mul(m as Weight)) + (14_884_000 as Weight) + // Standard Error: 0 + .saturating_add((95_000 as Weight).saturating_mul(m as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Membership Members (r:1 w:1) - // Storage: Instance2Collective Proposals (r:1 w:0) - // Storage: Instance1Membership Prime (r:1 w:0) - // Storage: Instance2Collective Members (r:0 w:1) - // Storage: Instance2Collective Prime (r:0 w:1) + // Storage: TechnicalMembership Members (r:1 w:1) + // Storage: TechnicalCommittee Proposals (r:1 w:0) + // Storage: TechnicalMembership Prime (r:1 w:0) + // Storage: TechnicalCommittee Members (r:0 w:1) + // Storage: TechnicalCommittee Prime (r:0 w:1) fn remove_member(m: u32, ) -> Weight { - (29_149_000 as Weight) + (17_612_000 as Weight) // Standard Error: 0 - .saturating_add((111_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((86_000 as Weight).saturating_mul(m as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Membership Members (r:1 w:1) - // Storage: Instance2Collective Proposals (r:1 w:0) - // Storage: Instance1Membership Prime (r:1 w:0) - // Storage: Instance2Collective Members (r:0 w:1) - // Storage: Instance2Collective Prime (r:0 w:1) + // Storage: TechnicalMembership Members (r:1 w:1) + // Storage: TechnicalCommittee Proposals (r:1 w:0) + // Storage: TechnicalMembership Prime (r:1 w:0) + // Storage: TechnicalCommittee Members (r:0 w:1) + // Storage: TechnicalCommittee Prime (r:0 w:1) fn swap_member(m: u32, ) -> Weight { - (29_289_000 as Weight) + (17_580_000 as Weight) // Standard Error: 0 - .saturating_add((126_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((98_000 as Weight).saturating_mul(m as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Membership Members (r:1 w:1) - // Storage: Instance2Collective Proposals (r:1 w:0) - // Storage: Instance1Membership Prime (r:1 w:0) - // Storage: Instance2Collective Members (r:0 w:1) - // Storage: Instance2Collective Prime (r:0 w:1) + // Storage: TechnicalMembership Members (r:1 w:1) + // Storage: TechnicalCommittee Proposals (r:1 w:0) + // Storage: TechnicalMembership Prime (r:1 w:0) + // Storage: TechnicalCommittee Members (r:0 w:1) + // Storage: TechnicalCommittee Prime (r:0 w:1) fn reset_member(m: u32, ) -> Weight { - (30_178_000 as Weight) - // Standard Error: 1_000 - .saturating_add((286_000 as Weight).saturating_mul(m as Weight)) + (17_610_000 as Weight) + // Standard Error: 0 + .saturating_add((199_000 as Weight).saturating_mul(m as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } - // Storage: Instance1Membership Members (r:1 w:1) - // Storage: Instance2Collective Proposals (r:1 w:0) - // Storage: Instance1Membership Prime (r:1 w:1) - // Storage: Instance2Collective Members (r:0 w:1) - // Storage: Instance2Collective Prime (r:0 w:1) + // Storage: TechnicalMembership Members (r:1 w:1) + // Storage: TechnicalCommittee Proposals (r:1 w:0) + // Storage: TechnicalMembership Prime (r:1 w:1) + // Storage: TechnicalCommittee Members (r:0 w:1) + // Storage: TechnicalCommittee Prime (r:0 w:1) fn change_key(m: u32, ) -> Weight { - (31_049_000 as Weight) + (18_208_000 as Weight) // Standard Error: 0 - .saturating_add((121_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((96_000 as Weight).saturating_mul(m as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } - // Storage: Instance1Membership Members (r:1 w:0) - // Storage: Instance1Membership Prime (r:0 w:1) - // Storage: Instance2Collective Prime (r:0 w:1) + // Storage: TechnicalMembership Members (r:1 w:0) + // Storage: TechnicalMembership Prime (r:0 w:1) + // Storage: TechnicalCommittee Prime (r:0 w:1) fn set_prime(m: u32, ) -> Weight { - (8_006_000 as Weight) + (4_661_000 as Weight) // Standard Error: 0 - .saturating_add((89_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((70_000 as Weight).saturating_mul(m as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } - // Storage: Instance1Membership Prime (r:0 w:1) - // Storage: Instance2Collective Prime (r:0 w:1) + // Storage: TechnicalMembership Prime (r:0 w:1) + // Storage: TechnicalCommittee Prime (r:0 w:1) fn clear_prime(m: u32, ) -> Weight { - (3_452_000 as Weight) + (1_574_000 as Weight) // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((1_000 as Weight).saturating_mul(m as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } } diff --git a/frame/merkle-mountain-range/Cargo.toml b/frame/merkle-mountain-range/Cargo.toml index 495b0add5b1c4..a614ffa977154 100644 --- a/frame/merkle-mountain-range/Cargo.toml +++ b/frame/merkle-mountain-range/Cargo.toml @@ -16,9 +16,9 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } mmr-lib = { package = "ckb-merkle-mountain-range", default-features = false, version = "0.3.2" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } diff --git a/frame/merkle-mountain-range/primitives/Cargo.toml b/frame/merkle-mountain-range/primitives/Cargo.toml index 2e483360facc1..d281f159bebad 100644 --- a/frame/merkle-mountain-range/primitives/Cargo.toml +++ b/frame/merkle-mountain-range/primitives/Cargo.toml @@ -14,11 +14,11 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } log = { version = "0.4.14", default-features = false } -serde = { version = "1.0.132", optional = true, features = ["derive"] } +serde = { version = "1.0.136", optional = true, features = ["derive"] } sp-api = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/api" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../../primitives/core" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../../primitives/std" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../../support" } diff --git a/frame/merkle-mountain-range/rpc/Cargo.toml b/frame/merkle-mountain-range/rpc/Cargo.toml index d6bf66cefefbb..7dc891267cebc 100644 --- a/frame/merkle-mountain-range/rpc/Cargo.toml +++ b/frame/merkle-mountain-range/rpc/Cargo.toml @@ -17,12 +17,12 @@ codec = { package = "parity-scale-codec", version = "2.0.0" } jsonrpc-core = "18.0.0" jsonrpc-core-client = "18.0.0" jsonrpc-derive = "18.0.0" -serde = { version = "1.0.132", features = ["derive"] } +serde = { version = "1.0.136", features = ["derive"] } sp-api = { version = "4.0.0-dev", path = "../../../primitives/api" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } pallet-mmr-primitives = { version = "4.0.0-dev", path = "../primitives" } diff --git a/frame/merkle-mountain-range/rpc/src/lib.rs b/frame/merkle-mountain-range/rpc/src/lib.rs index b256ccdd7d327..bf3eb3b694e39 100644 --- a/frame/merkle-mountain-range/rpc/src/lib.rs +++ b/frame/merkle-mountain-range/rpc/src/lib.rs @@ -144,11 +144,11 @@ fn mmr_error_into_rpc_error(err: MmrError) -> Error { } /// Converts a runtime trap into an RPC error. -fn runtime_error_into_rpc_error(err: impl std::fmt::Debug) -> Error { +fn runtime_error_into_rpc_error(err: impl std::fmt::Display) -> Error { Error { code: ErrorCode::ServerError(RUNTIME_ERROR), message: "Runtime trapped".into(), - data: Some(format!("{:?}", err).into()), + data: Some(err.to_string().into()), } } diff --git a/frame/merkle-mountain-range/src/lib.rs b/frame/merkle-mountain-range/src/lib.rs index 2a93dc7af2892..f904428e02048 100644 --- a/frame/merkle-mountain-range/src/lib.rs +++ b/frame/merkle-mountain-range/src/lib.rs @@ -84,7 +84,6 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] pub struct Pallet(PhantomData<(T, I)>); /// This pallet's configuration trait @@ -126,7 +125,8 @@ pub mod pallet { + Default + codec::Codec + codec::EncodeLike - + scale_info::TypeInfo; + + scale_info::TypeInfo + + MaxEncodedLen; /// Data stored in the leaf nodes. /// diff --git a/frame/multisig/Cargo.toml b/frame/multisig/Cargo.toml index 696f8afe0d85c..dfc05888b1aa9 100644 --- a/frame/multisig/Cargo.toml +++ b/frame/multisig/Cargo.toml @@ -17,14 +17,14 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } [features] diff --git a/frame/multisig/src/weights.rs b/frame/multisig/src/weights.rs index eb78a88f1531c..501fb9c184194 100644 --- a/frame/multisig/src/weights.rs +++ b/frame/multisig/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_multisig //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/multisig/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -61,18 +62,18 @@ pub trait WeightInfo { pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { fn as_multi_threshold_1(z: u32, ) -> Weight { - (19_405_000 as Weight) + (16_534_000 as Weight) // Standard Error: 0 .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) } // Storage: Multisig Multisigs (r:1 w:1) // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) fn as_multi_create(s: u32, z: u32, ) -> Weight { - (54_364_000 as Weight) - // Standard Error: 0 - .saturating_add((163_000 as Weight).saturating_mul(s as Weight)) + (30_917_000 as Weight) + // Standard Error: 1_000 + .saturating_add((131_000 as Weight).saturating_mul(s as Weight)) // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -80,32 +81,32 @@ impl WeightInfo for SubstrateWeight { // Storage: Multisig Calls (r:1 w:1) // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) fn as_multi_create_store(s: u32, z: u32, ) -> Weight { - (59_545_000 as Weight) - // Standard Error: 0 - .saturating_add((168_000 as Weight).saturating_mul(s as Weight)) + (33_570_000 as Weight) + // Standard Error: 1_000 + .saturating_add((138_000 as Weight).saturating_mul(s as Weight)) // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(z as Weight)) + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Multisig Multisigs (r:1 w:1) fn as_multi_approve(s: u32, z: u32, ) -> Weight { - (32_721_000 as Weight) + (21_051_000 as Weight) // Standard Error: 0 - .saturating_add((176_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((126_000 as Weight).saturating_mul(s as Weight)) // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Multisig Multisigs (r:1 w:1) // Storage: Multisig Calls (r:1 w:1) fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { - (56_596_000 as Weight) + (32_581_000 as Weight) // Standard Error: 1_000 - .saturating_add((183_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((135_000 as Weight).saturating_mul(s as Weight)) // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(z as Weight)) + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -113,29 +114,29 @@ impl WeightInfo for SubstrateWeight { // Storage: Multisig Calls (r:1 w:1) // Storage: System Account (r:1 w:1) fn as_multi_complete(s: u32, z: u32, ) -> Weight { - (72_391_000 as Weight) + (39_215_000 as Weight) // Standard Error: 1_000 - .saturating_add((268_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((221_000 as Weight).saturating_mul(s as Weight)) // Standard Error: 0 - .saturating_add((4_000 as Weight).saturating_mul(z as Weight)) + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } // Storage: Multisig Multisigs (r:1 w:1) // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) fn approve_as_multi_create(s: u32, ) -> Weight { - (52_543_000 as Weight) - // Standard Error: 0 - .saturating_add((164_000 as Weight).saturating_mul(s as Weight)) + (28_572_000 as Weight) + // Standard Error: 1_000 + .saturating_add((146_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Multisig Multisigs (r:1 w:1) // Storage: Multisig Calls (r:1 w:0) fn approve_as_multi_approve(s: u32, ) -> Weight { - (30_764_000 as Weight) + (18_032_000 as Weight) // Standard Error: 0 - .saturating_add((180_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((151_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -143,18 +144,18 @@ impl WeightInfo for SubstrateWeight { // Storage: Multisig Calls (r:1 w:1) // Storage: System Account (r:1 w:1) fn approve_as_multi_complete(s: u32, ) -> Weight { - (113_631_000 as Weight) - // Standard Error: 3_000 - .saturating_add((283_000 as Weight).saturating_mul(s as Weight)) + (56_353_000 as Weight) + // Standard Error: 1_000 + .saturating_add((239_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } // Storage: Multisig Multisigs (r:1 w:1) // Storage: Multisig Calls (r:1 w:1) fn cancel_as_multi(s: u32, ) -> Weight { - (86_310_000 as Weight) + (44_544_000 as Weight) // Standard Error: 0 - .saturating_add((166_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((158_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -163,18 +164,18 @@ impl WeightInfo for SubstrateWeight { // For backwards compatibility and tests impl WeightInfo for () { fn as_multi_threshold_1(z: u32, ) -> Weight { - (19_405_000 as Weight) + (16_534_000 as Weight) // Standard Error: 0 .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) } // Storage: Multisig Multisigs (r:1 w:1) // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) fn as_multi_create(s: u32, z: u32, ) -> Weight { - (54_364_000 as Weight) - // Standard Error: 0 - .saturating_add((163_000 as Weight).saturating_mul(s as Weight)) + (30_917_000 as Weight) + // Standard Error: 1_000 + .saturating_add((131_000 as Weight).saturating_mul(s as Weight)) // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -182,32 +183,32 @@ impl WeightInfo for () { // Storage: Multisig Calls (r:1 w:1) // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) fn as_multi_create_store(s: u32, z: u32, ) -> Weight { - (59_545_000 as Weight) - // Standard Error: 0 - .saturating_add((168_000 as Weight).saturating_mul(s as Weight)) + (33_570_000 as Weight) + // Standard Error: 1_000 + .saturating_add((138_000 as Weight).saturating_mul(s as Weight)) // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(z as Weight)) + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Multisig Multisigs (r:1 w:1) fn as_multi_approve(s: u32, z: u32, ) -> Weight { - (32_721_000 as Weight) + (21_051_000 as Weight) // Standard Error: 0 - .saturating_add((176_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((126_000 as Weight).saturating_mul(s as Weight)) // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) + .saturating_add((1_000 as Weight).saturating_mul(z as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Multisig Multisigs (r:1 w:1) // Storage: Multisig Calls (r:1 w:1) fn as_multi_approve_store(s: u32, z: u32, ) -> Weight { - (56_596_000 as Weight) + (32_581_000 as Weight) // Standard Error: 1_000 - .saturating_add((183_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((135_000 as Weight).saturating_mul(s as Weight)) // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(z as Weight)) + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -215,29 +216,29 @@ impl WeightInfo for () { // Storage: Multisig Calls (r:1 w:1) // Storage: System Account (r:1 w:1) fn as_multi_complete(s: u32, z: u32, ) -> Weight { - (72_391_000 as Weight) + (39_215_000 as Weight) // Standard Error: 1_000 - .saturating_add((268_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((221_000 as Weight).saturating_mul(s as Weight)) // Standard Error: 0 - .saturating_add((4_000 as Weight).saturating_mul(z as Weight)) + .saturating_add((2_000 as Weight).saturating_mul(z as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } // Storage: Multisig Multisigs (r:1 w:1) // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) fn approve_as_multi_create(s: u32, ) -> Weight { - (52_543_000 as Weight) - // Standard Error: 0 - .saturating_add((164_000 as Weight).saturating_mul(s as Weight)) + (28_572_000 as Weight) + // Standard Error: 1_000 + .saturating_add((146_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Multisig Multisigs (r:1 w:1) // Storage: Multisig Calls (r:1 w:0) fn approve_as_multi_approve(s: u32, ) -> Weight { - (30_764_000 as Weight) + (18_032_000 as Weight) // Standard Error: 0 - .saturating_add((180_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((151_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -245,18 +246,18 @@ impl WeightInfo for () { // Storage: Multisig Calls (r:1 w:1) // Storage: System Account (r:1 w:1) fn approve_as_multi_complete(s: u32, ) -> Weight { - (113_631_000 as Weight) - // Standard Error: 3_000 - .saturating_add((283_000 as Weight).saturating_mul(s as Weight)) + (56_353_000 as Weight) + // Standard Error: 1_000 + .saturating_add((239_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } // Storage: Multisig Multisigs (r:1 w:1) // Storage: Multisig Calls (r:1 w:1) fn cancel_as_multi(s: u32, ) -> Weight { - (86_310_000 as Weight) + (44_544_000 as Weight) // Standard Error: 0 - .saturating_add((166_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((158_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } diff --git a/frame/nicks/Cargo.toml b/frame/nicks/Cargo.toml index 221a386c752a4..bf5afd26ebb59 100644 --- a/frame/nicks/Cargo.toml +++ b/frame/nicks/Cargo.toml @@ -16,13 +16,13 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } [features] diff --git a/frame/nicks/src/lib.rs b/frame/nicks/src/lib.rs index 9e4ecf8b2b1a3..632ff7b0a8083 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -110,11 +110,10 @@ pub mod pallet { /// The lookup table for names. #[pallet::storage] pub(super) type NameOf = - StorageMap<_, Twox64Concat, T::AccountId, (Vec, BalanceOf)>; + StorageMap<_, Twox64Concat, T::AccountId, (BoundedVec, BalanceOf)>; #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] pub struct Pallet(_); #[pallet::call] @@ -139,8 +138,9 @@ pub mod pallet { pub fn set_name(origin: OriginFor, name: Vec) -> DispatchResult { let sender = ensure_signed(origin)?; - ensure!(name.len() >= T::MinLength::get() as usize, Error::::TooShort); - ensure!(name.len() <= T::MaxLength::get() as usize, Error::::TooLong); + let bounded_name: BoundedVec<_, _> = + name.try_into().map_err(|()| Error::::TooLong)?; + ensure!(bounded_name.len() >= T::MinLength::get() as usize, Error::::TooShort); let deposit = if let Some((_, deposit)) = >::get(&sender) { Self::deposit_event(Event::::NameChanged { who: sender.clone() }); @@ -152,7 +152,7 @@ pub mod pallet { deposit }; - >::insert(&sender, (name, deposit)); + >::insert(&sender, (bounded_name, deposit)); Ok(()) } @@ -181,7 +181,7 @@ pub mod pallet { /// Remove an account's name and take charge of the deposit. /// - /// Fails if `who` has not been named. The deposit is dealt with through `T::Slashed` + /// Fails if `target` has not been named. The deposit is dealt with through `T::Slashed` /// imbalance handler. /// /// The dispatch origin for this call must match `T::ForceOrigin`. @@ -230,9 +230,11 @@ pub mod pallet { ) -> DispatchResult { T::ForceOrigin::ensure_origin(origin)?; + let bounded_name: BoundedVec<_, _> = + name.try_into().map_err(|()| Error::::TooLong)?; let target = T::Lookup::lookup(target)?; let deposit = >::get(&target).map(|x| x.1).unwrap_or_else(Zero::zero); - >::insert(&target, (name, deposit)); + >::insert(&target, (bounded_name, deposit)); Self::deposit_event(Event::::NameForced { target }); Ok(()) @@ -356,9 +358,15 @@ mod tests { assert_ok!(Nicks::set_name(Origin::signed(2), b"Dave".to_vec())); assert_eq!(Balances::reserved_balance(2), 2); - assert_ok!(Nicks::force_name(Origin::signed(1), 2, b"Dr. David Brubeck, III".to_vec())); + assert_noop!( + Nicks::force_name(Origin::signed(1), 2, b"Dr. David Brubeck, III".to_vec()), + Error::::TooLong, + ); + assert_ok!(Nicks::force_name(Origin::signed(1), 2, b"Dr. Brubeck, III".to_vec())); assert_eq!(Balances::reserved_balance(2), 2); - assert_eq!(>::get(2).unwrap(), (b"Dr. David Brubeck, III".to_vec(), 2)); + let (name, amount) = >::get(2).unwrap(); + assert_eq!(name, b"Dr. Brubeck, III".to_vec()); + assert_eq!(amount, 2); }); } diff --git a/frame/node-authorization/Cargo.toml b/frame/node-authorization/Cargo.toml index 610e536a2c818..0d64251885383 100644 --- a/frame/node-authorization/Cargo.toml +++ b/frame/node-authorization/Cargo.toml @@ -16,9 +16,9 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } log = { version = "0.4.14", default-features = false } diff --git a/frame/offences/Cargo.toml b/frame/offences/Cargo.toml index 49aa1d770e5b5..053708c8b247b 100644 --- a/frame/offences/Cargo.toml +++ b/frame/offences/Cargo.toml @@ -17,16 +17,16 @@ pallet-balances = { version = "4.0.0-dev", default-features = false, path = "../ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -serde = { version = "1.0.132", optional = true } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +serde = { version = "1.0.136", optional = true } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-staking = { version = "4.0.0-dev", default-features = false, path = "../../primitives/staking" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } log = { version = "0.4.14", default-features = false } [dev-dependencies] -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } [features] default = ["std"] diff --git a/frame/offences/benchmarking/Cargo.toml b/frame/offences/benchmarking/Cargo.toml index 2764eedc1191b..9742545383227 100644 --- a/frame/offences/benchmarking/Cargo.toml +++ b/frame/offences/benchmarking/Cargo.toml @@ -29,7 +29,7 @@ pallet-session = { version = "4.0.0-dev", default-features = false, path = "../. pallet-staking = { version = "4.0.0-dev", default-features = false, features = [ "runtime-benchmarks", ], path = "../../staking" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } sp-staking = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/staking" } sp-std = { version = "4.0.0", default-features = false, path = "../../../primitives/std" } frame-election-provider-support = { version = "4.0.0-dev", default-features = false, path = "../../election-provider-support" } @@ -37,8 +37,8 @@ frame-election-provider-support = { version = "4.0.0-dev", default-features = fa [dev-dependencies] pallet-staking-reward-curve = { version = "4.0.0-dev", path = "../../staking/reward-curve" } pallet-timestamp = { version = "4.0.0-dev", path = "../../timestamp" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } -sp-io = { version = "4.0.0-dev", path = "../../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../../primitives/io" } [features] default = ["std"] diff --git a/frame/offences/benchmarking/src/lib.rs b/frame/offences/benchmarking/src/lib.rs index 4d6a182034c9e..8688090206c36 100644 --- a/frame/offences/benchmarking/src/lib.rs +++ b/frame/offences/benchmarking/src/lib.rs @@ -24,7 +24,7 @@ mod mock; use sp_std::{prelude::*, vec}; use frame_benchmarking::{account, benchmarks}; -use frame_support::traits::{Currency, ValidatorSet, ValidatorSetWithIdentification}; +use frame_support::traits::{Currency, Get, ValidatorSet, ValidatorSetWithIdentification}; use frame_system::{Config as SystemConfig, Pallet as System, RawOrigin}; use sp_runtime::{ @@ -275,7 +275,7 @@ benchmarks! { let r in 1 .. MAX_REPORTERS; // we skip 1 offender, because in such case there is no slashing let o in 2 .. MAX_OFFENDERS; - let n in 0 .. MAX_NOMINATORS.min(::MAX_NOMINATIONS); + let n in 0 .. MAX_NOMINATORS.min(::MaxNominations::get()); // Make r reporters let mut reporters = vec![]; @@ -381,7 +381,7 @@ benchmarks! { } report_offence_grandpa { - let n in 0 .. MAX_NOMINATORS.min(::MAX_NOMINATIONS); + let n in 0 .. MAX_NOMINATORS.min(::MaxNominations::get()); // for grandpa equivocation reports the number of reporters // and offenders is always 1 @@ -405,6 +405,7 @@ benchmarks! { } verify { // make sure that all slashes have been applied + #[cfg(test)] assert_eq!( System::::event_count(), 0 + 1 // offence @@ -416,7 +417,7 @@ benchmarks! { } report_offence_babe { - let n in 0 .. MAX_NOMINATORS.min(::MAX_NOMINATIONS); + let n in 0 .. MAX_NOMINATORS.min(::MaxNominations::get()); // for babe equivocation reports the number of reporters // and offenders is always 1 @@ -440,6 +441,7 @@ benchmarks! { } verify { // make sure that all slashes have been applied + #[cfg(test)] assert_eq!( System::::event_count(), 0 + 1 // offence diff --git a/frame/offences/benchmarking/src/mock.rs b/frame/offences/benchmarking/src/mock.rs index 598ba650dfffb..3b5e640867c5a 100644 --- a/frame/offences/benchmarking/src/mock.rs +++ b/frame/offences/benchmarking/src/mock.rs @@ -156,7 +156,7 @@ impl onchain::Config for Test { } impl pallet_staking::Config for Test { - const MAX_NOMINATIONS: u32 = 16; + type MaxNominations = ConstU32<16>; type Currency = Balances; type UnixTime = pallet_timestamp::Pallet; type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; diff --git a/frame/preimage/Cargo.toml b/frame/preimage/Cargo.toml index 17fed986f7575..66ef8467be28a 100644 --- a/frame/preimage/Cargo.toml +++ b/frame/preimage/Cargo.toml @@ -14,15 +14,15 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" } -sp-core = { version = "4.1.0-dev", default-features = false, optional = true, path = "../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-core = { version = "5.0.0", default-features = false, optional = true, path = "../../primitives/core" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core", default-features = false } +sp-core = { version = "5.0.0", path = "../../primitives/core", default-features = false } pallet-balances = { version = "4.0.0-dev", path = "../balances" } [features] diff --git a/frame/preimage/src/weights.rs b/frame/preimage/src/weights.rs index fab5cdfb67361..0d7f583727c99 100644 --- a/frame/preimage/src/weights.rs +++ b/frame/preimage/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_preimage //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-12-10, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,7 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/preimage/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -91,58 +93,58 @@ impl WeightInfo for SubstrateWeight { // Storage: Preimage StatusFor (r:1 w:1) // Storage: Preimage PreimageFor (r:0 w:1) fn unnote_preimage() -> Weight { - (60_560_000 as Weight) + (39_239_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) // Storage: Preimage PreimageFor (r:0 w:1) fn unnote_no_deposit_preimage() -> Weight { - (37_575_000 as Weight) + (24_905_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) fn request_preimage() -> Weight { - (56_868_000 as Weight) + (37_451_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) fn request_no_deposit_preimage() -> Weight { - (37_058_000 as Weight) + (23_397_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) fn request_unnoted_preimage() -> Weight { - (21_500_000 as Weight) + (13_407_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) fn request_requested_preimage() -> Weight { - (7_798_000 as Weight) + (4_202_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) // Storage: Preimage PreimageFor (r:0 w:1) fn unrequest_preimage() -> Weight { - (37_771_000 as Weight) + (24_858_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) // Storage: Preimage PreimageFor (r:0 w:1) fn unrequest_unnoted_preimage() -> Weight { - (22_913_000 as Weight) + (13_763_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) fn unrequest_multi_referenced_preimage() -> Weight { - (7_608_000 as Weight) + (4_262_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -180,58 +182,58 @@ impl WeightInfo for () { // Storage: Preimage StatusFor (r:1 w:1) // Storage: Preimage PreimageFor (r:0 w:1) fn unnote_preimage() -> Weight { - (60_560_000 as Weight) + (39_239_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) // Storage: Preimage PreimageFor (r:0 w:1) fn unnote_no_deposit_preimage() -> Weight { - (37_575_000 as Weight) + (24_905_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) fn request_preimage() -> Weight { - (56_868_000 as Weight) + (37_451_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) fn request_no_deposit_preimage() -> Weight { - (37_058_000 as Weight) + (23_397_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) fn request_unnoted_preimage() -> Weight { - (21_500_000 as Weight) + (13_407_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) fn request_requested_preimage() -> Weight { - (7_798_000 as Weight) + (4_202_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) // Storage: Preimage PreimageFor (r:0 w:1) fn unrequest_preimage() -> Weight { - (37_771_000 as Weight) + (24_858_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) // Storage: Preimage PreimageFor (r:0 w:1) fn unrequest_unnoted_preimage() -> Weight { - (22_913_000 as Weight) + (13_763_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Preimage StatusFor (r:1 w:1) fn unrequest_multi_referenced_preimage() -> Weight { - (7_608_000 as Weight) + (4_262_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } diff --git a/frame/proxy/Cargo.toml b/frame/proxy/Cargo.toml index a07ecb4997741..f0bd9391789bb 100644 --- a/frame/proxy/Cargo.toml +++ b/frame/proxy/Cargo.toml @@ -17,14 +17,14 @@ codec = { package = "parity-scale-codec", version = "2.2.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } pallet-utility = { version = "4.0.0-dev", path = "../utility" } diff --git a/frame/proxy/src/benchmarking.rs b/frame/proxy/src/benchmarking.rs index ceed2e6ab22dc..f3098c6ad1274 100644 --- a/frame/proxy/src/benchmarking.rs +++ b/frame/proxy/src/benchmarking.rs @@ -33,7 +33,7 @@ fn assert_last_event(generic_event: ::Event) { fn add_proxies(n: u32, maybe_who: Option) -> Result<(), &'static str> { let caller = maybe_who.unwrap_or_else(|| whitelisted_caller()); - T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); + T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value() / 2u32.into()); for i in 0..n { Proxy::::add_proxy( RawOrigin::Signed(caller.clone()).into(), @@ -51,12 +51,12 @@ fn add_announcements( maybe_real: Option, ) -> Result<(), &'static str> { let caller = maybe_who.unwrap_or_else(|| account("caller", 0, SEED)); - T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); + T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value() / 2u32.into()); let real = if let Some(real) = maybe_real { real } else { let real = account("real", 0, SEED); - T::Currency::make_free_balance_be(&real, BalanceOf::::max_value()); + T::Currency::make_free_balance_be(&real, BalanceOf::::max_value() / 2u32.into()); Proxy::::add_proxy( RawOrigin::Signed(real.clone()).into(), caller.clone(), @@ -80,7 +80,7 @@ benchmarks! { let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::(p, None)?; // In this case the caller is the "target" proxy let caller: T::AccountId = account("target", p - 1, SEED); - T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); + T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value() / 2u32.into()); // ... and "real" is the traditional caller. This is not a typo. let real: T::AccountId = whitelisted_caller(); let call: ::Call = frame_system::Call::::remark { remark: vec![] }.into(); @@ -95,7 +95,7 @@ benchmarks! { // In this case the caller is the "target" proxy let caller: T::AccountId = account("anonymous", 0, SEED); let delegate: T::AccountId = account("target", p - 1, SEED); - T::Currency::make_free_balance_be(&delegate, BalanceOf::::max_value()); + T::Currency::make_free_balance_be(&delegate, BalanceOf::::max_value() / 2u32.into()); // ... and "real" is the traditional caller. This is not a typo. let real: T::AccountId = whitelisted_caller(); let call: ::Call = frame_system::Call::::remark { remark: vec![] }.into(); @@ -115,7 +115,7 @@ benchmarks! { let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::(p, None)?; // In this case the caller is the "target" proxy let caller: T::AccountId = account("target", p - 1, SEED); - T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); + T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value() / 2u32.into()); // ... and "real" is the traditional caller. This is not a typo. let real: T::AccountId = whitelisted_caller(); let call: ::Call = frame_system::Call::::remark { remark: vec![] }.into(); @@ -136,7 +136,7 @@ benchmarks! { let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::(p, None)?; // In this case the caller is the "target" proxy let caller: T::AccountId = account("target", p - 1, SEED); - T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); + T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value() / 2u32.into()); // ... and "real" is the traditional caller. This is not a typo. let real: T::AccountId = whitelisted_caller(); let call: ::Call = frame_system::Call::::remark { remark: vec![] }.into(); @@ -157,7 +157,7 @@ benchmarks! { let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::(p, None)?; // In this case the caller is the "target" proxy let caller: T::AccountId = account("target", p - 1, SEED); - T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); + T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value() / 2u32.into()); // ... and "real" is the traditional caller. This is not a typo. let real: T::AccountId = whitelisted_caller(); add_announcements::(a, Some(caller.clone()), None)?; diff --git a/frame/proxy/src/weights.rs b/frame/proxy/src/weights.rs index bde4fd761179c..176f8683e0b5f 100644 --- a/frame/proxy/src/weights.rs +++ b/frame/proxy/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_proxy //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/proxy/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -62,38 +63,42 @@ pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { // Storage: Proxy Proxies (r:1 w:0) fn proxy(p: u32, ) -> Weight { - (23_213_000 as Weight) - // Standard Error: 2_000 - .saturating_add((153_000 as Weight).saturating_mul(p as Weight)) + (13_323_000 as Weight) + // Standard Error: 1_000 + .saturating_add((114_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) } // 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 { - (53_286_000 as Weight) - // Standard Error: 2_000 - .saturating_add((549_000 as Weight).saturating_mul(a as Weight)) + (28_825_000 as Weight) + // Standard Error: 1_000 + .saturating_add((254_000 as Weight).saturating_mul(a as Weight)) // Standard Error: 2_000 - .saturating_add((138_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((120_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Proxy Announcements (r:1 w:1) // Storage: System Account (r:1 w:1) - fn remove_announcement(a: u32, _p: u32, ) -> Weight { - (36_864_000 as Weight) - // Standard Error: 2_000 - .saturating_add((550_000 as Weight).saturating_mul(a as Weight)) + fn remove_announcement(a: u32, p: u32, ) -> Weight { + (20_594_000 as Weight) + // Standard Error: 1_000 + .saturating_add((259_000 as Weight).saturating_mul(a as Weight)) + // Standard Error: 1_000 + .saturating_add((15_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Proxy Announcements (r:1 w:1) // Storage: System Account (r:1 w:1) - fn reject_announcement(a: u32, _p: u32, ) -> Weight { - (36_755_000 as Weight) + fn reject_announcement(a: u32, p: u32, ) -> Weight { + (20_316_000 as Weight) + // Standard Error: 1_000 + .saturating_add((265_000 as Weight).saturating_mul(a as Weight)) // Standard Error: 1_000 - .saturating_add((550_000 as Weight).saturating_mul(a as Weight)) + .saturating_add((18_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -101,52 +106,52 @@ impl WeightInfo for SubstrateWeight { // Storage: Proxy Announcements (r:1 w:1) // Storage: System Account (r:1 w:1) fn announce(a: u32, p: u32, ) -> Weight { - (50_765_000 as Weight) + (27_696_000 as Weight) // Standard Error: 2_000 - .saturating_add((547_000 as Weight).saturating_mul(a as Weight)) + .saturating_add((241_000 as Weight).saturating_mul(a as Weight)) // Standard Error: 2_000 - .saturating_add((141_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((111_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Proxy Proxies (r:1 w:1) fn add_proxy(p: u32, ) -> Weight { - (35_556_000 as Weight) - // Standard Error: 3_000 - .saturating_add((211_000 as Weight).saturating_mul(p as Weight)) + (22_849_000 as Weight) + // Standard Error: 2_000 + .saturating_add((140_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Proxy Proxies (r:1 w:1) fn remove_proxy(p: u32, ) -> Weight { - (35_284_000 as Weight) - // Standard Error: 3_000 - .saturating_add((229_000 as Weight).saturating_mul(p as Weight)) + (19_350_000 as Weight) + // Standard Error: 2_000 + .saturating_add((147_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Proxy Proxies (r:1 w:1) fn remove_proxies(p: u32, ) -> Weight { - (34_449_000 as Weight) + (18_878_000 as Weight) // Standard Error: 2_000 - .saturating_add((146_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((112_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) // Storage: Proxy Proxies (r:1 w:1) fn anonymous(p: u32, ) -> Weight { - (49_149_000 as Weight) + (25_743_000 as Weight) // Standard Error: 2_000 - .saturating_add((15_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((25_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Proxy Proxies (r:1 w:1) fn kill_anonymous(p: u32, ) -> Weight { - (36_399_000 as Weight) + (20_484_000 as Weight) // Standard Error: 2_000 - .saturating_add((152_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((105_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -156,38 +161,42 @@ impl WeightInfo for SubstrateWeight { impl WeightInfo for () { // Storage: Proxy Proxies (r:1 w:0) fn proxy(p: u32, ) -> Weight { - (23_213_000 as Weight) - // Standard Error: 2_000 - .saturating_add((153_000 as Weight).saturating_mul(p as Weight)) + (13_323_000 as Weight) + // Standard Error: 1_000 + .saturating_add((114_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) } // 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 { - (53_286_000 as Weight) - // Standard Error: 2_000 - .saturating_add((549_000 as Weight).saturating_mul(a as Weight)) + (28_825_000 as Weight) + // Standard Error: 1_000 + .saturating_add((254_000 as Weight).saturating_mul(a as Weight)) // Standard Error: 2_000 - .saturating_add((138_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((120_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Proxy Announcements (r:1 w:1) // Storage: System Account (r:1 w:1) - fn remove_announcement(a: u32, _p: u32, ) -> Weight { - (36_864_000 as Weight) - // Standard Error: 2_000 - .saturating_add((550_000 as Weight).saturating_mul(a as Weight)) + fn remove_announcement(a: u32, p: u32, ) -> Weight { + (20_594_000 as Weight) + // Standard Error: 1_000 + .saturating_add((259_000 as Weight).saturating_mul(a as Weight)) + // Standard Error: 1_000 + .saturating_add((15_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Proxy Announcements (r:1 w:1) // Storage: System Account (r:1 w:1) - fn reject_announcement(a: u32, _p: u32, ) -> Weight { - (36_755_000 as Weight) + fn reject_announcement(a: u32, p: u32, ) -> Weight { + (20_316_000 as Weight) + // Standard Error: 1_000 + .saturating_add((265_000 as Weight).saturating_mul(a as Weight)) // Standard Error: 1_000 - .saturating_add((550_000 as Weight).saturating_mul(a as Weight)) + .saturating_add((18_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -195,52 +204,52 @@ impl WeightInfo for () { // Storage: Proxy Announcements (r:1 w:1) // Storage: System Account (r:1 w:1) fn announce(a: u32, p: u32, ) -> Weight { - (50_765_000 as Weight) + (27_696_000 as Weight) // Standard Error: 2_000 - .saturating_add((547_000 as Weight).saturating_mul(a as Weight)) + .saturating_add((241_000 as Weight).saturating_mul(a as Weight)) // Standard Error: 2_000 - .saturating_add((141_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((111_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Proxy Proxies (r:1 w:1) fn add_proxy(p: u32, ) -> Weight { - (35_556_000 as Weight) - // Standard Error: 3_000 - .saturating_add((211_000 as Weight).saturating_mul(p as Weight)) + (22_849_000 as Weight) + // Standard Error: 2_000 + .saturating_add((140_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Proxy Proxies (r:1 w:1) fn remove_proxy(p: u32, ) -> Weight { - (35_284_000 as Weight) - // Standard Error: 3_000 - .saturating_add((229_000 as Weight).saturating_mul(p as Weight)) + (19_350_000 as Weight) + // Standard Error: 2_000 + .saturating_add((147_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Proxy Proxies (r:1 w:1) fn remove_proxies(p: u32, ) -> Weight { - (34_449_000 as Weight) + (18_878_000 as Weight) // Standard Error: 2_000 - .saturating_add((146_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((112_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: unknown [0x3a65787472696e7369635f696e646578] (r:1 w:0) // Storage: Proxy Proxies (r:1 w:1) fn anonymous(p: u32, ) -> Weight { - (49_149_000 as Weight) + (25_743_000 as Weight) // Standard Error: 2_000 - .saturating_add((15_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((25_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Proxy Proxies (r:1 w:1) fn kill_anonymous(p: u32, ) -> Weight { - (36_399_000 as Weight) + (20_484_000 as Weight) // Standard Error: 2_000 - .saturating_add((152_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((105_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } diff --git a/frame/randomness-collective-flip/Cargo.toml b/frame/randomness-collective-flip/Cargo.toml index a29e7ac7b3265..a93585700f2b0 100644 --- a/frame/randomness-collective-flip/Cargo.toml +++ b/frame/randomness-collective-flip/Cargo.toml @@ -16,15 +16,15 @@ targets = ["x86_64-unknown-linux-gnu"] safe-mix = { version = "1.0", default-features = false } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } [features] default = ["std"] diff --git a/frame/randomness-collective-flip/src/lib.rs b/frame/randomness-collective-flip/src/lib.rs index a74c58405de4f..b72aa665550cf 100644 --- a/frame/randomness-collective-flip/src/lib.rs +++ b/frame/randomness-collective-flip/src/lib.rs @@ -91,7 +91,6 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] pub struct Pallet(_); #[pallet::config] @@ -103,9 +102,7 @@ pub mod pallet { let parent_hash = >::parent_hash(); >::mutate(|ref mut values| { - if values.len() < RANDOM_MATERIAL_LEN as usize { - values.push(parent_hash) - } else { + if values.try_push(parent_hash).is_err() { let index = block_number_to_index::(block_number); values[index] = parent_hash; } @@ -120,7 +117,8 @@ pub mod pallet { /// the oldest hash. #[pallet::storage] #[pallet::getter(fn random_material)] - pub(super) type RandomMaterial = StorageValue<_, Vec, ValueQuery>; + pub(super) type RandomMaterial = + StorageValue<_, BoundedVec>, ValueQuery>; } impl Randomness for Pallet { diff --git a/frame/recovery/Cargo.toml b/frame/recovery/Cargo.toml index 53fe6851564dd..88da65327e2f0 100644 --- a/frame/recovery/Cargo.toml +++ b/frame/recovery/Cargo.toml @@ -16,13 +16,13 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } [features] diff --git a/frame/recovery/src/lib.rs b/frame/recovery/src/lib.rs index f5a57843a983b..adc5c0b895c5f 100644 --- a/frame/recovery/src/lib.rs +++ b/frame/recovery/src/lib.rs @@ -154,7 +154,7 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_runtime::traits::{CheckedAdd, CheckedMul, Dispatchable, SaturatedConversion}; use sp_std::prelude::*; @@ -163,7 +163,7 @@ use frame_support::{ dispatch::PostDispatchInfo, traits::{BalanceStatus, Currency, ReservableCurrency}, weights::GetDispatchInfo, - RuntimeDebug, + BoundedVec, RuntimeDebug, }; pub use pallet::*; @@ -176,21 +176,23 @@ mod tests; type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +type FriendsOf = BoundedVec<::AccountId, ::MaxFriends>; + /// An active recovery process. -#[derive(Clone, Eq, PartialEq, Encode, Decode, Default, RuntimeDebug, TypeInfo)] -pub struct ActiveRecovery { +#[derive(Clone, Eq, PartialEq, Encode, Decode, Default, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct ActiveRecovery { /// The block number when the recovery process started. created: BlockNumber, /// The amount held in reserve of the `depositor`, /// To be returned once this recovery process is closed. deposit: Balance, /// The friends which have vouched so far. Always sorted. - friends: Vec, + friends: Friends, } /// Configuration for recovering an account. -#[derive(Clone, Eq, PartialEq, Encode, Decode, Default, RuntimeDebug, TypeInfo)] -pub struct RecoveryConfig { +#[derive(Clone, Eq, PartialEq, Encode, Decode, Default, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct RecoveryConfig { /// The minimum number of blocks since the start of the recovery process before the account /// can be recovered. delay_period: BlockNumber, @@ -198,7 +200,7 @@ pub struct RecoveryConfig { /// to be returned once this configuration is removed. deposit: Balance, /// The list of friends which can help recover an account. Always sorted. - friends: Vec, + friends: Friends, /// The number of approving friends needed to recover an account. threshold: u16, } @@ -212,7 +214,6 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] pub struct Pallet(_); /// Configuration trait. @@ -245,8 +246,13 @@ pub mod pallet { type FriendDepositFactor: Get>; /// The maximum amount of friends allowed in a recovery configuration. + /// + /// NOTE: The threshold programmed in this Pallet uses u16, so it does + /// not really make sense to have a limit here greater than u16::MAX. + /// But also, that is a lot more than you should probably set this value + /// to anyway... #[pallet::constant] - type MaxFriends: Get; + type MaxFriends: Get; /// The base amount of currency needed to reserve for starting a recovery. /// @@ -324,7 +330,7 @@ pub mod pallet { _, Twox64Concat, T::AccountId, - RecoveryConfig, T::AccountId>, + RecoveryConfig, FriendsOf>, >; /// Active recovery attempts. @@ -339,7 +345,7 @@ pub mod pallet { T::AccountId, Twox64Concat, T::AccountId, - ActiveRecovery, T::AccountId>, + ActiveRecovery, FriendsOf>, >; /// The list of allowed proxy accounts. @@ -458,12 +464,12 @@ pub mod pallet { ensure!(threshold >= 1, Error::::ZeroThreshold); ensure!(!friends.is_empty(), Error::::NotEnoughFriends); ensure!(threshold as usize <= friends.len(), Error::::NotEnoughFriends); - let max_friends = T::MaxFriends::get() as usize; - ensure!(friends.len() <= max_friends, Error::::MaxFriends); - ensure!(Self::is_sorted_and_unique(&friends), Error::::NotSorted); + let bounded_friends: FriendsOf = + friends.try_into().map_err(|()| Error::::MaxFriends)?; + ensure!(Self::is_sorted_and_unique(&bounded_friends), Error::::NotSorted); // Total deposit is base fee + number of friends * factor fee let friend_deposit = T::FriendDepositFactor::get() - .checked_mul(&friends.len().saturated_into()) + .checked_mul(&bounded_friends.len().saturated_into()) .ok_or(ArithmeticError::Overflow)?; let total_deposit = T::ConfigDepositBase::get() .checked_add(&friend_deposit) @@ -471,8 +477,12 @@ pub mod pallet { // Reserve the deposit T::Currency::reserve(&who, total_deposit)?; // Create the recovery configuration - let recovery_config = - RecoveryConfig { delay_period, deposit: total_deposit, friends, threshold }; + let recovery_config = RecoveryConfig { + delay_period, + deposit: total_deposit, + friends: bounded_friends, + threshold, + }; // Create the recovery configuration storage item >::insert(&who, recovery_config); @@ -519,7 +529,7 @@ pub mod pallet { let recovery_status = ActiveRecovery { created: >::block_number(), deposit: recovery_deposit, - friends: vec![], + friends: Default::default(), }; // Create the active recovery storage item >::insert(&account, &who, recovery_status); @@ -571,7 +581,10 @@ pub mod pallet { // Either insert the vouch, or return an error that the user already vouched. match active_recovery.friends.binary_search(&who) { Ok(_pos) => Err(Error::::AlreadyVouched)?, - Err(pos) => active_recovery.friends.insert(pos, who.clone()), + Err(pos) => active_recovery + .friends + .try_insert(pos, who.clone()) + .map_err(|()| Error::::MaxFriends)?, } // Update storage with the latest details >::insert(&lost, &rescuer, active_recovery); diff --git a/frame/recovery/src/mock.rs b/frame/recovery/src/mock.rs index 577aa7dee7117..2088f9eb0937e 100644 --- a/frame/recovery/src/mock.rs +++ b/frame/recovery/src/mock.rs @@ -22,7 +22,7 @@ use super::*; use crate as recovery; use frame_support::{ parameter_types, - traits::{ConstU16, ConstU32, ConstU64, OnFinalize, OnInitialize}, + traits::{ConstU32, ConstU64, OnFinalize, OnInitialize}, }; use sp_core::H256; use sp_runtime::{ @@ -105,7 +105,7 @@ impl Config for Test { type Currency = Balances; type ConfigDepositBase = ConfigDepositBase; type FriendDepositFactor = FriendDepositFactor; - type MaxFriends = ConstU16<3>; + type MaxFriends = ConstU32<3>; type RecoveryDeposit = RecoveryDeposit; } diff --git a/frame/recovery/src/tests.rs b/frame/recovery/src/tests.rs index 7d1da6353a3ad..16fc678d357bb 100644 --- a/frame/recovery/src/tests.rs +++ b/frame/recovery/src/tests.rs @@ -18,7 +18,7 @@ //! Tests for the module. use super::*; -use frame_support::{assert_noop, assert_ok, traits::Currency}; +use frame_support::{assert_noop, assert_ok, bounded_vec, traits::Currency}; use mock::{ new_test_ext, run_to_block, Balances, BalancesCall, Call, Origin, Recovery, RecoveryCall, Test, }; @@ -201,8 +201,12 @@ fn create_recovery_works() { // Base 10 + 1 per friends = 13 total reserved assert_eq!(Balances::reserved_balance(5), 13); // Recovery configuration is correctly stored - let recovery_config = - RecoveryConfig { delay_period, deposit: 13, friends: friends.clone(), threshold }; + let recovery_config = RecoveryConfig { + delay_period, + deposit: 13, + friends: friends.try_into().unwrap(), + threshold, + }; assert_eq!(Recovery::recovery_config(5), Some(recovery_config)); }); } @@ -254,7 +258,8 @@ fn initiate_recovery_works() { // Deposit is reserved assert_eq!(Balances::reserved_balance(1), 10); // Recovery status object is created correctly - let recovery_status = ActiveRecovery { created: 0, deposit: 10, friends: vec![] }; + let recovery_status = + ActiveRecovery { created: 0, deposit: 10, friends: Default::default() }; assert_eq!(>::get(&5, &1), Some(recovery_status)); // Multiple users can attempt to recover the same account assert_ok!(Recovery::initiate_recovery(Origin::signed(2), 5)); @@ -314,7 +319,8 @@ fn vouch_recovery_works() { assert_ok!(Recovery::vouch_recovery(Origin::signed(4), 5, 1)); assert_ok!(Recovery::vouch_recovery(Origin::signed(3), 5, 1)); // Final recovery status object is updated correctly - let recovery_status = ActiveRecovery { created: 0, deposit: 10, friends: vec![2, 3, 4] }; + let recovery_status = + ActiveRecovery { created: 0, deposit: 10, friends: bounded_vec![2, 3, 4] }; assert_eq!(>::get(&5, &1), Some(recovery_status)); }); } diff --git a/frame/referenda/Cargo.toml b/frame/referenda/Cargo.toml new file mode 100644 index 0000000000000..46ede8c1eed08 --- /dev/null +++ b/frame/referenda/Cargo.toml @@ -0,0 +1,56 @@ +[package] +name = "pallet-referenda" +version = "4.0.0-dev" +authors = ["Parity Technologies "] +edition = "2018" +license = "Apache-2.0" +homepage = "https://substrate.io" +repository = "https://github.com/paritytech/substrate/" +description = "FRAME pallet for inclusive on-chain decisions" +readme = "README.md" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +serde = { version = "1.0.136", optional = true, features = ["derive"] } +codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [ + "derive", +] } +scale-info = { version = "1.0", default-features = false, features = ["derive"] } +sp-std = { version = "4.0.0-dev", default-features = false, path = "../../primitives/std" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } +frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } +frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } +frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } +assert_matches = { version = "1.5", optional = true } + +[dev-dependencies] +sp-core = { version = "5.0.0", path = "../../primitives/core" } +pallet-balances = { version = "4.0.0-dev", path = "../balances" } +pallet-scheduler = { version = "4.0.0-dev", path = "../scheduler" } +pallet-preimage = { version = "4.0.0-dev", path = "../preimage" } +assert_matches = { version = "1.5" } + +[features] +default = ["std"] +std = [ + "serde", + "codec/std", + "scale-info/std", + "sp-std/std", + "sp-io/std", + "frame-benchmarking/std", + "frame-support/std", + "sp-runtime/std", + "frame-system/std", +] +runtime-benchmarks = [ + "frame-benchmarking", + "frame-system/runtime-benchmarks", + "frame-support/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "assert_matches", +] +try-runtime = ["frame-support/try-runtime"] diff --git a/frame/referenda/README.md b/frame/referenda/README.md new file mode 100644 index 0000000000000..85031a0113033 --- /dev/null +++ b/frame/referenda/README.md @@ -0,0 +1,8 @@ +# Referenda Pallet + +- [`assembly::Config`](https://docs.rs/pallet-assembly/latest/pallet_assembly/trait.Config.html) +- [`Call`](https://docs.rs/pallet-assembly/latest/pallet_assembly/enum.Call.html) + +## Overview + +The Assembly pallet handles the administration of general stakeholder voting. diff --git a/frame/referenda/src/benchmarking.rs b/frame/referenda/src/benchmarking.rs new file mode 100644 index 0000000000000..76a8173f16c9a --- /dev/null +++ b/frame/referenda/src/benchmarking.rs @@ -0,0 +1,520 @@ +// This file is part of Substrate. + +// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Democracy pallet benchmarking. + +use super::*; +use crate::Pallet as Referenda; +use assert_matches::assert_matches; +use frame_benchmarking::{account, benchmarks, whitelist_account}; +use frame_support::{ + assert_ok, + traits::{Currency, EnsureOrigin}, +}; +use frame_system::RawOrigin; +use sp_runtime::traits::{Bounded, Hash}; + +const SEED: u32 = 0; + +#[allow(dead_code)] +fn assert_last_event(generic_event: ::Event) { + frame_system::Pallet::::assert_last_event(generic_event.into()); +} + +fn funded_account(name: &'static str, index: u32) -> T::AccountId { + let caller: T::AccountId = account(name, index, SEED); + T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); + caller +} + +fn create_referendum() -> (T::AccountId, ReferendumIndex) { + let caller = funded_account::("caller", 0); + whitelist_account!(caller); + assert_ok!(Referenda::::submit( + RawOrigin::Signed(caller.clone()).into(), + RawOrigin::Root.into(), + T::Hashing::hash_of(&0), + AtOrAfter::After(0u32.into()) + )); + let index = ReferendumCount::::get() - 1; + (caller, index) +} + +fn place_deposit(index: ReferendumIndex) { + let caller = funded_account::("caller", 0); + whitelist_account!(caller); + assert_ok!(Referenda::::place_decision_deposit( + RawOrigin::Signed(caller.clone()).into(), + index, + )); +} + +fn nudge(index: ReferendumIndex) { + assert_ok!(Referenda::::nudge_referendum(RawOrigin::Root.into(), index)); +} + +fn fill_queue( + index: ReferendumIndex, + spaces: u32, + pass_after: u32, +) -> Vec { + // First, create enough other referendums to fill the track. + let mut others = vec![]; + for _ in 0..info::(index).max_deciding { + let (_caller, index) = create_referendum::(); + place_deposit::(index); + others.push(index); + } + + // We will also need enough referenda which are queued and passing, we want `MaxQueued - 1` + // in order to force the maximum amount of work to insert ours into the queue. + for _ in spaces..T::MaxQueued::get() { + let (_caller, index) = create_referendum::(); + place_deposit::(index); + make_passing_after::(index, Perbill::from_percent(pass_after)); + others.push(index); + } + + // Skip to when they can start being decided. + skip_prepare_period::(index); + + // Manually nudge the other referenda first to ensure that they begin. + others.iter().for_each(|&i| nudge::(i)); + + others +} + +fn info(index: ReferendumIndex) -> &'static TrackInfoOf { + let status = Referenda::::ensure_ongoing(index).unwrap(); + T::Tracks::info(status.track).expect("Id value returned from T::Tracks") +} + +fn make_passing_after(index: ReferendumIndex, period_portion: Perbill) { + let turnout = info::(index).min_turnout.threshold(period_portion); + let approval = info::(index).min_approval.threshold(period_portion); + Referenda::::access_poll(index, |status| { + if let PollStatus::Ongoing(tally, ..) = status { + *tally = T::Tally::from_requirements(turnout, approval); + } + }); +} + +fn make_passing(index: ReferendumIndex) { + Referenda::::access_poll(index, |status| { + if let PollStatus::Ongoing(tally, ..) = status { + *tally = T::Tally::unanimity(); + } + }); +} + +fn make_failing(index: ReferendumIndex) { + Referenda::::access_poll(index, |status| { + if let PollStatus::Ongoing(tally, ..) = status { + *tally = T::Tally::default(); + } + }); +} + +fn skip_prepare_period(index: ReferendumIndex) { + let status = Referenda::::ensure_ongoing(index).unwrap(); + let prepare_period_over = status.submitted + info::(index).prepare_period; + frame_system::Pallet::::set_block_number(prepare_period_over); +} + +fn skip_decision_period(index: ReferendumIndex) { + let status = Referenda::::ensure_ongoing(index).unwrap(); + let decision_period_over = status.deciding.unwrap().since + info::(index).decision_period; + frame_system::Pallet::::set_block_number(decision_period_over); +} + +fn skip_confirm_period(index: ReferendumIndex) { + let status = Referenda::::ensure_ongoing(index).unwrap(); + let confirm_period_over = status.deciding.unwrap().confirming.unwrap(); + frame_system::Pallet::::set_block_number(confirm_period_over); +} + +fn skip_timeout_period(index: ReferendumIndex) { + let status = Referenda::::ensure_ongoing(index).unwrap(); + let timeout_period_over = status.submitted + T::UndecidingTimeout::get(); + frame_system::Pallet::::set_block_number(timeout_period_over); +} + +fn alarm_time(index: ReferendumIndex) -> T::BlockNumber { + let status = Referenda::::ensure_ongoing(index).unwrap(); + status.alarm.unwrap().0 +} + +fn is_confirming(index: ReferendumIndex) -> bool { + let status = Referenda::::ensure_ongoing(index).unwrap(); + matches!( + status, + ReferendumStatus { deciding: Some(DecidingStatus { confirming: Some(_), .. }), .. } + ) +} + +fn is_not_confirming(index: ReferendumIndex) -> bool { + let status = Referenda::::ensure_ongoing(index).unwrap(); + matches!( + status, + ReferendumStatus { deciding: Some(DecidingStatus { confirming: None, .. }), .. } + ) +} + +benchmarks! { + submit { + let caller = funded_account::("caller", 0); + whitelist_account!(caller); + }: _( + RawOrigin::Signed(caller), + RawOrigin::Root.into(), + T::Hashing::hash_of(&0), + AtOrAfter::After(0u32.into()) + ) verify { + let index = ReferendumCount::::get().checked_sub(1).unwrap(); + assert_matches!(ReferendumInfoFor::::get(index), Some(ReferendumInfo::Ongoing(_))); + } + + place_decision_deposit_preparing { + let (caller, index) = create_referendum::(); + }: place_decision_deposit(RawOrigin::Signed(caller), index) + verify { + assert!(Referenda::::ensure_ongoing(index).unwrap().decision_deposit.is_some()); + } + + place_decision_deposit_queued { + let (caller, index) = create_referendum::(); + fill_queue::(index, 1, 90); + }: place_decision_deposit(RawOrigin::Signed(caller), index) + verify { + let track = Referenda::::ensure_ongoing(index).unwrap().track; + assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get()); + assert_eq!(TrackQueue::::get(&track)[0], (index, 0u32.into())); + } + + place_decision_deposit_not_queued { + let (caller, index) = create_referendum::(); + fill_queue::(index, 0, 90); + }: place_decision_deposit(RawOrigin::Signed(caller), index) + verify { + let track = Referenda::::ensure_ongoing(index).unwrap().track; + assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get()); + assert!(TrackQueue::::get(&track).into_iter().all(|(i, _)| i != index)); + } + + place_decision_deposit_passing { + let (caller, index) = create_referendum::(); + skip_prepare_period::(index); + make_passing::(index); + }: place_decision_deposit(RawOrigin::Signed(caller), index) + verify { + assert!(is_confirming::(index)); + } + + place_decision_deposit_failing { + let (caller, index) = create_referendum::(); + skip_prepare_period::(index); + }: place_decision_deposit(RawOrigin::Signed(caller), index) + verify { + assert!(is_not_confirming::(index)); + } + + refund_decision_deposit { + let (caller, index) = create_referendum::(); + place_deposit::(index); + assert_ok!(Referenda::::cancel(T::CancelOrigin::successful_origin(), index)); + }: _(RawOrigin::Signed(caller), index) + verify { + assert_matches!(ReferendumInfoFor::::get(index), Some(ReferendumInfo::Cancelled(_, _, None))); + } + + cancel { + let (_caller, index) = create_referendum::(); + place_deposit::(index); + }: _(T::CancelOrigin::successful_origin(), index) + verify { + assert_matches!(ReferendumInfoFor::::get(index), Some(ReferendumInfo::Cancelled(..))); + } + + kill { + let (_caller, index) = create_referendum::(); + place_deposit::(index); + }: _(T::KillOrigin::successful_origin(), index) + verify { + assert_matches!(ReferendumInfoFor::::get(index), Some(ReferendumInfo::Killed(..))); + } + + one_fewer_deciding_queue_empty { + let (_caller, index) = create_referendum::(); + place_deposit::(index); + skip_prepare_period::(index); + nudge::(index); + let track = Referenda::::ensure_ongoing(index).unwrap().track; + assert_ok!(Referenda::::cancel(T::CancelOrigin::successful_origin(), index)); + assert_eq!(DecidingCount::::get(&track), 1); + }: one_fewer_deciding(RawOrigin::Root, track.clone()) + verify { + assert_eq!(DecidingCount::::get(&track), 0); + } + + one_fewer_deciding_failing { + let (_caller, index) = create_referendum::(); + // No spaces free in the queue. + let queued = fill_queue::(index, 0, 90); + let track = Referenda::::ensure_ongoing(index).unwrap().track; + assert_ok!(Referenda::::cancel(T::CancelOrigin::successful_origin(), queued[0])); + assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get()); + let deciding_count = DecidingCount::::get(&track); + }: one_fewer_deciding(RawOrigin::Root, track.clone()) + verify { + assert_eq!(DecidingCount::::get(&track), deciding_count); + assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get() - 1); + assert!(queued.into_iter().skip(1).all(|i| Referenda::::ensure_ongoing(i) + .unwrap() + .deciding + .map_or(true, |d| d.confirming.is_none()) + )); + } + + one_fewer_deciding_passing { + let (_caller, index) = create_referendum::(); + // No spaces free in the queue. + let queued = fill_queue::(index, 0, 0); + let track = Referenda::::ensure_ongoing(index).unwrap().track; + assert_ok!(Referenda::::cancel(T::CancelOrigin::successful_origin(), queued[0])); + assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get()); + let deciding_count = DecidingCount::::get(&track); + }: one_fewer_deciding(RawOrigin::Root, track.clone()) + verify { + assert_eq!(DecidingCount::::get(&track), deciding_count); + assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get() - 1); + assert!(queued.into_iter().skip(1).all(|i| Referenda::::ensure_ongoing(i) + .unwrap() + .deciding + .map_or(true, |d| d.confirming.is_some()) + )); + } + + nudge_referendum_requeued_insertion { + // First create our referendum and place the deposit. It will be failing. + let (_caller, index) = create_referendum::(); + place_deposit::(index); + fill_queue::(index, 0, 90); + + // Now nudge ours, with the track now full and the queue full of referenda with votes, + // ours will not be in the queue. + nudge::(index); + let track = Referenda::::ensure_ongoing(index).unwrap().track; + assert!(TrackQueue::::get(&track).into_iter().all(|(i, _)| i != index)); + + // Now alter the voting, so that ours goes into pole-position and shifts others down. + make_passing::(index); + }: nudge_referendum(RawOrigin::Root, index) + verify { + let t = TrackQueue::::get(&track); + assert_eq!(t.len() as u32, T::MaxQueued::get()); + assert_eq!(t[t.len() - 1].0, index); + } + + nudge_referendum_requeued_slide { + // First create our referendum and place the deposit. It will be failing. + let (_caller, index) = create_referendum::(); + place_deposit::(index); + fill_queue::(index, 1, 90); + + // Now nudge ours, with the track now full, ours will be queued, but with no votes, it + // will have the worst position. + nudge::(index); + let track = Referenda::::ensure_ongoing(index).unwrap().track; + assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get()); + assert_eq!(TrackQueue::::get(&track)[0], (index, 0u32.into())); + + // Now alter the voting, so that ours leap-frogs all into the best position. + make_passing::(index); + }: nudge_referendum(RawOrigin::Root, index) + verify { + let t = TrackQueue::::get(&track); + assert_eq!(t.len() as u32, T::MaxQueued::get()); + assert_eq!(t[t.len() - 1].0, index); + } + + nudge_referendum_queued { + // NOTE: worst possible queue situation is with a queue full of passing refs with one slot + // free and this failing. It would result in `QUEUE_SIZE - 1` items being shifted for the + // insertion at the beginning. + + // First create our referendum and place the deposit. It will be failing. + let (_caller, index) = create_referendum::(); + place_deposit::(index); + fill_queue::(index, 1, 0); + + let track = Referenda::::ensure_ongoing(index).unwrap().track; + assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get() - 1); + assert!(TrackQueue::::get(&track).into_iter().all(|(_, v)| v > 0u32.into())); + + // Then nudge ours, with the track now full, ours will be queued. + }: nudge_referendum(RawOrigin::Root, index) + verify { + assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get()); + assert_eq!(TrackQueue::::get(&track)[0], (index, 0u32.into())); + } + + nudge_referendum_not_queued { + // First create our referendum and place the deposit. It will be failing. + let (_caller, index) = create_referendum::(); + place_deposit::(index); + fill_queue::(index, 0, 0); + + let track = Referenda::::ensure_ongoing(index).unwrap().track; + assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get()); + assert!(TrackQueue::::get(&track).into_iter().all(|(_, v)| v > 0u32.into())); + + // Then nudge ours, with the track now full, ours will be queued. + }: nudge_referendum(RawOrigin::Root, index) + verify { + assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get()); + assert!(TrackQueue::::get(&track).into_iter().all(|(i, _)| i != index)); + } + + nudge_referendum_no_deposit { + let (_caller, index) = create_referendum::(); + skip_prepare_period::(index); + }: nudge_referendum(RawOrigin::Root, index) + verify { + let status = Referenda::::ensure_ongoing(index).unwrap(); + assert_matches!(status, ReferendumStatus { deciding: None, .. }); + } + + nudge_referendum_preparing { + let (_caller, index) = create_referendum::(); + place_deposit::(index); + }: nudge_referendum(RawOrigin::Root, index) + verify { + let status = Referenda::::ensure_ongoing(index).unwrap(); + assert_matches!(status, ReferendumStatus { deciding: None, .. }); + } + + nudge_referendum_timed_out { + let (_caller, index) = create_referendum::(); + skip_timeout_period::(index); + }: nudge_referendum(RawOrigin::Root, index) + verify { + let info = ReferendumInfoFor::::get(index).unwrap(); + assert_matches!(info, ReferendumInfo::TimedOut(..)); + } + + nudge_referendum_begin_deciding_failing { + let (_caller, index) = create_referendum::(); + place_deposit::(index); + skip_prepare_period::(index); + }: nudge_referendum(RawOrigin::Root, index) + verify { + assert!(is_not_confirming::(index)); + } + + nudge_referendum_begin_deciding_passing { + let (_caller, index) = create_referendum::(); + place_deposit::(index); + make_passing::(index); + skip_prepare_period::(index); + }: nudge_referendum(RawOrigin::Root, index) + verify { + assert!(is_confirming::(index)); + } + + nudge_referendum_begin_confirming { + let (_caller, index) = create_referendum::(); + place_deposit::(index); + skip_prepare_period::(index); + nudge::(index); + assert!(!is_confirming::(index)); + make_passing::(index); + }: nudge_referendum(RawOrigin::Root, index) + verify { + assert!(is_confirming::(index)); + } + + nudge_referendum_end_confirming { + let (_caller, index) = create_referendum::(); + place_deposit::(index); + skip_prepare_period::(index); + make_passing::(index); + nudge::(index); + assert!(is_confirming::(index)); + make_failing::(index); + }: nudge_referendum(RawOrigin::Root, index) + verify { + assert!(!is_confirming::(index)); + } + + nudge_referendum_continue_not_confirming { + let (_caller, index) = create_referendum::(); + place_deposit::(index); + skip_prepare_period::(index); + nudge::(index); + assert!(!is_confirming::(index)); + let old_alarm = alarm_time::(index); + make_passing_after::(index, Perbill::from_percent(50)); + }: nudge_referendum(RawOrigin::Root, index) + verify { + assert_ne!(old_alarm, alarm_time::(index)); + assert!(!is_confirming::(index)); + } + + nudge_referendum_continue_confirming { + let (_caller, index) = create_referendum::(); + place_deposit::(index); + make_passing::(index); + skip_prepare_period::(index); + nudge::(index); + assert!(is_confirming::(index)); + let old_alarm = alarm_time::(index); + }: nudge_referendum(RawOrigin::Root, index) + verify { + assert!(is_confirming::(index)); + } + + nudge_referendum_approved { + let (_caller, index) = create_referendum::(); + place_deposit::(index); + skip_prepare_period::(index); + make_passing::(index); + nudge::(index); + skip_confirm_period::(index); + }: nudge_referendum(RawOrigin::Root, index) + verify { + let info = ReferendumInfoFor::::get(index).unwrap(); + assert_matches!(info, ReferendumInfo::Approved(..)); + } + + nudge_referendum_rejected { + let (_caller, index) = create_referendum::(); + place_deposit::(index); + skip_prepare_period::(index); + nudge::(index); + skip_decision_period::(index); + }: nudge_referendum(RawOrigin::Root, index) + verify { + let info = ReferendumInfoFor::::get(index).unwrap(); + assert_matches!(info, ReferendumInfo::Rejected(..)); + } + + impl_benchmark_test_suite!( + Referenda, + crate::mock::new_test_ext(), + crate::mock::Test + ); +} diff --git a/frame/referenda/src/branch.rs b/frame/referenda/src/branch.rs new file mode 100644 index 0000000000000..6a4efa31e15e2 --- /dev/null +++ b/frame/referenda/src/branch.rs @@ -0,0 +1,172 @@ +// This file is part of Substrate. + +// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Helpers for managing the different weights in various algorithmic branches. + +use super::Config; +use crate::weights::WeightInfo; + +/// Branches within the `begin_deciding` function. +pub enum BeginDecidingBranch { + Passing, + Failing, +} + +/// Branches within the `service_referendum` function. +pub enum ServiceBranch { + Fail, + NoDeposit, + Preparing, + Queued, + NotQueued, + RequeuedInsertion, + RequeuedSlide, + BeginDecidingPassing, + BeginDecidingFailing, + BeginConfirming, + ContinueConfirming, + EndConfirming, + ContinueNotConfirming, + Approved, + Rejected, + TimedOut, +} + +impl From for ServiceBranch { + fn from(x: BeginDecidingBranch) -> Self { + use BeginDecidingBranch::*; + use ServiceBranch::*; + match x { + Passing => BeginDecidingPassing, + Failing => BeginDecidingFailing, + } + } +} + +impl ServiceBranch { + /// Return the weight of the `nudge` function when it takes the branch denoted by `self`. + pub fn weight_of_nudge(self) -> frame_support::weights::Weight { + use ServiceBranch::*; + match self { + NoDeposit => T::WeightInfo::nudge_referendum_no_deposit(), + Preparing => T::WeightInfo::nudge_referendum_preparing(), + Queued => T::WeightInfo::nudge_referendum_queued(), + NotQueued => T::WeightInfo::nudge_referendum_not_queued(), + RequeuedInsertion => T::WeightInfo::nudge_referendum_requeued_insertion(), + RequeuedSlide => T::WeightInfo::nudge_referendum_requeued_slide(), + BeginDecidingPassing => T::WeightInfo::nudge_referendum_begin_deciding_passing(), + BeginDecidingFailing => T::WeightInfo::nudge_referendum_begin_deciding_failing(), + BeginConfirming => T::WeightInfo::nudge_referendum_begin_confirming(), + ContinueConfirming => T::WeightInfo::nudge_referendum_continue_confirming(), + EndConfirming => T::WeightInfo::nudge_referendum_end_confirming(), + ContinueNotConfirming => T::WeightInfo::nudge_referendum_continue_not_confirming(), + Approved => T::WeightInfo::nudge_referendum_approved(), + Rejected => T::WeightInfo::nudge_referendum_rejected(), + TimedOut | Fail => T::WeightInfo::nudge_referendum_timed_out(), + } + } + + /// Return the maximum possible weight of the `nudge` function. + pub fn max_weight_of_nudge() -> frame_support::weights::Weight { + 0.max(T::WeightInfo::nudge_referendum_no_deposit()) + .max(T::WeightInfo::nudge_referendum_preparing()) + .max(T::WeightInfo::nudge_referendum_queued()) + .max(T::WeightInfo::nudge_referendum_not_queued()) + .max(T::WeightInfo::nudge_referendum_requeued_insertion()) + .max(T::WeightInfo::nudge_referendum_requeued_slide()) + .max(T::WeightInfo::nudge_referendum_begin_deciding_passing()) + .max(T::WeightInfo::nudge_referendum_begin_deciding_failing()) + .max(T::WeightInfo::nudge_referendum_begin_confirming()) + .max(T::WeightInfo::nudge_referendum_continue_confirming()) + .max(T::WeightInfo::nudge_referendum_end_confirming()) + .max(T::WeightInfo::nudge_referendum_continue_not_confirming()) + .max(T::WeightInfo::nudge_referendum_approved()) + .max(T::WeightInfo::nudge_referendum_rejected()) + .max(T::WeightInfo::nudge_referendum_timed_out()) + } + + /// Return the weight of the `place_decision_deposit` function when it takes the branch denoted + /// by `self`. + pub fn weight_of_deposit(self) -> Option { + use ServiceBranch::*; + Some(match self { + Preparing => T::WeightInfo::place_decision_deposit_preparing(), + Queued => T::WeightInfo::place_decision_deposit_queued(), + NotQueued => T::WeightInfo::place_decision_deposit_not_queued(), + BeginDecidingPassing => T::WeightInfo::place_decision_deposit_passing(), + BeginDecidingFailing => T::WeightInfo::place_decision_deposit_failing(), + BeginConfirming | + ContinueConfirming | + EndConfirming | + ContinueNotConfirming | + Approved | + Rejected | + RequeuedInsertion | + RequeuedSlide | + TimedOut | + Fail | + NoDeposit => return None, + }) + } + + /// Return the maximum possible weight of the `place_decision_deposit` function. + pub fn max_weight_of_deposit() -> frame_support::weights::Weight { + 0.max(T::WeightInfo::place_decision_deposit_preparing()) + .max(T::WeightInfo::place_decision_deposit_queued()) + .max(T::WeightInfo::place_decision_deposit_not_queued()) + .max(T::WeightInfo::place_decision_deposit_passing()) + .max(T::WeightInfo::place_decision_deposit_failing()) + } +} + +/// Branches that the `one_fewer_deciding` function may take. +pub enum OneFewerDecidingBranch { + QueueEmpty, + BeginDecidingPassing, + BeginDecidingFailing, +} + +impl From for OneFewerDecidingBranch { + fn from(x: BeginDecidingBranch) -> Self { + use BeginDecidingBranch::*; + use OneFewerDecidingBranch::*; + match x { + Passing => BeginDecidingPassing, + Failing => BeginDecidingFailing, + } + } +} + +impl OneFewerDecidingBranch { + /// Return the weight of the `one_fewer_deciding` function when it takes the branch denoted + /// by `self`. + pub fn weight(self) -> frame_support::weights::Weight { + use OneFewerDecidingBranch::*; + match self { + QueueEmpty => T::WeightInfo::one_fewer_deciding_queue_empty(), + BeginDecidingPassing => T::WeightInfo::one_fewer_deciding_passing(), + BeginDecidingFailing => T::WeightInfo::one_fewer_deciding_failing(), + } + } + + /// Return the maximum possible weight of the `one_fewer_deciding` function. + pub fn max_weight() -> frame_support::weights::Weight { + 0.max(T::WeightInfo::one_fewer_deciding_queue_empty()) + .max(T::WeightInfo::one_fewer_deciding_passing()) + .max(T::WeightInfo::one_fewer_deciding_failing()) + } +} diff --git a/frame/referenda/src/lib.rs b/frame/referenda/src/lib.rs new file mode 100644 index 0000000000000..fb8e9aa6a6db7 --- /dev/null +++ b/frame/referenda/src/lib.rs @@ -0,0 +1,1065 @@ +// This file is part of Substrate. + +// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! # Referenda Pallet +//! +//! ## Overview +//! +//! A pallet for executing referenda. No voting logic is present here, and the `Polling` and +//! `PollStatus` traits are used to allow the voting logic (likely in a pallet) to be utilized. +//! +//! A referendum is a vote on whether a proposal should be dispatched from a particular origin. The +//! origin is used to determine which one of several _tracks_ that a referendum happens under. +//! Tracks each have their own configuration which governs the voting process and parameters. +//! +//! A referendum's lifecycle has three main stages: Preparation, deciding and conclusion. +//! Referenda are considered "ongoing" immediately after submission until their eventual +//! conclusion, and votes may be cast throughout. +//! +//! In order to progress from preparating to being decided, three things must be in place: +//! - There must have been a *Decision Deposit* placed, an amount determined by the track. Anyone +//! may place this deposit. +//! - A period must have elapsed since submission of the referendum. This period is known as the +//! *Preparation Period* and is determined by the track. +//! - The track must not already be at capacity with referendum being decided. The maximum number of +//! referenda which may be being decided simultaneously is determined by the track. +//! +//! In order to become concluded, one of three things must happen: +//! - The referendum should remain in an unbroken _Passing_ state for a period of time. This +//! is known as the _Confirmation Period_ and is determined by the track. A referendum is considered +//! _Passing_ when there is a sufficiently high turnout and approval, given the amount of time it +//! has been being decided. Generally the threshold for what counts as being "sufficiently high" +//! will reduce over time. The curves setting these thresholds are determined by the track. In this +//! case, the referendum is considered _Approved_ and the proposal is scheduled for dispatch. +//! - The referendum reaches the end of its deciding phase outside not _Passing_. It ends in +//! rejection and the proposal is not dispatched. +//! - The referendum is cancelled. +//! +//! A general time-out is also in place and referenda which exist in preparation for too long may +//! conclude without ever entering into a deciding stage. +//! +//! Once a referendum is concluded, the decision deposit may be refunded. +//! +//! - [`Config`] +//! - [`Call`] + +#![recursion_limit = "256"] +#![cfg_attr(not(feature = "std"), no_std)] + +use codec::{Codec, Encode}; +use frame_support::{ + ensure, + traits::{ + schedule::{ + v2::{Anon as ScheduleAnon, Named as ScheduleNamed}, + DispatchTime, MaybeHashed, + }, + Currency, Get, LockIdentifier, LockableCurrency, OnUnbalanced, OriginTrait, PollStatus, + Polling, ReservableCurrency, VoteTally, + }, + BoundedVec, +}; +use scale_info::TypeInfo; +use sp_runtime::{ + traits::{AtLeast32BitUnsigned, Dispatchable, One, Saturating, Zero}, + DispatchError, Perbill, +}; +use sp_std::{fmt::Debug, prelude::*}; + +mod branch; +mod types; +pub mod weights; +use branch::{BeginDecidingBranch, OneFewerDecidingBranch, ServiceBranch}; +pub use pallet::*; +pub use types::{ + AtOrAfter, BalanceOf, CallOf, Curve, DecidingStatus, DecidingStatusOf, Deposit, InsertSorted, + NegativeImbalanceOf, PalletsOriginOf, ReferendumIndex, ReferendumInfo, ReferendumInfoOf, + ReferendumStatus, ReferendumStatusOf, ScheduleAddressOf, TallyOf, TrackIdOf, TrackInfo, + TrackInfoOf, TracksInfo, VotesOf, +}; +pub use weights::WeightInfo; + +#[cfg(test)] +mod mock; +#[cfg(test)] +mod tests; + +#[cfg(feature = "runtime-benchmarks")] +pub mod benchmarking; + +const ASSEMBLY_ID: LockIdentifier = *b"assembly"; + +#[frame_support::pallet] +pub mod pallet { + use super::*; + use frame_support::{pallet_prelude::*, traits::EnsureOrigin, Parameter}; + use frame_system::pallet_prelude::*; + use sp_runtime::DispatchResult; + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + #[pallet::without_storage_info] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config + Sized { + // System level stuff. + type Call: Parameter + Dispatchable + From>; + type Event: From> + IsType<::Event>; + /// Weight information for extrinsics in this pallet. + type WeightInfo: WeightInfo; + /// The Scheduler. + type Scheduler: ScheduleAnon, PalletsOriginOf, Hash = Self::Hash> + + ScheduleNamed, PalletsOriginOf, Hash = Self::Hash>; + /// Currency type for this pallet. + type Currency: ReservableCurrency + + LockableCurrency; + + // Origins and unbalances. + /// Origin from which any vote may be cancelled. + type CancelOrigin: EnsureOrigin; + /// Origin from which any vote may be killed. + type KillOrigin: EnsureOrigin; + /// Handler for the unbalanced reduction when slashing a preimage deposit. + type Slash: OnUnbalanced>; + /// The counting type for votes. Usually just balance. + type Votes: AtLeast32BitUnsigned + Copy + Parameter + Member; + /// The tallying type. + type Tally: VoteTally + Default + Clone + Codec + Eq + Debug + TypeInfo; + + // Constants + /// The minimum amount to be used as a deposit for a public referendum proposal. + #[pallet::constant] + type SubmissionDeposit: Get>; + + /// Maximum size of the referendum queue for a single track. + #[pallet::constant] + type MaxQueued: Get; + + /// The number of blocks after submission that a referendum must begin being decided by. + /// Once this passes, then anyone may cancel the referendum. + #[pallet::constant] + type UndecidingTimeout: Get; + + /// Quantization level for the referendum wakeup scheduler. A higher number will result in + /// fewer storage reads/writes needed for smaller voters, but also result in delays to the + /// automatic referendum status changes. Explicit servicing instructions are unaffected. + #[pallet::constant] + type AlarmInterval: Get; + + // The other stuff. + /// Information concerning the different referendum tracks. + type Tracks: TracksInfo< + BalanceOf, + Self::BlockNumber, + Origin = ::PalletsOrigin, + >; + } + + /// The next free referendum index, aka the number of referenda started so far. + #[pallet::storage] + pub type ReferendumCount = StorageValue<_, ReferendumIndex, ValueQuery>; + + /// Information concerning any given referendum. + /// + /// TWOX-NOTE: SAFE as indexes are not under an attacker’s control. + #[pallet::storage] + pub type ReferendumInfoFor = + StorageMap<_, Blake2_128Concat, ReferendumIndex, ReferendumInfoOf>; + + /// The sorted list of referenda ready to be decided but not yet being decided, ordered by + /// conviction-weighted approvals. + /// + /// This should be empty if `DecidingCount` is less than `TrackInfo::max_deciding`. + #[pallet::storage] + pub type TrackQueue = StorageMap< + _, + Twox64Concat, + TrackIdOf, + BoundedVec<(ReferendumIndex, T::Votes), T::MaxQueued>, + ValueQuery, + >; + + /// The number of referenda being decided currently. + #[pallet::storage] + pub type DecidingCount = StorageMap<_, Twox64Concat, TrackIdOf, u32, ValueQuery>; + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + /// A referendum has being submitted. + Submitted { + /// Index of the referendum. + index: ReferendumIndex, + /// The track (and by extension proposal dispatch origin) of this referendum. + track: TrackIdOf, + /// The hash of the proposal up for referendum. + proposal_hash: T::Hash, + }, + /// The decision deposit has been placed. + DecisionDepositPlaced { + /// Index of the referendum. + index: ReferendumIndex, + /// The account who placed the deposit. + who: T::AccountId, + /// The amount placed by the account. + amount: BalanceOf, + }, + /// The decision deposit has been refunded. + DecisionDepositRefunded { + /// Index of the referendum. + index: ReferendumIndex, + /// The account who placed the deposit. + who: T::AccountId, + /// The amount placed by the account. + amount: BalanceOf, + }, + /// A deposit has been slashaed. + DepositSlashed { + /// The account who placed the deposit. + who: T::AccountId, + /// The amount placed by the account. + amount: BalanceOf, + }, + /// A referendum has moved into the deciding phase. + DecisionStarted { + /// Index of the referendum. + index: ReferendumIndex, + /// The track (and by extension proposal dispatch origin) of this referendum. + track: TrackIdOf, + /// The hash of the proposal up for referendum. + proposal_hash: T::Hash, + /// The current tally of votes in this referendum. + tally: T::Tally, + }, + ConfirmStarted { + /// Index of the referendum. + index: ReferendumIndex, + }, + ConfirmAborted { + /// Index of the referendum. + index: ReferendumIndex, + }, + /// A referendum has ended its confirmation phase and is ready for approval. + Confirmed { + /// Index of the referendum. + index: ReferendumIndex, + /// The final tally of votes in this referendum. + tally: T::Tally, + }, + /// A referendum has been approved and its proposal has been scheduled. + Approved { + /// Index of the referendum. + index: ReferendumIndex, + }, + /// A proposal has been rejected by referendum. + Rejected { + /// Index of the referendum. + index: ReferendumIndex, + /// The final tally of votes in this referendum. + tally: T::Tally, + }, + /// A referendum has been timed out without being decided. + TimedOut { + /// Index of the referendum. + index: ReferendumIndex, + /// The final tally of votes in this referendum. + tally: T::Tally, + }, + /// A referendum has been cancelled. + Cancelled { + /// Index of the referendum. + index: ReferendumIndex, + /// The final tally of votes in this referendum. + tally: T::Tally, + }, + /// A referendum has been killed. + Killed { + /// Index of the referendum. + index: ReferendumIndex, + /// The final tally of votes in this referendum. + tally: T::Tally, + }, + } + + #[pallet::error] + pub enum Error { + /// Referendum is not ongoing. + NotOngoing, + /// Referendum's decision deposit is already paid. + HaveDeposit, + /// The track identifier given was invalid. + BadTrack, + /// There are already a full complement of referendums in progress for this track. + Full, + /// The queue of the track is empty. + QueueEmpty, + /// The referendum index provided is invalid in this context. + BadReferendum, + /// There was nothing to do in the advancement. + NothingToDo, + /// No track exists for the proposal origin. + NoTrack, + /// Any deposit cannot be refunded until after the decision is over. + Unfinished, + /// The deposit refunder is not the depositor. + NoPermission, + /// The deposit cannot be refunded since none was made. + NoDeposit, + } + + #[pallet::call] + impl Pallet { + /// Propose a referendum on a privileged action. + /// + /// - `origin`: must be `Signed` and the account must have `SubmissionDeposit` funds + /// available. + /// - `proposal_origin`: The origin from which the proposal should be executed. + /// - `proposal_hash`: The hash of the proposal preimage. + /// - `enactment_moment`: The moment that the proposal should be enacted. + /// + /// Emits `Submitted`. + #[pallet::weight(T::WeightInfo::submit())] + pub fn submit( + origin: OriginFor, + proposal_origin: PalletsOriginOf, + proposal_hash: T::Hash, + enactment_moment: AtOrAfter, + ) -> DispatchResult { + let who = ensure_signed(origin)?; + + let track = T::Tracks::track_for(&proposal_origin).map_err(|_| Error::::NoTrack)?; + let submission_deposit = Self::take_deposit(who, T::SubmissionDeposit::get())?; + let index = ReferendumCount::::mutate(|x| { + let r = *x; + *x += 1; + r + }); + let now = frame_system::Pallet::::block_number(); + let nudge_call = Call::nudge_referendum { index }; + let status = ReferendumStatus { + track, + origin: proposal_origin, + proposal_hash: proposal_hash.clone(), + enactment: enactment_moment, + submitted: now, + submission_deposit, + decision_deposit: None, + deciding: None, + tally: Default::default(), + in_queue: false, + alarm: Self::set_alarm(nudge_call, now.saturating_add(T::UndecidingTimeout::get())), + }; + ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); + + Self::deposit_event(Event::::Submitted { index, track, proposal_hash }); + Ok(()) + } + + /// Post the Decision Deposit for a referendum. + /// + /// - `origin`: must be `Signed` and the account must have funds available for the + /// referendum's track's Decision Deposit. + /// - `index`: The index of the submitted referendum whose Decision Deposit is yet to be + /// posted. + /// + /// Emits `DecisionDepositPlaced`. + #[pallet::weight(ServiceBranch::max_weight_of_deposit::())] + pub fn place_decision_deposit( + origin: OriginFor, + index: ReferendumIndex, + ) -> DispatchResultWithPostInfo { + let who = ensure_signed(origin)?; + let mut status = Self::ensure_ongoing(index)?; + ensure!(status.decision_deposit.is_none(), Error::::HaveDeposit); + let track = Self::track(status.track).ok_or(Error::::NoTrack)?; + status.decision_deposit = + Some(Self::take_deposit(who.clone(), track.decision_deposit)?); + let now = frame_system::Pallet::::block_number(); + let (info, _, branch) = Self::service_referendum(now, index, status); + ReferendumInfoFor::::insert(index, info); + let e = + Event::::DecisionDepositPlaced { index, who, amount: track.decision_deposit }; + Self::deposit_event(e); + Ok(branch.weight_of_deposit::().into()) + } + + /// Refund the Decision Deposit for a closed referendum back to the depositor. + /// + /// - `origin`: must be `Signed` or `Root`. + /// - `index`: The index of a closed referendum whose Decision Deposit has not yet been + /// refunded. + /// + /// Emits `DecisionDepositRefunded`. + #[pallet::weight(T::WeightInfo::refund_decision_deposit())] + pub fn refund_decision_deposit( + origin: OriginFor, + index: ReferendumIndex, + ) -> DispatchResult { + ensure_signed_or_root(origin)?; + let mut info = ReferendumInfoFor::::get(index).ok_or(Error::::BadReferendum)?; + let deposit = info + .take_decision_deposit() + .map_err(|_| Error::::Unfinished)? + .ok_or(Error::::NoDeposit)?; + Self::refund_deposit(Some(deposit.clone())); + ReferendumInfoFor::::insert(index, info); + let e = Event::::DecisionDepositRefunded { + index, + who: deposit.who, + amount: deposit.amount, + }; + Self::deposit_event(e); + Ok(()) + } + + /// Cancel an ongoing referendum. + /// + /// - `origin`: must be the `CancelOrigin`. + /// - `index`: The index of the referendum to be cancelled. + /// + /// Emits `Cancelled`. + #[pallet::weight(T::WeightInfo::cancel())] + pub fn cancel(origin: OriginFor, index: ReferendumIndex) -> DispatchResult { + T::CancelOrigin::ensure_origin(origin)?; + let status = Self::ensure_ongoing(index)?; + if let Some((_, last_alarm)) = status.alarm { + let _ = T::Scheduler::cancel(last_alarm); + } + Self::note_one_fewer_deciding(status.track); + Self::deposit_event(Event::::Cancelled { index, tally: status.tally }); + let info = ReferendumInfo::Cancelled( + frame_system::Pallet::::block_number(), + status.submission_deposit, + status.decision_deposit, + ); + ReferendumInfoFor::::insert(index, info); + Ok(()) + } + + /// Cancel an ongoing referendum and slash the deposits. + /// + /// - `origin`: must be the `KillOrigin`. + /// - `index`: The index of the referendum to be cancelled. + /// + /// Emits `Killed` and `DepositSlashed`. + #[pallet::weight(T::WeightInfo::kill())] + pub fn kill(origin: OriginFor, index: ReferendumIndex) -> DispatchResult { + T::KillOrigin::ensure_origin(origin)?; + let status = Self::ensure_ongoing(index)?; + if let Some((_, last_alarm)) = status.alarm { + let _ = T::Scheduler::cancel(last_alarm); + } + Self::note_one_fewer_deciding(status.track); + Self::deposit_event(Event::::Killed { index, tally: status.tally }); + Self::slash_deposit(Some(status.submission_deposit.clone())); + Self::slash_deposit(status.decision_deposit.clone()); + let info = ReferendumInfo::Killed(frame_system::Pallet::::block_number()); + ReferendumInfoFor::::insert(index, info); + Ok(()) + } + + /// Advance a referendum onto its next logical state. Only used internally. + /// + /// - `origin`: must be `Root`. + /// - `index`: the referendum to be advanced. + #[pallet::weight(ServiceBranch::max_weight_of_nudge::())] + pub fn nudge_referendum( + origin: OriginFor, + index: ReferendumIndex, + ) -> DispatchResultWithPostInfo { + ensure_root(origin)?; + let now = frame_system::Pallet::::block_number(); + let mut status = Self::ensure_ongoing(index)?; + // This is our wake-up, so we can disregard the alarm. + status.alarm = None; + let (info, dirty, branch) = Self::service_referendum(now, index, status); + if dirty { + ReferendumInfoFor::::insert(index, info); + } + Ok(Some(branch.weight_of_nudge::()).into()) + } + + /// Advance a track onto its next logical state. Only used internally. + /// + /// - `origin`: must be `Root`. + /// - `track`: the track to be advanced. + /// + /// Action item for when there is now one fewer referendum in the deciding phase and the + /// `DecidingCount` is not yet updated. This means that we should either: + /// - begin deciding another referendum (and leave `DecidingCount` alone); or + /// - decrement `DecidingCount`. + #[pallet::weight(OneFewerDecidingBranch::max_weight::())] + pub fn one_fewer_deciding( + origin: OriginFor, + track: TrackIdOf, + ) -> DispatchResultWithPostInfo { + ensure_root(origin)?; + let track_info = T::Tracks::info(track).ok_or(Error::::BadTrack)?; + let mut track_queue = TrackQueue::::get(track); + let branch = + if let Some((index, mut status)) = Self::next_for_deciding(&mut track_queue) { + let now = frame_system::Pallet::::block_number(); + let (maybe_alarm, branch) = + Self::begin_deciding(&mut status, index, now, track_info); + if let Some(set_alarm) = maybe_alarm { + Self::ensure_alarm_at(&mut status, index, set_alarm); + } + ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); + TrackQueue::::insert(track, track_queue); + branch.into() + } else { + DecidingCount::::mutate(track, |x| x.saturating_dec()); + OneFewerDecidingBranch::QueueEmpty + }; + Ok(Some(branch.weight::()).into()) + } + } +} + +impl Polling for Pallet { + type Index = ReferendumIndex; + type Votes = VotesOf; + type Moment = T::BlockNumber; + type Class = TrackIdOf; + + fn classes() -> Vec { + T::Tracks::tracks().iter().map(|x| x.0).collect() + } + + fn access_poll( + index: Self::Index, + f: impl FnOnce(PollStatus<&mut T::Tally, T::BlockNumber, TrackIdOf>) -> R, + ) -> R { + match ReferendumInfoFor::::get(index) { + Some(ReferendumInfo::Ongoing(mut status)) => { + let result = f(PollStatus::Ongoing(&mut status.tally, status.track)); + let now = frame_system::Pallet::::block_number(); + Self::ensure_alarm_at(&mut status, index, now + One::one()); + ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); + result + }, + Some(ReferendumInfo::Approved(end, ..)) => f(PollStatus::Completed(end, true)), + Some(ReferendumInfo::Rejected(end, ..)) => f(PollStatus::Completed(end, false)), + _ => f(PollStatus::None), + } + } + + fn try_access_poll( + index: Self::Index, + f: impl FnOnce( + PollStatus<&mut T::Tally, T::BlockNumber, TrackIdOf>, + ) -> Result, + ) -> Result { + match ReferendumInfoFor::::get(index) { + Some(ReferendumInfo::Ongoing(mut status)) => { + let result = f(PollStatus::Ongoing(&mut status.tally, status.track))?; + let now = frame_system::Pallet::::block_number(); + Self::ensure_alarm_at(&mut status, index, now + One::one()); + ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); + Ok(result) + }, + Some(ReferendumInfo::Approved(end, ..)) => f(PollStatus::Completed(end, true)), + Some(ReferendumInfo::Rejected(end, ..)) => f(PollStatus::Completed(end, false)), + _ => f(PollStatus::None), + } + } + + fn as_ongoing(index: Self::Index) -> Option<(T::Tally, TrackIdOf)> { + Self::ensure_ongoing(index).ok().map(|x| (x.tally, x.track)) + } + + #[cfg(feature = "runtime-benchmarks")] + fn create_ongoing(class: Self::Class) -> Result { + let index = ReferendumCount::::mutate(|x| { + let r = *x; + *x += 1; + r + }); + let now = frame_system::Pallet::::block_number(); + let dummy_account_id = + codec::Decode::decode(&mut sp_runtime::traits::TrailingZeroInput::new(&b"dummy"[..])) + .expect("infinite length input; no invalid inputs for type; qed"); + let mut status = ReferendumStatusOf:: { + track: class, + origin: frame_support::dispatch::RawOrigin::Root.into(), + proposal_hash: ::hash_of(&index), + enactment: AtOrAfter::After(Zero::zero()), + submitted: now, + submission_deposit: Deposit { who: dummy_account_id, amount: Zero::zero() }, + decision_deposit: None, + deciding: None, + tally: Default::default(), + in_queue: false, + alarm: None, + }; + Self::ensure_alarm_at(&mut status, index, sp_runtime::traits::Bounded::max_value()); + ReferendumInfoFor::::insert(index, ReferendumInfo::Ongoing(status)); + Ok(index) + } + + #[cfg(feature = "runtime-benchmarks")] + fn end_ongoing(index: Self::Index, approved: bool) -> Result<(), ()> { + let mut status = Self::ensure_ongoing(index).map_err(|_| ())?; + Self::ensure_no_alarm(&mut status); + Self::note_one_fewer_deciding(status.track); + let now = frame_system::Pallet::::block_number(); + let info = if approved { + ReferendumInfo::Approved(now, status.submission_deposit, status.decision_deposit) + } else { + ReferendumInfo::Rejected(now, status.submission_deposit, status.decision_deposit) + }; + ReferendumInfoFor::::insert(index, info); + Ok(()) + } + + #[cfg(feature = "runtime-benchmarks")] + fn max_ongoing() -> (Self::Class, u32) { + let r = T::Tracks::tracks() + .iter() + .max_by_key(|(_, info)| info.max_deciding) + .expect("Always one class"); + (r.0.clone(), r.1.max_deciding) + } +} + +impl Pallet { + /// Check that referendum `index` is in the `Ongoing` state and return the `ReferendumStatus` + /// value, or `Err` otherwise. + pub fn ensure_ongoing(index: ReferendumIndex) -> Result, DispatchError> { + match ReferendumInfoFor::::get(index) { + Some(ReferendumInfo::Ongoing(status)) => Ok(status), + _ => Err(Error::::NotOngoing.into()), + } + } + + // Enqueue a proposal from a referendum which has presumably passed. + fn schedule_enactment( + index: ReferendumIndex, + track: &TrackInfoOf, + desired: AtOrAfter, + origin: PalletsOriginOf, + call_hash: T::Hash, + ) { + let now = frame_system::Pallet::::block_number(); + let earliest_allowed = now.saturating_add(track.min_enactment_period); + let desired = desired.evaluate(now); + let ok = T::Scheduler::schedule_named( + (ASSEMBLY_ID, "enactment", index).encode(), + DispatchTime::At(desired.max(earliest_allowed)), + None, + 63, + origin, + MaybeHashed::Hash(call_hash), + ) + .is_ok(); + debug_assert!(ok, "LOGIC ERROR: bake_referendum/schedule_named failed"); + } + + /// Set an alarm to dispatch `call` at block number `when`. + fn set_alarm( + call: impl Into>, + when: T::BlockNumber, + ) -> Option<(T::BlockNumber, ScheduleAddressOf)> { + let alarm_interval = T::AlarmInterval::get().max(One::one()); + let when = (when + alarm_interval - One::one()) / alarm_interval * alarm_interval; + let maybe_result = T::Scheduler::schedule( + DispatchTime::At(when), + None, + 128u8, + frame_system::RawOrigin::Root.into(), + MaybeHashed::Value(call.into()), + ) + .ok() + .map(|x| (when, x)); + debug_assert!( + maybe_result.is_some(), + "Unable to schedule a new alarm at #{:?} (now: #{:?})?!", + when, + frame_system::Pallet::::block_number() + ); + maybe_result + } + + /// Mutate a referendum's `status` into the correct deciding state. + /// + /// - `now` is the current block number. + /// - `track` is the track info for the referendum. + /// + /// This will properly set up the `confirming` item. + fn begin_deciding( + status: &mut ReferendumStatusOf, + index: ReferendumIndex, + now: T::BlockNumber, + track: &TrackInfoOf, + ) -> (Option, BeginDecidingBranch) { + let is_passing = Self::is_passing( + &status.tally, + Zero::zero(), + track.decision_period, + &track.min_turnout, + &track.min_approval, + ); + status.in_queue = false; + Self::deposit_event(Event::::DecisionStarted { + index, + tally: status.tally.clone(), + proposal_hash: status.proposal_hash.clone(), + track: status.track.clone(), + }); + let confirming = if is_passing { + Self::deposit_event(Event::::ConfirmStarted { index }); + Some(now.saturating_add(track.confirm_period)) + } else { + None + }; + let deciding_status = DecidingStatus { since: now, confirming }; + let alarm = Self::decision_time(&deciding_status, &status.tally, track); + status.deciding = Some(deciding_status); + let branch = + if is_passing { BeginDecidingBranch::Passing } else { BeginDecidingBranch::Failing }; + (Some(alarm), branch) + } + + /// If it returns `Some`, deciding has begun and it needs waking at the given block number. The + /// second item is the flag for whether it is confirming or not. + /// + /// If `None`, then it is queued and should be nudged automatically as the queue gets drained. + fn ready_for_deciding( + now: T::BlockNumber, + track: &TrackInfoOf, + index: ReferendumIndex, + status: &mut ReferendumStatusOf, + ) -> (Option, ServiceBranch) { + let deciding_count = DecidingCount::::get(status.track); + if deciding_count < track.max_deciding { + // Begin deciding. + DecidingCount::::insert(status.track, deciding_count.saturating_add(1)); + let r = Self::begin_deciding(status, index, now, track); + (r.0, r.1.into()) + } else { + // Add to queue. + let item = (index, status.tally.ayes()); + status.in_queue = true; + TrackQueue::::mutate(status.track, |q| q.insert_sorted_by_key(item, |x| x.1)); + (None, ServiceBranch::Queued) + } + } + + /// Grab the index and status for the referendum which is the highest priority of those for the + /// given track which are ready for being decided. + fn next_for_deciding( + track_queue: &mut BoundedVec<(u32, VotesOf), T::MaxQueued>, + ) -> Option<(ReferendumIndex, ReferendumStatusOf)> { + loop { + let (index, _) = track_queue.pop()?; + match Self::ensure_ongoing(index) { + Ok(s) => return Some((index, s)), + Err(_) => {}, // referendum already timedout or was cancelled. + } + } + } + + /// Schedule a call to `one_fewer_deciding` function via the dispatchable + /// `defer_one_fewer_deciding`. We could theoretically call it immediately (and it would be + /// overall more efficient), however the weights become rather less easy to measure. + fn note_one_fewer_deciding(track: TrackIdOf) { + // Set an alarm call for the next block to nudge the track along. + let now = frame_system::Pallet::::block_number(); + let next_block = now + One::one(); + let alarm_interval = T::AlarmInterval::get().max(One::one()); + let when = (next_block + alarm_interval - One::one()) / alarm_interval * alarm_interval; + + let maybe_result = T::Scheduler::schedule( + DispatchTime::At(when), + None, + 128u8, + frame_system::RawOrigin::Root.into(), + MaybeHashed::Value(Call::one_fewer_deciding { track }.into()), + ); + debug_assert!( + maybe_result.is_ok(), + "Unable to schedule a new alarm at #{:?} (now: #{:?})?!", + when, + now + ); + } + + /// Ensure that a `service_referendum` alarm happens for the referendum `index` at `alarm`. + /// + /// This will do nothing if the alarm is already set. + /// + /// Returns `false` if nothing changed. + fn ensure_alarm_at( + status: &mut ReferendumStatusOf, + index: ReferendumIndex, + alarm: T::BlockNumber, + ) -> bool { + if status.alarm.as_ref().map_or(true, |&(when, _)| when != alarm) { + // Either no alarm or one that was different + Self::ensure_no_alarm(status); + status.alarm = Self::set_alarm(Call::nudge_referendum { index }, alarm); + true + } else { + false + } + } + + /// Advance the state of a referendum, which comes down to: + /// - If it's ready to be decided, start deciding; + /// - If it's not ready to be decided and non-deciding timeout has passed, fail; + /// - If it's ongoing and passing, ensure confirming; if at end of confirmation period, pass. + /// - If it's ongoing and not passing, stop confirning; if it has reached end time, fail. + /// + /// Weight will be a bit different depending on what it does, but it's designed so as not to + /// differ dramatically, especially if `MaxQueue` is kept small. In particular _there are no + /// balance operations in here_. + /// + /// In terms of storage, every call to it is expected to access: + /// - The scheduler, either to insert, remove or alter an entry; + /// - `TrackQueue`, which should be a `BoundedVec` with a low limit (8-16). + /// - `DecidingCount`. + /// + /// Both of the two storage items will only have as many items as there are different tracks, + /// perhaps around 10 and should be whitelisted. + /// + /// The heaviest branch is likely to be when a proposal is placed into, or moved within, the + /// `TrackQueue`. Basically this happens when a referendum is in the deciding queue and receives + /// a vote, or when it moves into the deciding queue. + fn service_referendum( + now: T::BlockNumber, + index: ReferendumIndex, + mut status: ReferendumStatusOf, + ) -> (ReferendumInfoOf, bool, ServiceBranch) { + let mut dirty = false; + // Should it begin being decided? + let track = match Self::track(status.track) { + Some(x) => x, + None => return (ReferendumInfo::Ongoing(status), false, ServiceBranch::Fail), + }; + let timeout = status.submitted + T::UndecidingTimeout::get(); + // Default the alarm to the submission timeout. + let mut alarm = timeout; + let branch; + match &mut status.deciding { + None => { + // Are we already queued for deciding? + if status.in_queue { + // Does our position in the queue need updating? + let ayes = status.tally.ayes(); + let mut queue = TrackQueue::::get(status.track); + let maybe_old_pos = queue.iter().position(|(x, _)| *x == index); + let new_pos = queue.binary_search_by_key(&ayes, |x| x.1).unwrap_or_else(|x| x); + branch = if maybe_old_pos.is_none() && new_pos > 0 { + // Just insert. + queue.force_insert_keep_right(new_pos, (index, ayes)); + ServiceBranch::RequeuedInsertion + } else if let Some(old_pos) = maybe_old_pos { + // We were in the queue - slide into the correct position. + queue[old_pos].1 = ayes; + queue.slide(old_pos, new_pos); + ServiceBranch::RequeuedSlide + } else { + ServiceBranch::NotQueued + }; + TrackQueue::::insert(status.track, queue); + } else { + // Are we ready for deciding? + branch = if status.decision_deposit.is_some() { + let prepare_end = status.submitted.saturating_add(track.prepare_period); + if now >= prepare_end { + let (maybe_alarm, branch) = + Self::ready_for_deciding(now, &track, index, &mut status); + if let Some(set_alarm) = maybe_alarm { + alarm = alarm.min(set_alarm); + } + dirty = true; + branch + } else { + alarm = alarm.min(prepare_end); + ServiceBranch::Preparing + } + } else { + ServiceBranch::NoDeposit + } + } + // If we didn't move into being decided, then check the timeout. + if status.deciding.is_none() && now >= timeout { + // Too long without being decided - end it. + Self::ensure_no_alarm(&mut status); + Self::deposit_event(Event::::TimedOut { index, tally: status.tally }); + return ( + ReferendumInfo::TimedOut( + now, + status.submission_deposit, + status.decision_deposit, + ), + true, + ServiceBranch::TimedOut, + ) + } + }, + Some(deciding) => { + let is_passing = Self::is_passing( + &status.tally, + now.saturating_sub(deciding.since), + track.decision_period, + &track.min_turnout, + &track.min_approval, + ); + branch = if is_passing { + match deciding.confirming.clone() { + Some(t) if now >= t => { + // Passed! + Self::ensure_no_alarm(&mut status); + Self::note_one_fewer_deciding(status.track); + let (desired, call_hash) = (status.enactment, status.proposal_hash); + Self::schedule_enactment( + index, + track, + desired, + status.origin, + call_hash, + ); + Self::deposit_event(Event::::Confirmed { + index, + tally: status.tally, + }); + return ( + ReferendumInfo::Approved( + now, + status.submission_deposit, + status.decision_deposit, + ), + true, + ServiceBranch::Approved, + ) + }, + Some(_) => ServiceBranch::ContinueConfirming, + None => { + // Start confirming + dirty = true; + deciding.confirming = Some(now.saturating_add(track.confirm_period)); + Self::deposit_event(Event::::ConfirmStarted { index }); + ServiceBranch::BeginConfirming + }, + } + } else { + if now >= deciding.since.saturating_add(track.decision_period) { + // Failed! + Self::ensure_no_alarm(&mut status); + Self::note_one_fewer_deciding(status.track); + Self::deposit_event(Event::::Rejected { index, tally: status.tally }); + return ( + ReferendumInfo::Rejected( + now, + status.submission_deposit, + status.decision_deposit, + ), + true, + ServiceBranch::Rejected, + ) + } + if deciding.confirming.is_some() { + // Stop confirming + dirty = true; + deciding.confirming = None; + Self::deposit_event(Event::::ConfirmAborted { index }); + ServiceBranch::EndConfirming + } else { + ServiceBranch::ContinueNotConfirming + } + }; + alarm = Self::decision_time(&deciding, &status.tally, track); + }, + } + + let dirty_alarm = Self::ensure_alarm_at(&mut status, index, alarm); + (ReferendumInfo::Ongoing(status), dirty_alarm || dirty, branch) + } + + /// Determine the point at which a referendum will be accepted, move into confirmation with the + /// given `tally` or end with rejection (whichever happens sooner). + fn decision_time( + deciding: &DecidingStatusOf, + tally: &T::Tally, + track: &TrackInfoOf, + ) -> T::BlockNumber { + deciding.confirming.unwrap_or_else(|| { + // Set alarm to the point where the current voting would make it pass. + let approval = tally.approval(); + let turnout = tally.turnout(); + let until_approval = track.min_approval.delay(approval); + let until_turnout = track.min_turnout.delay(turnout); + let offset = until_turnout.max(until_approval); + deciding.since.saturating_add(offset * track.decision_period) + }) + } + + /// Cancel the alarm in `status`, if one exists. + fn ensure_no_alarm(status: &mut ReferendumStatusOf) { + if let Some((_, last_alarm)) = status.alarm.take() { + // Incorrect alarm - cancel it. + let _ = T::Scheduler::cancel(last_alarm); + } + } + + /// Reserve a deposit and return the `Deposit` instance. + fn take_deposit( + who: T::AccountId, + amount: BalanceOf, + ) -> Result>, DispatchError> { + T::Currency::reserve(&who, amount)?; + Ok(Deposit { who, amount }) + } + + /// Return a deposit, if `Some`. + fn refund_deposit(deposit: Option>>) { + if let Some(Deposit { who, amount }) = deposit { + T::Currency::unreserve(&who, amount); + } + } + + /// Slash a deposit, if `Some`. + fn slash_deposit(deposit: Option>>) { + if let Some(Deposit { who, amount }) = deposit { + T::Slash::on_unbalanced(T::Currency::slash_reserved(&who, amount).0); + Self::deposit_event(Event::::DepositSlashed { who, amount }); + } + } + + /// Get the track info value for the track `id`. + fn track(id: TrackIdOf) -> Option<&'static TrackInfoOf> { + let tracks = T::Tracks::tracks(); + let index = tracks.binary_search_by_key(&id, |x| x.0).unwrap_or_else(|x| x); + Some(&tracks[index].1) + } + + /// Determine whether the given `tally` would result in a referendum passing at `elapsed` blocks + /// into a total decision `period`, given the two curves for `turnout_needed` and + /// `approval_needed`. + fn is_passing( + tally: &T::Tally, + elapsed: T::BlockNumber, + period: T::BlockNumber, + turnout_needed: &Curve, + approval_needed: &Curve, + ) -> bool { + let x = Perbill::from_rational(elapsed.min(period), period); + turnout_needed.passing(x, tally.turnout()) && approval_needed.passing(x, tally.approval()) + } +} diff --git a/frame/referenda/src/mock.rs b/frame/referenda/src/mock.rs new file mode 100644 index 0000000000000..063b124f2b71f --- /dev/null +++ b/frame/referenda/src/mock.rs @@ -0,0 +1,460 @@ +// This file is part of Substrate. + +// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The crate's tests. + +use super::*; +use crate as pallet_referenda; +use codec::{Decode, Encode, MaxEncodedLen}; +use frame_support::{ + assert_ok, ord_parameter_types, parameter_types, + traits::{ + ConstU32, ConstU64, Contains, EqualPrivilegeOnly, OnInitialize, OriginTrait, Polling, + PreimageRecipient, SortedMembers, + }, + weights::Weight, +}; +use frame_system::{EnsureRoot, EnsureSignedBy}; +use sp_core::H256; +use sp_runtime::{ + testing::Header, + traits::{BlakeTwo256, Hash, IdentityLookup}, + DispatchResult, Perbill, +}; + +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; + +frame_support::construct_runtime!( + pub enum Test where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system, + Balances: pallet_balances, + Preimage: pallet_preimage, + Scheduler: pallet_scheduler, + Referenda: pallet_referenda, + } +); + +// Test that a fitlered call can be dispatched. +pub struct BaseFilter; +impl Contains for BaseFilter { + fn contains(call: &Call) -> bool { + !matches!(call, &Call::Balances(pallet_balances::Call::set_balance { .. })) + } +} + +parameter_types! { + pub const BlockHashCount: u64 = 250; + pub BlockWeights: frame_system::limits::BlockWeights = + frame_system::limits::BlockWeights::simple_max(1_000_000); +} +impl frame_system::Config for Test { + type BaseCallFilter = BaseFilter; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Origin = Origin; + type Index = u64; + type BlockNumber = u64; + type Call = Call; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = u64; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = BlockHashCount; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = ConstU32<16>; +} +impl pallet_preimage::Config for Test { + type Event = Event; + type WeightInfo = (); + type Currency = Balances; + type ManagerOrigin = EnsureRoot; + type MaxSize = ConstU32<4096>; + type BaseDeposit = (); + type ByteDeposit = (); +} +parameter_types! { + pub MaximumSchedulerWeight: Weight = 2_000_000_000_000; +} +impl pallet_scheduler::Config for Test { + type Event = Event; + type Origin = Origin; + type PalletsOrigin = OriginCaller; + type Call = Call; + type MaximumWeight = MaximumSchedulerWeight; + type ScheduleOrigin = EnsureRoot; + type MaxScheduledPerBlock = ConstU32<100>; + type WeightInfo = (); + type OriginPrivilegeCmp = EqualPrivilegeOnly; + type PreimageProvider = Preimage; + type NoPreimagePostponement = ConstU64<10>; +} +parameter_types! { + pub const ExistentialDeposit: u64 = 1; + pub const MaxLocks: u32 = 10; +} +impl pallet_balances::Config for Test { + type MaxReserves = (); + type ReserveIdentifier = [u8; 8]; + type MaxLocks = MaxLocks; + type Balance = u64; + type Event = Event; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); +} +parameter_types! { + pub static AlarmInterval: u64 = 1; + pub const SubmissionDeposit: u64 = 2; + pub const MaxQueued: u32 = 3; + pub const UndecidingTimeout: u64 = 20; +} +ord_parameter_types! { + pub const One: u64 = 1; + pub const Two: u64 = 2; + pub const Three: u64 = 3; + pub const Four: u64 = 4; + pub const Five: u64 = 5; + pub const Six: u64 = 6; +} +pub struct OneToFive; +impl SortedMembers for OneToFive { + fn sorted_members() -> Vec { + vec![1, 2, 3, 4, 5] + } + #[cfg(feature = "runtime-benchmarks")] + fn add(_m: &u64) {} +} + +pub struct TestTracksInfo; +impl TracksInfo for TestTracksInfo { + type Id = u8; + type Origin = ::PalletsOrigin; + fn tracks() -> &'static [(Self::Id, TrackInfo)] { + static DATA: [(u8, TrackInfo); 2] = [ + ( + 0u8, + TrackInfo { + name: "root", + max_deciding: 1, + decision_deposit: 10, + prepare_period: 4, + decision_period: 4, + confirm_period: 2, + min_enactment_period: 4, + min_approval: Curve::LinearDecreasing { + begin: Perbill::from_percent(100), + delta: Perbill::from_percent(50), + }, + min_turnout: Curve::LinearDecreasing { + begin: Perbill::from_percent(100), + delta: Perbill::from_percent(100), + }, + }, + ), + ( + 1u8, + TrackInfo { + name: "none", + max_deciding: 3, + decision_deposit: 1, + prepare_period: 2, + decision_period: 2, + confirm_period: 1, + min_enactment_period: 2, + min_approval: Curve::LinearDecreasing { + begin: Perbill::from_percent(55), + delta: Perbill::from_percent(5), + }, + min_turnout: Curve::LinearDecreasing { + begin: Perbill::from_percent(10), + delta: Perbill::from_percent(10), + }, + }, + ), + ]; + &DATA[..] + } + fn track_for(id: &Self::Origin) -> Result { + if let Ok(system_origin) = frame_system::RawOrigin::try_from(id.clone()) { + match system_origin { + frame_system::RawOrigin::Root => Ok(0), + frame_system::RawOrigin::None => Ok(1), + _ => Err(()), + } + } else { + Err(()) + } + } +} + +impl Config for Test { + type WeightInfo = (); + type Call = Call; + type Event = Event; + type Scheduler = Scheduler; + type Currency = pallet_balances::Pallet; + type CancelOrigin = EnsureSignedBy; + type KillOrigin = EnsureRoot; + type Slash = (); + type Votes = u32; + type Tally = Tally; + type SubmissionDeposit = SubmissionDeposit; + type MaxQueued = MaxQueued; + type UndecidingTimeout = UndecidingTimeout; + type AlarmInterval = AlarmInterval; + type Tracks = TestTracksInfo; +} + +pub fn new_test_ext() -> sp_io::TestExternalities { + let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); + let balances = vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100), (6, 100)]; + pallet_balances::GenesisConfig:: { balances } + .assimilate_storage(&mut t) + .unwrap(); + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext +} + +/// Execute the function two times, with `true` and with `false`. +#[allow(dead_code)] +pub fn new_test_ext_execute_with_cond(execute: impl FnOnce(bool) -> () + Clone) { + new_test_ext().execute_with(|| (execute.clone())(false)); + new_test_ext().execute_with(|| execute(true)); +} + +#[derive(Encode, Debug, Decode, TypeInfo, Eq, PartialEq, Clone, Default, MaxEncodedLen)] +pub struct Tally { + pub ayes: u32, + pub nays: u32, +} + +impl VoteTally for Tally { + fn ayes(&self) -> u32 { + self.ayes + } + + fn turnout(&self) -> Perbill { + Perbill::from_percent(self.ayes + self.nays) + } + + fn approval(&self) -> Perbill { + Perbill::from_rational(self.ayes, self.ayes + self.nays) + } + + #[cfg(feature = "runtime-benchmarks")] + fn unanimity() -> Self { + Self { ayes: 100, nays: 0 } + } + + #[cfg(feature = "runtime-benchmarks")] + fn from_requirements(turnout: Perbill, approval: Perbill) -> Self { + let turnout = turnout.mul_ceil(100u32); + let ayes = approval.mul_ceil(turnout); + Self { ayes, nays: turnout - ayes } + } +} + +pub fn set_balance_proposal(value: u64) -> Vec { + Call::Balances(pallet_balances::Call::set_balance { who: 42, new_free: value, new_reserved: 0 }) + .encode() +} + +pub fn set_balance_proposal_hash(value: u64) -> H256 { + let c = Call::Balances(pallet_balances::Call::set_balance { + who: 42, + new_free: value, + new_reserved: 0, + }); + >::note_preimage(c.encode().try_into().unwrap()); + BlakeTwo256::hash_of(&c) +} + +#[allow(dead_code)] +pub fn propose_set_balance(who: u64, value: u64, delay: u64) -> DispatchResult { + Referenda::submit( + Origin::signed(who), + frame_system::RawOrigin::Root.into(), + set_balance_proposal_hash(value), + AtOrAfter::After(delay), + ) +} + +pub fn next_block() { + System::set_block_number(System::block_number() + 1); + Scheduler::on_initialize(System::block_number()); +} + +pub fn run_to(n: u64) { + while System::block_number() < n { + next_block(); + } +} + +#[allow(dead_code)] +pub fn begin_referendum() -> ReferendumIndex { + System::set_block_number(0); + assert_ok!(propose_set_balance(1, 2, 1)); + run_to(2); + 0 +} + +#[allow(dead_code)] +pub fn tally(r: ReferendumIndex) -> Tally { + Referenda::ensure_ongoing(r).unwrap().tally +} + +pub fn set_tally(index: ReferendumIndex, ayes: u32, nays: u32) { + >::access_poll(index, |status| { + let tally = status.ensure_ongoing().unwrap().0; + tally.ayes = ayes; + tally.nays = nays; + }); +} + +pub fn waiting_since(i: ReferendumIndex) -> u64 { + match ReferendumInfoFor::::get(i).unwrap() { + ReferendumInfo::Ongoing(ReferendumStatus { submitted, deciding: None, .. }) => submitted, + _ => panic!("Not waiting"), + } +} + +pub fn deciding_since(i: ReferendumIndex) -> u64 { + match ReferendumInfoFor::::get(i).unwrap() { + ReferendumInfo::Ongoing(ReferendumStatus { + deciding: Some(DecidingStatus { since, .. }), + .. + }) => since, + _ => panic!("Not deciding"), + } +} + +pub fn deciding_and_failing_since(i: ReferendumIndex) -> u64 { + match ReferendumInfoFor::::get(i).unwrap() { + ReferendumInfo::Ongoing(ReferendumStatus { + deciding: Some(DecidingStatus { since, confirming: None, .. }), + .. + }) => since, + _ => panic!("Not deciding"), + } +} + +pub fn confirming_until(i: ReferendumIndex) -> u64 { + match ReferendumInfoFor::::get(i).unwrap() { + ReferendumInfo::Ongoing(ReferendumStatus { + deciding: Some(DecidingStatus { confirming: Some(until), .. }), + .. + }) => until, + _ => panic!("Not confirming"), + } +} + +pub fn approved_since(i: ReferendumIndex) -> u64 { + match ReferendumInfoFor::::get(i).unwrap() { + ReferendumInfo::Approved(since, ..) => since, + _ => panic!("Not approved"), + } +} + +pub fn rejected_since(i: ReferendumIndex) -> u64 { + match ReferendumInfoFor::::get(i).unwrap() { + ReferendumInfo::Rejected(since, ..) => since, + _ => panic!("Not rejected"), + } +} + +pub fn cancelled_since(i: ReferendumIndex) -> u64 { + match ReferendumInfoFor::::get(i).unwrap() { + ReferendumInfo::Cancelled(since, ..) => since, + _ => panic!("Not cancelled"), + } +} + +pub fn killed_since(i: ReferendumIndex) -> u64 { + match ReferendumInfoFor::::get(i).unwrap() { + ReferendumInfo::Killed(since, ..) => since, + _ => panic!("Not killed"), + } +} + +pub fn timed_out_since(i: ReferendumIndex) -> u64 { + match ReferendumInfoFor::::get(i).unwrap() { + ReferendumInfo::TimedOut(since, ..) => since, + _ => panic!("Not timed out"), + } +} + +fn is_deciding(i: ReferendumIndex) -> bool { + matches!( + ReferendumInfoFor::::get(i), + Some(ReferendumInfo::Ongoing(ReferendumStatus { deciding: Some(_), .. })) + ) +} + +#[derive(Clone, Copy)] +pub enum RefState { + Failing, + Passing, + Confirming { immediate: bool }, +} + +impl RefState { + pub fn create(self) -> ReferendumIndex { + assert_ok!(Referenda::submit( + Origin::signed(1), + frame_support::dispatch::RawOrigin::Root.into(), + set_balance_proposal_hash(1), + AtOrAfter::At(10), + )); + assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); + if matches!(self, RefState::Confirming { immediate: true }) { + set_tally(0, 100, 0); + } + let index = ReferendumCount::::get() - 1; + while !is_deciding(index) { + run_to(System::block_number() + 1); + } + if matches!(self, RefState::Confirming { immediate: false }) { + set_tally(0, 100, 0); + run_to(System::block_number() + 1); + } + if matches!(self, RefState::Confirming { .. }) { + assert_eq!(confirming_until(index), System::block_number() + 2); + } + if matches!(self, RefState::Passing) { + set_tally(0, 100, 99); + run_to(System::block_number() + 1); + } + index + } +} diff --git a/frame/referenda/src/tests.rs b/frame/referenda/src/tests.rs new file mode 100644 index 0000000000000..cea071ced12fe --- /dev/null +++ b/frame/referenda/src/tests.rs @@ -0,0 +1,511 @@ +// This file is part of Substrate. + +// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The crate's tests. + +use super::*; +use crate::mock::{RefState::*, *}; +use assert_matches::assert_matches; +use codec::Decode; +use frame_support::{ + assert_noop, assert_ok, + dispatch::{DispatchError::BadOrigin, RawOrigin}, + traits::Contains, +}; +use pallet_balances::Error as BalancesError; + +// TODO: Scheduler should re-use `None` items in its `Agenda`. + +#[test] +fn params_should_work() { + new_test_ext().execute_with(|| { + assert_eq!(ReferendumCount::::get(), 0); + assert_eq!(Balances::free_balance(42), 0); + assert_eq!(Balances::total_issuance(), 600); + }); +} + +#[test] +fn basic_happy_path_works() { + new_test_ext().execute_with(|| { + // #1: submit + assert_ok!(Referenda::submit( + Origin::signed(1), + RawOrigin::Root.into(), + set_balance_proposal_hash(1), + AtOrAfter::At(10), + )); + assert_eq!(Balances::reserved_balance(&1), 2); + assert_eq!(ReferendumCount::::get(), 1); + assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); + run_to(4); + assert_eq!(DecidingCount::::get(0), 0); + run_to(5); + // #5: 4 blocks after submit - vote should now be deciding. + assert_eq!(DecidingCount::::get(0), 1); + run_to(6); + // #6: Lots of ayes. Should now be confirming. + set_tally(0, 100, 0); + run_to(7); + assert_eq!(confirming_until(0), 9); + run_to(9); + // #8: Should be confirmed & ended. + assert_eq!(approved_since(0), 9); + assert_ok!(Referenda::refund_decision_deposit(Origin::signed(2), 0)); + run_to(12); + // #9: Should not yet be enacted. + assert_eq!(Balances::free_balance(&42), 0); + run_to(13); + // #10: Proposal should be executed. + assert_eq!(Balances::free_balance(&42), 1); + }); +} + +#[test] +fn insta_confirm_then_kill_works() { + new_test_ext().execute_with(|| { + let r = Confirming { immediate: true }.create(); + run_to(6); + assert_ok!(Referenda::kill(Origin::root(), r)); + assert_eq!(killed_since(r), 6); + }); +} + +#[test] +fn confirm_then_reconfirm_with_elapsed_trigger_works() { + new_test_ext().execute_with(|| { + let r = Confirming { immediate: false }.create(); + assert_eq!(confirming_until(r), 8); + run_to(7); + set_tally(r, 100, 99); + run_to(8); + assert_eq!(deciding_and_failing_since(r), 5); + run_to(11); + assert_eq!(approved_since(r), 11); + }); +} + +#[test] +fn instaconfirm_then_reconfirm_with_elapsed_trigger_works() { + new_test_ext().execute_with(|| { + let r = Confirming { immediate: true }.create(); + run_to(6); + assert_eq!(confirming_until(r), 7); + set_tally(r, 100, 99); + run_to(7); + assert_eq!(deciding_and_failing_since(r), 5); + run_to(11); + assert_eq!(approved_since(r), 11); + }); +} + +#[test] +fn instaconfirm_then_reconfirm_with_voting_trigger_works() { + new_test_ext().execute_with(|| { + let r = Confirming { immediate: true }.create(); + run_to(6); + assert_eq!(confirming_until(r), 7); + set_tally(r, 100, 99); + run_to(7); + assert_eq!(deciding_and_failing_since(r), 5); + run_to(8); + set_tally(r, 100, 0); + run_to(9); + assert_eq!(confirming_until(r), 11); + run_to(11); + assert_eq!(approved_since(r), 11); + }); +} + +#[test] +fn voting_should_extend_for_late_confirmation() { + new_test_ext().execute_with(|| { + let r = Passing.create(); + run_to(10); + assert_eq!(confirming_until(r), 11); + run_to(11); + assert_eq!(approved_since(r), 11); + }); +} + +#[test] +fn should_instafail_during_extension_confirmation() { + new_test_ext().execute_with(|| { + let r = Passing.create(); + run_to(10); + assert_eq!(confirming_until(r), 11); + // Should insta-fail since it's now past the normal voting time. + set_tally(r, 100, 101); + run_to(11); + assert_eq!(rejected_since(r), 11); + }); +} + +#[test] +fn confirming_then_fail_works() { + new_test_ext().execute_with(|| { + let r = Failing.create(); + // Normally ends at 5 + 4 (voting period) = 9. + assert_eq!(deciding_and_failing_since(r), 5); + set_tally(r, 100, 0); + run_to(6); + assert_eq!(confirming_until(r), 8); + set_tally(r, 100, 101); + run_to(9); + assert_eq!(rejected_since(r), 9); + }); +} + +#[test] +fn queueing_works() { + new_test_ext().execute_with(|| { + // Submit a proposal into a track with a queue len of 1. + assert_ok!(Referenda::submit( + Origin::signed(5), + RawOrigin::Root.into(), + set_balance_proposal_hash(0), + AtOrAfter::After(0), + )); + assert_ok!(Referenda::place_decision_deposit(Origin::signed(5), 0)); + + run_to(2); + + // Submit 3 more proposals into the same queue. + for i in 1..=4 { + assert_ok!(Referenda::submit( + Origin::signed(i), + RawOrigin::Root.into(), + set_balance_proposal_hash(i), + AtOrAfter::After(0), + )); + assert_ok!(Referenda::place_decision_deposit(Origin::signed(i), i as u32)); + // TODO: decision deposit after some initial votes with a non-highest voted coming + // first. + } + assert_eq!(ReferendumCount::::get(), 5); + + run_to(5); + // One should be being decided. + assert_eq!(DecidingCount::::get(0), 1); + assert_eq!(deciding_and_failing_since(0), 5); + for i in 1..=4 { + assert_eq!(waiting_since(i), 2); + } + + // Vote to set order. + set_tally(1, 1, 10); + set_tally(2, 2, 20); + set_tally(3, 3, 30); + set_tally(4, 100, 0); + println!("Agenda #6: {:?}", pallet_scheduler::Agenda::::get(6)); + run_to(6); + println!("{:?}", Vec::<_>::from(TrackQueue::::get(0))); + + // Cancel the first. + assert_ok!(Referenda::cancel(Origin::signed(4), 0)); + assert_eq!(cancelled_since(0), 6); + + // The other with the most approvals (#4) should be being decided. + run_to(7); + assert_eq!(DecidingCount::::get(0), 1); + assert_eq!(deciding_since(4), 7); + assert_eq!(confirming_until(4), 9); + + // Vote on the remaining two to change order. + println!("Set tally #1"); + set_tally(1, 30, 31); + println!("{:?}", Vec::<_>::from(TrackQueue::::get(0))); + println!("Set tally #2"); + set_tally(2, 20, 20); + println!("{:?}", Vec::<_>::from(TrackQueue::::get(0))); + + // Let confirmation period end. + run_to(9); + + // #4 should have been confirmed. + assert_eq!(approved_since(4), 9); + + // On to the next block to select the new referendum + run_to(10); + // #1 (the one with the most approvals) should now be being decided. + assert_eq!(deciding_since(1), 10); + + // Let it end unsuccessfully. + run_to(14); + assert_eq!(rejected_since(1), 14); + + // Service queue. + run_to(15); + // #2 should now be being decided. It will (barely) pass. + assert_eq!(deciding_and_failing_since(2), 15); + + // #2 moves into confirming at the last moment with a 50% approval. + run_to(19); + assert_eq!(confirming_until(2), 21); + + // #2 gets approved. + run_to(21); + assert_eq!(approved_since(2), 21); + + // The final one has since timed out. + run_to(22); + assert_eq!(timed_out_since(3), 22); + }); +} + +#[test] +fn auto_timeout_should_happen_with_nothing_but_submit() { + new_test_ext().execute_with(|| { + // #1: submit + assert_ok!(Referenda::submit( + Origin::signed(1), + RawOrigin::Root.into(), + set_balance_proposal_hash(1), + AtOrAfter::At(20), + )); + run_to(20); + assert_matches!(ReferendumInfoFor::::get(0), Some(ReferendumInfo::Ongoing(..))); + run_to(21); + // #11: Timed out - ended. + assert_matches!( + ReferendumInfoFor::::get(0), + Some(ReferendumInfo::TimedOut(21, _, None)) + ); + }); +} + +#[test] +fn tracks_are_distinguished() { + new_test_ext().execute_with(|| { + assert_ok!(Referenda::submit( + Origin::signed(1), + RawOrigin::Root.into(), + set_balance_proposal_hash(1), + AtOrAfter::At(10), + )); + assert_ok!(Referenda::submit( + Origin::signed(2), + RawOrigin::None.into(), + set_balance_proposal_hash(2), + AtOrAfter::At(20), + )); + + assert_ok!(Referenda::place_decision_deposit(Origin::signed(3), 0)); + assert_ok!(Referenda::place_decision_deposit(Origin::signed(4), 1)); + + let mut i = ReferendumInfoFor::::iter().collect::>(); + i.sort_by_key(|x| x.0); + assert_eq!( + i, + vec![ + ( + 0, + ReferendumInfo::Ongoing(ReferendumStatus { + track: 0, + origin: OriginCaller::system(RawOrigin::Root), + proposal_hash: set_balance_proposal_hash(1), + enactment: AtOrAfter::At(10), + submitted: 1, + submission_deposit: Deposit { who: 1, amount: 2 }, + decision_deposit: Some(Deposit { who: 3, amount: 10 }), + deciding: None, + tally: Tally { ayes: 0, nays: 0 }, + in_queue: false, + alarm: Some((5, (5, 0))), + }) + ), + ( + 1, + ReferendumInfo::Ongoing(ReferendumStatus { + track: 1, + origin: OriginCaller::system(RawOrigin::None), + proposal_hash: set_balance_proposal_hash(2), + enactment: AtOrAfter::At(20), + submitted: 1, + submission_deposit: Deposit { who: 2, amount: 2 }, + decision_deposit: Some(Deposit { who: 4, amount: 1 }), + deciding: None, + tally: Tally { ayes: 0, nays: 0 }, + in_queue: false, + alarm: Some((3, (3, 0))), + }) + ), + ] + ); + }); +} + +#[test] +fn submit_errors_work() { + new_test_ext().execute_with(|| { + let h = set_balance_proposal_hash(1); + // No track for Signed origins. + assert_noop!( + Referenda::submit(Origin::signed(1), RawOrigin::Signed(2).into(), h, AtOrAfter::At(10),), + Error::::NoTrack + ); + + // No funds for deposit + assert_noop!( + Referenda::submit(Origin::signed(10), RawOrigin::Root.into(), h, AtOrAfter::At(10),), + BalancesError::::InsufficientBalance + ); + }); +} + +#[test] +fn decision_deposit_errors_work() { + new_test_ext().execute_with(|| { + let e = Error::::NotOngoing; + assert_noop!(Referenda::place_decision_deposit(Origin::signed(2), 0), e); + + let h = set_balance_proposal_hash(1); + assert_ok!(Referenda::submit( + Origin::signed(1), + RawOrigin::Root.into(), + h, + AtOrAfter::At(10), + )); + let e = BalancesError::::InsufficientBalance; + assert_noop!(Referenda::place_decision_deposit(Origin::signed(10), 0), e); + + assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); + let e = Error::::HaveDeposit; + assert_noop!(Referenda::place_decision_deposit(Origin::signed(2), 0), e); + }); +} + +#[test] +fn refund_deposit_works() { + new_test_ext().execute_with(|| { + let e = Error::::BadReferendum; + assert_noop!(Referenda::refund_decision_deposit(Origin::signed(1), 0), e); + + let h = set_balance_proposal_hash(1); + assert_ok!(Referenda::submit( + Origin::signed(1), + RawOrigin::Root.into(), + h, + AtOrAfter::At(10), + )); + let e = Error::::NoDeposit; + assert_noop!(Referenda::refund_decision_deposit(Origin::signed(2), 0), e); + + assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); + let e = Error::::Unfinished; + assert_noop!(Referenda::refund_decision_deposit(Origin::signed(3), 0), e); + + run_to(11); + assert_ok!(Referenda::refund_decision_deposit(Origin::signed(3), 0)); + }); +} + +#[test] +fn cancel_works() { + new_test_ext().execute_with(|| { + let h = set_balance_proposal_hash(1); + assert_ok!(Referenda::submit( + Origin::signed(1), + RawOrigin::Root.into(), + h, + AtOrAfter::At(10), + )); + assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); + + run_to(8); + assert_ok!(Referenda::cancel(Origin::signed(4), 0)); + assert_ok!(Referenda::refund_decision_deposit(Origin::signed(3), 0)); + assert_eq!(cancelled_since(0), 8); + }); +} + +#[test] +fn cancel_errors_works() { + new_test_ext().execute_with(|| { + let h = set_balance_proposal_hash(1); + assert_ok!(Referenda::submit( + Origin::signed(1), + RawOrigin::Root.into(), + h, + AtOrAfter::At(10), + )); + assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); + assert_noop!(Referenda::cancel(Origin::signed(1), 0), BadOrigin); + + run_to(11); + assert_noop!(Referenda::cancel(Origin::signed(4), 0), Error::::NotOngoing); + }); +} + +#[test] +fn kill_works() { + new_test_ext().execute_with(|| { + let h = set_balance_proposal_hash(1); + assert_ok!(Referenda::submit( + Origin::signed(1), + RawOrigin::Root.into(), + h, + AtOrAfter::At(10), + )); + assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); + + run_to(8); + assert_ok!(Referenda::kill(Origin::root(), 0)); + let e = Error::::NoDeposit; + assert_noop!(Referenda::refund_decision_deposit(Origin::signed(3), 0), e); + assert_eq!(killed_since(0), 8); + }); +} + +#[test] +fn kill_errors_works() { + new_test_ext().execute_with(|| { + let h = set_balance_proposal_hash(1); + assert_ok!(Referenda::submit( + Origin::signed(1), + RawOrigin::Root.into(), + h, + AtOrAfter::At(10), + )); + assert_ok!(Referenda::place_decision_deposit(Origin::signed(2), 0)); + assert_noop!(Referenda::kill(Origin::signed(4), 0), BadOrigin); + + run_to(11); + assert_noop!(Referenda::kill(Origin::root(), 0), Error::::NotOngoing); + }); +} + +#[test] +fn set_balance_proposal_is_correctly_filtered_out() { + for i in 0..10 { + let call = crate::mock::Call::decode(&mut &set_balance_proposal(i)[..]).unwrap(); + assert!(!::BaseCallFilter::contains(&call)); + } +} + +#[test] +fn curve_handles_all_inputs() { + let test_curve = Curve::LinearDecreasing { begin: Perbill::zero(), delta: Perbill::zero() }; + + let delay = test_curve.delay(Perbill::zero()); + assert_eq!(delay, Perbill::zero()); + + let test_curve = Curve::LinearDecreasing { begin: Perbill::zero(), delta: Perbill::one() }; + + let threshold = test_curve.threshold(Perbill::one()); + assert_eq!(threshold, Perbill::zero()); +} diff --git a/frame/referenda/src/types.rs b/frame/referenda/src/types.rs new file mode 100644 index 0000000000000..1b028fdfe9f79 --- /dev/null +++ b/frame/referenda/src/types.rs @@ -0,0 +1,358 @@ +// This file is part of Substrate. + +// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Miscellaneous additional datatypes. + +use super::*; +use codec::{Decode, Encode, EncodeLike, MaxEncodedLen}; +use frame_support::{traits::schedule::Anon, Parameter}; +use scale_info::TypeInfo; +use sp_runtime::RuntimeDebug; +use sp_std::fmt::Debug; + +pub type BalanceOf = + <::Currency as Currency<::AccountId>>::Balance; +pub type NegativeImbalanceOf = <::Currency as Currency< + ::AccountId, +>>::NegativeImbalance; +pub type CallOf = ::Call; +pub type VotesOf = ::Votes; +pub type TallyOf = ::Tally; +pub type PalletsOriginOf = <::Origin as OriginTrait>::PalletsOrigin; +pub type ReferendumInfoOf = ReferendumInfo< + TrackIdOf, + PalletsOriginOf, + ::BlockNumber, + ::Hash, + BalanceOf, + TallyOf, + ::AccountId, + ScheduleAddressOf, +>; +pub type ReferendumStatusOf = ReferendumStatus< + TrackIdOf, + PalletsOriginOf, + ::BlockNumber, + ::Hash, + BalanceOf, + TallyOf, + ::AccountId, + ScheduleAddressOf, +>; +pub type DecidingStatusOf = DecidingStatus<::BlockNumber>; +pub type TrackInfoOf = TrackInfo, ::BlockNumber>; +pub type TrackIdOf = <::Tracks as TracksInfo< + BalanceOf, + ::BlockNumber, +>>::Id; +pub type ScheduleAddressOf = <::Scheduler as Anon< + ::BlockNumber, + CallOf, + PalletsOriginOf, +>>::Address; + +/// A referendum index. +pub type ReferendumIndex = u32; + +pub trait InsertSorted { + /// Inserts an item into a sorted series. + /// + /// Returns `true` if it was inserted, `false` if it would belong beyond the bound of the + /// series. + fn insert_sorted_by_key K, K: PartialOrd + Ord>( + &mut self, + t: T, + f: F, + ) -> bool; +} +impl> InsertSorted for BoundedVec { + fn insert_sorted_by_key K, K: PartialOrd + Ord>( + &mut self, + t: T, + mut f: F, + ) -> bool { + let index = self.binary_search_by_key::(&f(&t), f).unwrap_or_else(|x| x); + self.force_insert_keep_right(index, t) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use frame_support::traits::ConstU32; + + #[test] + fn insert_sorted_works() { + let mut b: BoundedVec> = vec![20, 30, 40].try_into().unwrap(); + assert!(b.insert_sorted_by_key(10, |&x| x)); + assert_eq!(&b[..], &[10, 20, 30, 40][..]); + + assert!(b.insert_sorted_by_key(60, |&x| x)); + assert_eq!(&b[..], &[10, 20, 30, 40, 60][..]); + + assert!(b.insert_sorted_by_key(50, |&x| x)); + assert_eq!(&b[..], &[10, 20, 30, 40, 50, 60][..]); + + assert!(!b.insert_sorted_by_key(9, |&x| x)); + assert_eq!(&b[..], &[10, 20, 30, 40, 50, 60][..]); + + assert!(b.insert_sorted_by_key(11, |&x| x)); + assert_eq!(&b[..], &[11, 20, 30, 40, 50, 60][..]); + + assert!(b.insert_sorted_by_key(21, |&x| x)); + assert_eq!(&b[..], &[20, 21, 30, 40, 50, 60][..]); + + assert!(b.insert_sorted_by_key(61, |&x| x)); + assert_eq!(&b[..], &[21, 30, 40, 50, 60, 61][..]); + + assert!(b.insert_sorted_by_key(51, |&x| x)); + assert_eq!(&b[..], &[30, 40, 50, 51, 60, 61][..]); + } +} + +#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct DecidingStatus { + /// When this referendum began being "decided". If confirming, then the + /// end will actually be delayed until the end of the confirmation period. + pub(crate) since: BlockNumber, + /// If `Some`, then the referendum has entered confirmation stage and will end at + /// the block number as long as it doesn't lose its approval in the meantime. + pub(crate) confirming: Option, +} + +#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct Deposit { + pub(crate) who: AccountId, + pub(crate) amount: Balance, +} + +#[derive(Clone, Encode, TypeInfo)] +pub struct TrackInfo { + /// Name of this track. TODO was &'static str + pub name: &'static str, + /// A limit for the number of referenda on this track that can be being decided at once. + /// For Root origin this should generally be just one. + pub max_deciding: u32, + /// Amount that must be placed on deposit before a decision can be made. + pub decision_deposit: Balance, + /// Amount of time this must be submitted for before a decision can be made. + pub prepare_period: Moment, + /// Amount of time that a decision may take to be approved prior to cancellation. + pub decision_period: Moment, + /// Amount of time that the approval criteria must hold before it can be approved. + pub confirm_period: Moment, + /// Minimum amount of time that an approved proposal must be in the dispatch queue. + pub min_enactment_period: Moment, + /// Minimum aye votes as percentage of overall conviction-weighted votes needed for + /// approval as a function of time into decision period. + pub min_approval: Curve, + /// Minimum turnout as percentage of overall population that is needed for + /// approval as a function of time into decision period. + pub min_turnout: Curve, +} + +/// Information on the voting tracks. +pub trait TracksInfo { + /// The identifier for a track. + type Id: Copy + Parameter + Ord + PartialOrd + Send + Sync + 'static; + + /// The origin type from which a track is implied. + type Origin; + + /// Return the array of known tracks and their information. + fn tracks() -> &'static [(Self::Id, TrackInfo)]; + + /// Determine the voting track for the given `origin`. + fn track_for(origin: &Self::Origin) -> Result; + + /// Return the track info for track `id`, by default this just looks it up in `Self::tracks()`. + fn info(id: Self::Id) -> Option<&'static TrackInfo> { + Self::tracks().iter().find(|x| &x.0 == &id).map(|x| &x.1) + } +} + +/// Indication of either a specific moment or a delay from a implicitly defined moment. +#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub enum AtOrAfter { + /// Indiciates that the event should occur at the moment given. + At(Moment), + /// Indiciates that the event should occur some period of time (defined by the parameter) after + /// a prior event. The prior event is defined by the context, but for the purposes of + /// referendum proposals, the "prior event" is the passing of the referendum. + After(Moment), +} + +impl AtOrAfter { + pub fn evaluate(&self, since: Moment) -> Moment { + match &self { + Self::At(m) => *m, + Self::After(m) => m.saturating_add(since), + } + } +} + +/// Info regarding an ongoing referendum. +#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub struct ReferendumStatus< + TrackId: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + Origin: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + Moment: Parameter + Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone + EncodeLike, + Hash: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + Balance: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + Tally: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + AccountId: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + ScheduleAddress: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, +> { + /// The track of this referendum. + pub(crate) track: TrackId, + /// The origin for this referendum. + pub(crate) origin: Origin, + /// The hash of the proposal up for referendum. + pub(crate) proposal_hash: Hash, + /// The time the proposal should be scheduled for enactment. + pub(crate) enactment: AtOrAfter, + /// The time of submission. Once `UndecidingTimeout` passes, it may be closed by anyone if it + /// `deciding` is `None`. + pub(crate) submitted: Moment, + /// The deposit reserved for the submission of this referendum. + pub(crate) submission_deposit: Deposit, + /// The deposit reserved for this referendum to be decided. + pub(crate) decision_deposit: Option>, + /// The status of a decision being made. If `None`, it has not entered the deciding period. + pub(crate) deciding: Option>, + /// The current tally of votes in this referendum. + pub(crate) tally: Tally, + /// Whether we have been placed in the queue for being decided or not. + pub(crate) in_queue: bool, + /// The next scheduled wake-up, if `Some`. + pub(crate) alarm: Option<(Moment, ScheduleAddress)>, +} + +/// Info regarding a referendum, present or past. +#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] +pub enum ReferendumInfo< + TrackId: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + Origin: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + Moment: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone + EncodeLike, + Hash: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + Balance: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + Tally: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + AccountId: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + ScheduleAddress: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, +> { + /// Referendum has been submitted and is being voted on. + Ongoing( + ReferendumStatus, + ), + /// Referendum finished with approval. Submission deposit is held. + Approved(Moment, Deposit, Option>), + /// Referendum finished with rejection. Submission deposit is held. + Rejected(Moment, Deposit, Option>), + /// Referendum finished with cancelation. Submission deposit is held. + Cancelled(Moment, Deposit, Option>), + /// Referendum finished and was never decided. Submission deposit is held. + TimedOut(Moment, Deposit, Option>), + /// Referendum finished with a kill. + Killed(Moment), +} + +impl< + TrackId: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + Origin: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + Moment: Parameter + Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone + EncodeLike, + Hash: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + Balance: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + Tally: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + AccountId: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + ScheduleAddress: Eq + PartialEq + Debug + Encode + Decode + TypeInfo + Clone, + > ReferendumInfo +{ + /// Take the Decision Deposit from `self`, if there is one. Returns an `Err` if `self` is not + /// in a valid state for the Decision Deposit to be refunded. + pub fn take_decision_deposit(&mut self) -> Result>, ()> { + use ReferendumInfo::*; + match self { + Ongoing(x) if x.decision_deposit.is_none() => Ok(None), + // Cannot refund deposit if Ongoing as this breaks assumptions. + Ongoing(_) => Err(()), + Approved(_, _, d) | Rejected(_, _, d) | TimedOut(_, _, d) | Cancelled(_, _, d) => + Ok(d.take()), + Killed(_) => Ok(None), + } + } +} + +/// Type for describing a curve over the 2-dimensional space of axes between 0-1, as represented +/// by `(Perbill, Perbill)`. +#[derive(Clone, Eq, PartialEq, Encode, Decode, TypeInfo, MaxEncodedLen)] +#[cfg_attr(not(feature = "std"), derive(RuntimeDebug))] +pub enum Curve { + /// Linear curve starting at `(0, begin)`, ending at `(period, begin - delta)`. + LinearDecreasing { begin: Perbill, delta: Perbill }, +} + +impl Curve { + /// Determine the `y` value for the given `x` value. + pub(crate) fn threshold(&self, x: Perbill) -> Perbill { + match self { + Self::LinearDecreasing { begin, delta } => *begin - (*delta * x).min(*begin), + } + } + + /// Determine the smallest `x` value such that `passing` returns `true` when passed along with + /// the given `y` value. + /// + /// ```nocompile + /// let c = Curve::LinearDecreasing { begin: Perbill::one(), delta: Perbill::one() }; + /// // ^^^ Can be any curve. + /// let y = Perbill::from_percent(50); + /// // ^^^ Can be any value. + /// let x = c.delay(y); + /// assert!(c.passing(x, y)); + /// ``` + pub fn delay(&self, y: Perbill) -> Perbill { + match self { + Self::LinearDecreasing { begin, delta } => + if delta.is_zero() { + return *delta + } else { + return (*begin - y.min(*begin)).min(*delta) / *delta + }, + } + } + + /// Return `true` iff the `y` value is greater than the curve at the `x`. + pub fn passing(&self, x: Perbill, y: Perbill) -> bool { + y >= self.threshold(x) + } +} + +#[cfg(feature = "std")] +impl Debug for Curve { + fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { + match self { + Self::LinearDecreasing { begin, delta } => { + write!( + f, + "Linear[(0%, {}%) -> (100%, {}%)]", + *begin * 100u32, + (*begin - *delta) * 100u32, + ) + }, + } + } +} diff --git a/frame/referenda/src/weights.rs b/frame/referenda/src/weights.rs new file mode 100644 index 0000000000000..202901bdd10bd --- /dev/null +++ b/frame/referenda/src/weights.rs @@ -0,0 +1,491 @@ +// This file is part of Substrate. + +// Copyright (C) 2021 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Autogenerated weights for pallet_referenda +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2021-12-19, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 + +// Executed Command: +// target/release/substrate +// benchmark +// --chain=dev +// --steps=50 +// --repeat=20 +// --pallet=pallet_referenda +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --output=./frame/referenda/src/weights.rs +// --template=./.maintain/frame-weight-template.hbs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; +use sp_std::marker::PhantomData; + +/// Weight functions needed for pallet_referenda. +pub trait WeightInfo { + fn submit() -> Weight; + fn place_decision_deposit_preparing() -> Weight; + fn place_decision_deposit_queued() -> Weight; + fn place_decision_deposit_not_queued() -> Weight; + fn place_decision_deposit_passing() -> Weight; + fn place_decision_deposit_failing() -> Weight; + fn refund_decision_deposit() -> Weight; + fn cancel() -> Weight; + fn kill() -> Weight; + fn one_fewer_deciding_queue_empty() -> Weight; + fn one_fewer_deciding_failing() -> Weight; + fn one_fewer_deciding_passing() -> Weight; + fn nudge_referendum_requeued_insertion() -> Weight; + fn nudge_referendum_requeued_slide() -> Weight; + fn nudge_referendum_queued() -> Weight; + fn nudge_referendum_not_queued() -> Weight; + fn nudge_referendum_no_deposit() -> Weight; + fn nudge_referendum_preparing() -> Weight; + fn nudge_referendum_timed_out() -> Weight; + fn nudge_referendum_begin_deciding_failing() -> Weight; + fn nudge_referendum_begin_deciding_passing() -> Weight; + fn nudge_referendum_begin_confirming() -> Weight; + fn nudge_referendum_end_confirming() -> Weight; + fn nudge_referendum_continue_not_confirming() -> Weight; + fn nudge_referendum_continue_confirming() -> Weight; + fn nudge_referendum_approved() -> Weight; + fn nudge_referendum_rejected() -> Weight; +} + +/// Weights for pallet_referenda using the Substrate node and recommended hardware. +pub struct SubstrateWeight(PhantomData); +impl WeightInfo for SubstrateWeight { + // Storage: Referenda ReferendumCount (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Referenda ReferendumInfoFor (r:0 w:1) + fn submit() -> Weight { + (42_395_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn place_decision_deposit_preparing() -> Weight { + (48_113_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:0) + // Storage: Referenda TrackQueue (r:1 w:1) + fn place_decision_deposit_queued() -> Weight { + (53_624_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:0) + // Storage: Referenda TrackQueue (r:1 w:1) + fn place_decision_deposit_not_queued() -> Weight { + (52_560_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn place_decision_deposit_passing() -> Weight { + (54_067_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn place_decision_deposit_failing() -> Weight { + (52_457_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + fn refund_decision_deposit() -> Weight { + (28_504_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn cancel() -> Weight { + (40_425_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn kill() -> Weight { + (65_974_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda TrackQueue (r:1 w:0) + // Storage: Referenda DecidingCount (r:1 w:1) + fn one_fewer_deciding_queue_empty() -> Weight { + (8_904_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Referenda TrackQueue (r:1 w:1) + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn one_fewer_deciding_failing() -> Weight { + (181_387_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: Referenda TrackQueue (r:1 w:1) + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn one_fewer_deciding_passing() -> Weight { + (179_753_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(4 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda TrackQueue (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_requeued_insertion() -> Weight { + (53_592_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda TrackQueue (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_requeued_slide() -> Weight { + (53_173_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:0) + // Storage: Referenda TrackQueue (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_queued() -> Weight { + (55_770_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:0) + // Storage: Referenda TrackQueue (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_not_queued() -> Weight { + (53_922_000 as Weight) + .saturating_add(T::DbWeight::get().reads(4 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_no_deposit() -> Weight { + (26_906_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_preparing() -> Weight { + (27_943_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + fn nudge_referendum_timed_out() -> Weight { + (20_256_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_begin_deciding_failing() -> Weight { + (30_964_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_begin_deciding_passing() -> Weight { + (31_763_000 as Weight) + .saturating_add(T::DbWeight::get().reads(3 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_begin_confirming() -> Weight { + (28_892_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_end_confirming() -> Weight { + (29_666_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_continue_not_confirming() -> Weight { + (29_740_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_continue_confirming() -> Weight { + (29_661_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn nudge_referendum_approved() -> Weight { + (55_736_000 as Weight) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(5 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_rejected() -> Weight { + (32_726_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) + } +} + +// For backwards compatibility and tests +impl WeightInfo for () { + // Storage: Referenda ReferendumCount (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + // Storage: Referenda ReferendumInfoFor (r:0 w:1) + fn submit() -> Weight { + (42_395_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn place_decision_deposit_preparing() -> Weight { + (48_113_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:0) + // Storage: Referenda TrackQueue (r:1 w:1) + fn place_decision_deposit_queued() -> Weight { + (53_624_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:0) + // Storage: Referenda TrackQueue (r:1 w:1) + fn place_decision_deposit_not_queued() -> Weight { + (52_560_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn place_decision_deposit_passing() -> Weight { + (54_067_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn place_decision_deposit_failing() -> Weight { + (52_457_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + fn refund_decision_deposit() -> Weight { + (28_504_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn cancel() -> Weight { + (40_425_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn kill() -> Weight { + (65_974_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda TrackQueue (r:1 w:0) + // Storage: Referenda DecidingCount (r:1 w:1) + fn one_fewer_deciding_queue_empty() -> Weight { + (8_904_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Referenda TrackQueue (r:1 w:1) + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn one_fewer_deciding_failing() -> Weight { + (181_387_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: Referenda TrackQueue (r:1 w:1) + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + fn one_fewer_deciding_passing() -> Weight { + (179_753_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda TrackQueue (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_requeued_insertion() -> Weight { + (53_592_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda TrackQueue (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_requeued_slide() -> Weight { + (53_173_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:0) + // Storage: Referenda TrackQueue (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_queued() -> Weight { + (55_770_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:0) + // Storage: Referenda TrackQueue (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_not_queued() -> Weight { + (53_922_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(4 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_no_deposit() -> Weight { + (26_906_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_preparing() -> Weight { + (27_943_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + fn nudge_referendum_timed_out() -> Weight { + (20_256_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_begin_deciding_failing() -> Weight { + (30_964_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Referenda DecidingCount (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_begin_deciding_passing() -> Weight { + (31_763_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(3 as Weight)) + .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_begin_confirming() -> Weight { + (28_892_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_end_confirming() -> Weight { + (29_666_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_continue_not_confirming() -> Weight { + (29_740_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_continue_confirming() -> Weight { + (29_661_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:2 w:2) + // Storage: Scheduler Lookup (r:1 w:1) + // Storage: Preimage StatusFor (r:1 w:1) + fn nudge_referendum_approved() -> Weight { + (55_736_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(5 as Weight)) + .saturating_add(RocksDbWeight::get().writes(5 as Weight)) + } + // Storage: Referenda ReferendumInfoFor (r:1 w:1) + // Storage: Scheduler Agenda (r:1 w:1) + fn nudge_referendum_rejected() -> Weight { + (32_726_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + } +} diff --git a/frame/scheduler/Cargo.toml b/frame/scheduler/Cargo.toml index 424c3852862ec..d88063d69c5bb 100644 --- a/frame/scheduler/Cargo.toml +++ b/frame/scheduler/Cargo.toml @@ -14,15 +14,15 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } log = { version = "0.4.14", default-features = false } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core", default-features = false } +sp-core = { version = "5.0.0", path = "../../primitives/core", default-features = false } substrate-test-utils = { version = "4.0.0-dev", path = "../../test-utils" } pallet-preimage = { version = "4.0.0-dev", path = "../preimage" } diff --git a/frame/scheduler/src/lib.rs b/frame/scheduler/src/lib.rs index f9077d4c8c8fa..ec60cedc280b6 100644 --- a/frame/scheduler/src/lib.rs +++ b/frame/scheduler/src/lib.rs @@ -694,13 +694,6 @@ impl Pallet { }); Agenda::::append(when, s); let index = Agenda::::decode_len(when).unwrap_or(1) as u32 - 1; - if index > T::MaxScheduledPerBlock::get() { - log::warn!( - target: "runtime::scheduler", - "Warning: There are more items queued in the Scheduler than \ - expected from the runtime configuration. An update might be needed.", - ); - } Self::deposit_event(Event::Scheduled { when, index }); Ok((when, index)) @@ -795,13 +788,6 @@ impl Pallet { }; Agenda::::append(when, Some(s)); let index = Agenda::::decode_len(when).unwrap_or(1) as u32 - 1; - if index > T::MaxScheduledPerBlock::get() { - log::warn!( - target: "runtime::scheduler", - "Warning: There are more items queued in the Scheduler than \ - expected from the runtime configuration. An update might be needed.", - ); - } let address = (when, index); Lookup::::insert(&id, &address); Self::deposit_event(Event::Scheduled { when, index }); diff --git a/frame/scheduler/src/weights.rs b/frame/scheduler/src/weights.rs index b8209c6031c89..dd00b8dfe6cd6 100644 --- a/frame/scheduler/src/weights.rs +++ b/frame/scheduler/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_scheduler //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-12-10, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,7 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/scheduler/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -68,9 +70,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Preimage StatusFor (r:1 w:1) // Storage: Scheduler Lookup (r:0 w:1) fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight { - (8_183_000 as Weight) - // Standard Error: 36_000 - .saturating_add((34_670_000 as Weight).saturating_mul(s as Weight)) + (11_587_000 as Weight) + // Standard Error: 17_000 + .saturating_add((17_428_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) .saturating_add(T::DbWeight::get().writes(1 as Weight)) @@ -81,9 +83,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Preimage StatusFor (r:1 w:1) // Storage: Scheduler Lookup (r:0 w:1) fn on_initialize_named_resolved(s: u32, ) -> Weight { - (11_520_000 as Weight) - // Standard Error: 30_000 - .saturating_add((26_386_000 as Weight).saturating_mul(s as Weight)) + (8_965_000 as Weight) + // Standard Error: 11_000 + .saturating_add((13_410_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) .saturating_add(T::DbWeight::get().writes(1 as Weight)) @@ -93,9 +95,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Preimage PreimageFor (r:1 w:1) // Storage: Preimage StatusFor (r:1 w:1) fn on_initialize_periodic_resolved(s: u32, ) -> Weight { - (8_222_000 as Weight) - // Standard Error: 33_000 - .saturating_add((28_925_000 as Weight).saturating_mul(s as Weight)) + (8_654_000 as Weight) + // Standard Error: 17_000 + .saturating_add((14_990_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) .saturating_add(T::DbWeight::get().writes(1 as Weight)) @@ -105,9 +107,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Preimage PreimageFor (r:1 w:1) // Storage: Preimage StatusFor (r:1 w:1) fn on_initialize_resolved(s: u32, ) -> Weight { - (11_610_000 as Weight) - // Standard Error: 26_000 - .saturating_add((23_857_000 as Weight).saturating_mul(s as Weight)) + (9_303_000 as Weight) + // Standard Error: 10_000 + .saturating_add((12_244_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) .saturating_add(T::DbWeight::get().writes(1 as Weight)) @@ -117,9 +119,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Preimage PreimageFor (r:1 w:0) // Storage: Scheduler Lookup (r:0 w:1) fn on_initialize_named_aborted(s: u32, ) -> Weight { - (11_067_000 as Weight) - // Standard Error: 15_000 - .saturating_add((11_728_000 as Weight).saturating_mul(s as Weight)) + (7_506_000 as Weight) + // Standard Error: 3_000 + .saturating_add((5_208_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) .saturating_add(T::DbWeight::get().writes(2 as Weight)) @@ -128,9 +130,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Scheduler Agenda (r:2 w:2) // Storage: Preimage PreimageFor (r:1 w:0) fn on_initialize_aborted(s: u32, ) -> Weight { - (13_045_000 as Weight) - // Standard Error: 5_000 - .saturating_add((6_378_000 as Weight).saturating_mul(s as Weight)) + (8_046_000 as Weight) + // Standard Error: 3_000 + .saturating_add((2_914_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) .saturating_add(T::DbWeight::get().writes(2 as Weight)) @@ -138,9 +140,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Scheduler Agenda (r:2 w:2) // Storage: Scheduler Lookup (r:0 w:1) fn on_initialize_periodic_named(s: u32, ) -> Weight { - (13_496_000 as Weight) - // Standard Error: 27_000 - .saturating_add((17_932_000 as Weight).saturating_mul(s as Weight)) + (13_704_000 as Weight) + // Standard Error: 4_000 + .saturating_add((8_186_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) .saturating_add(T::DbWeight::get().writes(1 as Weight)) @@ -148,9 +150,9 @@ impl WeightInfo for SubstrateWeight { } // Storage: Scheduler Agenda (r:2 w:2) fn on_initialize_periodic(s: u32, ) -> Weight { - (17_074_000 as Weight) - // Standard Error: 16_000 - .saturating_add((11_982_000 as Weight).saturating_mul(s as Weight)) + (12_668_000 as Weight) + // Standard Error: 5_000 + .saturating_add((5_868_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) .saturating_add(T::DbWeight::get().writes(1 as Weight)) @@ -159,53 +161,53 @@ impl WeightInfo for SubstrateWeight { // Storage: Scheduler Agenda (r:1 w:1) // Storage: Scheduler Lookup (r:0 w:1) fn on_initialize_named(s: u32, ) -> Weight { - (18_730_000 as Weight) - // Standard Error: 10_000 - .saturating_add((9_909_000 as Weight).saturating_mul(s as Weight)) + (13_946_000 as Weight) + // Standard Error: 4_000 + .saturating_add((4_367_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) } // Storage: Scheduler Agenda (r:1 w:1) fn on_initialize(s: u32, ) -> Weight { - (17_844_000 as Weight) - // Standard Error: 9_000 - .saturating_add((7_719_000 as Weight).saturating_mul(s as Weight)) + (13_151_000 as Weight) + // Standard Error: 4_000 + .saturating_add((3_455_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Scheduler Agenda (r:1 w:1) fn schedule(s: u32, ) -> Weight { - (23_361_000 as Weight) + (14_040_000 as Weight) // Standard Error: 1_000 - .saturating_add((82_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((89_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Scheduler Agenda (r:1 w:1) // Storage: Scheduler Lookup (r:0 w:1) fn cancel(s: u32, ) -> Weight { - (22_359_000 as Weight) - // Standard Error: 2_000 - .saturating_add((1_219_000 as Weight).saturating_mul(s as Weight)) + (14_376_000 as Weight) + // Standard Error: 1_000 + .saturating_add((576_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Scheduler Lookup (r:1 w:1) // Storage: Scheduler Agenda (r:1 w:1) fn schedule_named(s: u32, ) -> Weight { - (28_499_000 as Weight) + (16_806_000 as Weight) // Standard Error: 1_000 - .saturating_add((98_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((102_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Scheduler Lookup (r:1 w:1) // Storage: Scheduler Agenda (r:1 w:1) fn cancel_named(s: u32, ) -> Weight { - (24_995_000 as Weight) + (15_852_000 as Weight) // Standard Error: 2_000 - .saturating_add((1_223_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((590_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -218,9 +220,9 @@ impl WeightInfo for () { // Storage: Preimage StatusFor (r:1 w:1) // Storage: Scheduler Lookup (r:0 w:1) fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight { - (8_183_000 as Weight) - // Standard Error: 36_000 - .saturating_add((34_670_000 as Weight).saturating_mul(s as Weight)) + (11_587_000 as Weight) + // Standard Error: 17_000 + .saturating_add((17_428_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) @@ -231,9 +233,9 @@ impl WeightInfo for () { // Storage: Preimage StatusFor (r:1 w:1) // Storage: Scheduler Lookup (r:0 w:1) fn on_initialize_named_resolved(s: u32, ) -> Weight { - (11_520_000 as Weight) - // Standard Error: 30_000 - .saturating_add((26_386_000 as Weight).saturating_mul(s as Weight)) + (8_965_000 as Weight) + // Standard Error: 11_000 + .saturating_add((13_410_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) @@ -243,9 +245,9 @@ impl WeightInfo for () { // Storage: Preimage PreimageFor (r:1 w:1) // Storage: Preimage StatusFor (r:1 w:1) fn on_initialize_periodic_resolved(s: u32, ) -> Weight { - (8_222_000 as Weight) - // Standard Error: 33_000 - .saturating_add((28_925_000 as Weight).saturating_mul(s as Weight)) + (8_654_000 as Weight) + // Standard Error: 17_000 + .saturating_add((14_990_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight))) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) @@ -255,9 +257,9 @@ impl WeightInfo for () { // Storage: Preimage PreimageFor (r:1 w:1) // Storage: Preimage StatusFor (r:1 w:1) fn on_initialize_resolved(s: u32, ) -> Weight { - (11_610_000 as Weight) - // Standard Error: 26_000 - .saturating_add((23_857_000 as Weight).saturating_mul(s as Weight)) + (9_303_000 as Weight) + // Standard Error: 10_000 + .saturating_add((12_244_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight))) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) @@ -267,9 +269,9 @@ impl WeightInfo for () { // Storage: Preimage PreimageFor (r:1 w:0) // Storage: Scheduler Lookup (r:0 w:1) fn on_initialize_named_aborted(s: u32, ) -> Weight { - (11_067_000 as Weight) - // Standard Error: 15_000 - .saturating_add((11_728_000 as Weight).saturating_mul(s as Weight)) + (7_506_000 as Weight) + // Standard Error: 3_000 + .saturating_add((5_208_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) @@ -278,9 +280,9 @@ impl WeightInfo for () { // Storage: Scheduler Agenda (r:2 w:2) // Storage: Preimage PreimageFor (r:1 w:0) fn on_initialize_aborted(s: u32, ) -> Weight { - (13_045_000 as Weight) - // Standard Error: 5_000 - .saturating_add((6_378_000 as Weight).saturating_mul(s as Weight)) + (8_046_000 as Weight) + // Standard Error: 3_000 + .saturating_add((2_914_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) @@ -288,9 +290,9 @@ impl WeightInfo for () { // Storage: Scheduler Agenda (r:2 w:2) // Storage: Scheduler Lookup (r:0 w:1) fn on_initialize_periodic_named(s: u32, ) -> Weight { - (13_496_000 as Weight) - // Standard Error: 27_000 - .saturating_add((17_932_000 as Weight).saturating_mul(s as Weight)) + (13_704_000 as Weight) + // Standard Error: 4_000 + .saturating_add((8_186_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) @@ -298,9 +300,9 @@ impl WeightInfo for () { } // Storage: Scheduler Agenda (r:2 w:2) fn on_initialize_periodic(s: u32, ) -> Weight { - (17_074_000 as Weight) - // Standard Error: 16_000 - .saturating_add((11_982_000 as Weight).saturating_mul(s as Weight)) + (12_668_000 as Weight) + // Standard Error: 5_000 + .saturating_add((5_868_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) @@ -309,53 +311,53 @@ impl WeightInfo for () { // Storage: Scheduler Agenda (r:1 w:1) // Storage: Scheduler Lookup (r:0 w:1) fn on_initialize_named(s: u32, ) -> Weight { - (18_730_000 as Weight) - // Standard Error: 10_000 - .saturating_add((9_909_000 as Weight).saturating_mul(s as Weight)) + (13_946_000 as Weight) + // Standard Error: 4_000 + .saturating_add((4_367_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) } // Storage: Scheduler Agenda (r:1 w:1) fn on_initialize(s: u32, ) -> Weight { - (17_844_000 as Weight) - // Standard Error: 9_000 - .saturating_add((7_719_000 as Weight).saturating_mul(s as Weight)) + (13_151_000 as Weight) + // Standard Error: 4_000 + .saturating_add((3_455_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Scheduler Agenda (r:1 w:1) fn schedule(s: u32, ) -> Weight { - (23_361_000 as Weight) + (14_040_000 as Weight) // Standard Error: 1_000 - .saturating_add((82_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((89_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Scheduler Agenda (r:1 w:1) // Storage: Scheduler Lookup (r:0 w:1) fn cancel(s: u32, ) -> Weight { - (22_359_000 as Weight) - // Standard Error: 2_000 - .saturating_add((1_219_000 as Weight).saturating_mul(s as Weight)) + (14_376_000 as Weight) + // Standard Error: 1_000 + .saturating_add((576_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Scheduler Lookup (r:1 w:1) // Storage: Scheduler Agenda (r:1 w:1) fn schedule_named(s: u32, ) -> Weight { - (28_499_000 as Weight) + (16_806_000 as Weight) // Standard Error: 1_000 - .saturating_add((98_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((102_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Scheduler Lookup (r:1 w:1) // Storage: Scheduler Agenda (r:1 w:1) fn cancel_named(s: u32, ) -> Weight { - (24_995_000 as Weight) + (15_852_000 as Weight) // Standard Error: 2_000 - .saturating_add((1_223_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((590_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } diff --git a/frame/scored-pool/Cargo.toml b/frame/scored-pool/Cargo.toml index b97a7e3664903..af8b0f6aa2643 100644 --- a/frame/scored-pool/Cargo.toml +++ b/frame/scored-pool/Cargo.toml @@ -15,15 +15,15 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } [dev-dependencies] pallet-balances = { version = "4.0.0-dev", path = "../balances" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } [features] default = ["std"] diff --git a/frame/session/Cargo.toml b/frame/session/Cargo.toml index db6f10c728883..a342865615d91 100644 --- a/frame/session/Cargo.toml +++ b/frame/session/Cargo.toml @@ -20,12 +20,12 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-session = { version = "4.0.0-dev", default-features = false, path = "../../primitives/session" } sp-staking = { version = "4.0.0-dev", default-features = false, path = "../../primitives/staking" } -sp-trie = { version = "4.0.0", default-features = false, path = "../../primitives/trie", optional = true } +sp-trie = { version = "5.0.0", default-features = false, path = "../../primitives/trie", optional = true } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } diff --git a/frame/session/benchmarking/Cargo.toml b/frame/session/benchmarking/Cargo.toml index 10a430d52b0a5..cd33c5b186490 100644 --- a/frame/session/benchmarking/Cargo.toml +++ b/frame/session/benchmarking/Cargo.toml @@ -16,7 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"] rand = { version = "0.7.2", default-features = false } sp-std = { version = "4.0.0", default-features = false, path = "../../../primitives/std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } sp-session = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/session" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../../benchmarking" } @@ -28,8 +28,8 @@ pallet-staking = { version = "4.0.0-dev", default-features = false, features = [ [dev-dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", features = ["derive"] } scale-info = "1.0" -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } -sp-io = { version = "4.0.0-dev", path = "../../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../../primitives/io" } pallet-balances = { version = "4.0.0-dev", path = "../../balances" } pallet-timestamp = { version = "4.0.0-dev", path = "../../timestamp" } pallet-staking-reward-curve = { version = "4.0.0-dev", path = "../../staking/reward-curve" } diff --git a/frame/session/benchmarking/src/lib.rs b/frame/session/benchmarking/src/lib.rs index 7beb4631e0518..265c35cbe4908 100644 --- a/frame/session/benchmarking/src/lib.rs +++ b/frame/session/benchmarking/src/lib.rs @@ -28,7 +28,7 @@ use sp_std::{prelude::*, vec}; use frame_benchmarking::benchmarks; use frame_support::{ codec::Decode, - traits::{KeyOwnerProofSystem, OnInitialize}, + traits::{Get, KeyOwnerProofSystem, OnInitialize}, }; use frame_system::RawOrigin; use pallet_session::{historical::Pallet as Historical, Pallet as Session, *}; @@ -53,10 +53,10 @@ impl OnInitialize for Pallet { benchmarks! { set_keys { - let n = ::MAX_NOMINATIONS; + let n = ::MaxNominations::get(); let (v_stash, _) = create_validator_with_nominators::( n, - ::MAX_NOMINATIONS, + ::MaxNominations::get(), false, RewardDestination::Staked, )?; @@ -70,10 +70,10 @@ benchmarks! { }: _(RawOrigin::Signed(v_controller), keys, proof) purge_keys { - let n = ::MAX_NOMINATIONS; + let n = ::MaxNominations::get(); let (v_stash, _) = create_validator_with_nominators::( n, - ::MAX_NOMINATIONS, + ::MaxNominations::get(), false, RewardDestination::Staked )?; diff --git a/frame/session/benchmarking/src/mock.rs b/frame/session/benchmarking/src/mock.rs index 1f00236605130..37305437ca095 100644 --- a/frame/session/benchmarking/src/mock.rs +++ b/frame/session/benchmarking/src/mock.rs @@ -162,7 +162,7 @@ impl onchain::Config for Test { } impl pallet_staking::Config for Test { - const MAX_NOMINATIONS: u32 = 16; + type MaxNominations = ConstU32<16>; type Currency = Balances; type UnixTime = pallet_timestamp::Pallet; type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; diff --git a/frame/session/src/weights.rs b/frame/session/src/weights.rs index 35c9cc7230fb4..39276fb0b17ee 100644 --- a/frame/session/src/weights.rs +++ b/frame/session/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_session //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/session/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -56,7 +57,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Session NextKeys (r:1 w:1) // Storage: Session KeyOwner (r:4 w:4) fn set_keys() -> Weight { - (64_427_000 as Weight) + (42_131_000 as Weight) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(5 as Weight)) } @@ -64,7 +65,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Session NextKeys (r:1 w:1) // Storage: Session KeyOwner (r:0 w:4) fn purge_keys() -> Weight { - (42_497_000 as Weight) + (32_374_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(5 as Weight)) } @@ -76,7 +77,7 @@ impl WeightInfo for () { // Storage: Session NextKeys (r:1 w:1) // Storage: Session KeyOwner (r:4 w:4) fn set_keys() -> Weight { - (64_427_000 as Weight) + (42_131_000 as Weight) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(5 as Weight)) } @@ -84,7 +85,7 @@ impl WeightInfo for () { // Storage: Session NextKeys (r:1 w:1) // Storage: Session KeyOwner (r:0 w:4) fn purge_keys() -> Weight { - (42_497_000 as Weight) + (32_374_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(5 as Weight)) } diff --git a/frame/society/Cargo.toml b/frame/society/Cargo.toml index fa3f981f19d48..2787453d49d3e 100644 --- a/frame/society/Cargo.toml +++ b/frame/society/Cargo.toml @@ -15,15 +15,15 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } rand_chacha = { version = "0.2", default-features = false } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-io ={ version = "4.0.0-dev", path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-io ={ version = "5.0.0", path = "../../primitives/io" } frame-support-test = { version = "3.0.0", path = "../support/test" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } diff --git a/frame/staking/Cargo.toml b/frame/staking/Cargo.toml index e0d5dabaa8927..363ffe4428fb4 100644 --- a/frame/staking/Cargo.toml +++ b/frame/staking/Cargo.toml @@ -13,14 +13,14 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -serde = { version = "1.0.132", optional = true } +serde = { version = "1.0.136", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = [ "derive", ] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-staking = { version = "4.0.0-dev", default-features = false, path = "../../primitives/staking" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } @@ -28,7 +28,7 @@ pallet-session = { version = "4.0.0-dev", default-features = false, features = [ "historical", ], path = "../session" } pallet-authorship = { version = "4.0.0-dev", default-features = false, path = "../authorship" } -sp-application-crypto = { version = "4.0.0", default-features = false, path = "../../primitives/application-crypto" } +sp-application-crypto = { version = "5.0.0", default-features = false, path = "../../primitives/application-crypto" } frame-election-provider-support = { version = "4.0.0-dev", default-features = false, path = "../election-provider-support" } log = { version = "0.4.14", default-features = false } @@ -38,7 +38,7 @@ rand_chacha = { version = "0.2", default-features = false, optional = true } [dev-dependencies] sp-tracing = { version = "4.0.0", path = "../../primitives/tracing" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } sp-npos-elections = { version = "4.0.0-dev", path = "../../primitives/npos-elections" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } pallet-timestamp = { version = "4.0.0-dev", path = "../timestamp" } diff --git a/frame/staking/reward-curve/Cargo.toml b/frame/staking/reward-curve/Cargo.toml index 4c1d2b922f6d6..86fdd09076e5d 100644 --- a/frame/staking/reward-curve/Cargo.toml +++ b/frame/staking/reward-curve/Cargo.toml @@ -21,4 +21,4 @@ proc-macro2 = "1.0.36" proc-macro-crate = "1.1.0" [dev-dependencies] -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } diff --git a/frame/staking/src/benchmarking.rs b/frame/staking/src/benchmarking.rs index 8328adc00a978..65a1ee92e2eab 100644 --- a/frame/staking/src/benchmarking.rs +++ b/frame/staking/src/benchmarking.rs @@ -355,17 +355,17 @@ benchmarks! { kick { // scenario: we want to kick `k` nominators from nominating us (we are a validator). // we'll assume that `k` is under 128 for the purposes of determining the slope. - // each nominator should have `T::MAX_NOMINATIONS` validators nominated, and our validator + // each nominator should have `T::MaxNominations::get()` validators nominated, and our validator // should be somewhere in there. let k in 1 .. 128; - // these are the other validators; there are `T::MAX_NOMINATIONS - 1` of them, so - // there are a total of `T::MAX_NOMINATIONS` validators in the system. - let rest_of_validators = create_validators_with_seed::(T::MAX_NOMINATIONS - 1, 100, 415)?; + // these are the other validators; there are `T::MaxNominations::get() - 1` of them, so + // there are a total of `T::MaxNominations::get()` validators in the system. + let rest_of_validators = create_validators_with_seed::(T::MaxNominations::get() - 1, 100, 415)?; // this is the validator that will be kicking. let (stash, controller) = create_stash_controller::( - T::MAX_NOMINATIONS - 1, + T::MaxNominations::get() - 1, 100, Default::default(), )?; @@ -380,7 +380,7 @@ benchmarks! { for i in 0 .. k { // create a nominator stash. let (n_stash, n_controller) = create_stash_controller::( - T::MAX_NOMINATIONS + i, + T::MaxNominations::get() + i, 100, Default::default(), )?; @@ -415,9 +415,9 @@ benchmarks! { } } - // Worst case scenario, T::MAX_NOMINATIONS + // Worst case scenario, T::MaxNominations::get() nominate { - let n in 1 .. T::MAX_NOMINATIONS; + let n in 1 .. T::MaxNominations::get(); // clean up any existing state. clear_validators_and_nominators::(); @@ -428,7 +428,7 @@ benchmarks! { // we are just doing an insert into the origin position. let scenario = ListScenario::::new(origin_weight, true)?; let (stash, controller) = create_stash_controller_with_balance::( - SEED + T::MAX_NOMINATIONS + 1, // make sure the account does not conflict with others + SEED + T::MaxNominations::get() + 1, // make sure the account does not conflict with others origin_weight, Default::default(), ).unwrap(); @@ -724,7 +724,7 @@ benchmarks! { create_validators_with_nominators_for_era::( v, n, - ::MAX_NOMINATIONS as usize, + ::MaxNominations::get() as usize, false, None, )?; @@ -742,7 +742,7 @@ benchmarks! { create_validators_with_nominators_for_era::( v, n, - ::MAX_NOMINATIONS as usize, + ::MaxNominations::get() as usize, false, None, )?; @@ -822,7 +822,7 @@ benchmarks! { let s in 1 .. 20; let validators = create_validators_with_nominators_for_era::( - v, n, T::MAX_NOMINATIONS as usize, false, None + v, n, T::MaxNominations::get() as usize, false, None )? .into_iter() .map(|v| T::Lookup::lookup(v).unwrap()) @@ -845,7 +845,7 @@ benchmarks! { let n = MaxNominators::::get(); let _ = create_validators_with_nominators_for_era::( - v, n, T::MAX_NOMINATIONS as usize, false, None + v, n, T::MaxNominations::get() as usize, false, None )?; }: { let targets = >::get_npos_targets(); @@ -900,6 +900,35 @@ benchmarks! { assert!(!T::SortedListProvider::contains(&stash)); } + force_apply_min_commission { + // Clean up any existing state + clear_validators_and_nominators::(); + + // Create a validator with a commission of 50% + let (stash, controller) = + create_stash_controller::(1, 1, RewardDestination::Staked)?; + let validator_prefs = + ValidatorPrefs { commission: Perbill::from_percent(50), ..Default::default() }; + Staking::::validate(RawOrigin::Signed(controller).into(), validator_prefs)?; + + // Sanity check + assert_eq!( + Validators::::get(&stash), + ValidatorPrefs { commission: Perbill::from_percent(50), ..Default::default() } + ); + + // Set the min commission to 75% + MinCommission::::set(Perbill::from_percent(75)); + let caller = whitelisted_caller(); + }: _(RawOrigin::Signed(caller), stash.clone()) + verify { + // The validators commission has been bumped to 75% + assert_eq!( + Validators::::get(&stash), + ValidatorPrefs { commission: Perbill::from_percent(75), ..Default::default() } + ); + } + impl_benchmark_test_suite!( Staking, crate::mock::ExtBuilder::default().has_stakers(true), @@ -923,7 +952,7 @@ mod tests { create_validators_with_nominators_for_era::( v, n, - ::MAX_NOMINATIONS as usize, + ::MaxNominations::get() as usize, false, None, ) diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index efe67c8b00c85..17af4829c0ea8 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -303,6 +303,7 @@ use codec::{Decode, Encode, HasCompact}; use frame_support::{ traits::{ConstU32, Currency, Get}, weights::Weight, + BoundedVec, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound, }; use scale_info::TypeInfo; use sp_runtime::{ @@ -574,10 +575,12 @@ where } /// A record of the nominations made by a specific account. -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct Nominations { +#[derive(PartialEqNoBound, EqNoBound, Clone, Encode, Decode, RuntimeDebugNoBound, TypeInfo)] +#[codec(mel_bound())] +#[scale_info(skip_type_params(T))] +pub struct Nominations { /// The targets of nomination. - pub targets: Vec, + pub targets: BoundedVec, /// The era the nominations were submitted. /// /// Except for initial nominations which are considered submitted at era 0. diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 3bf46588044a6..95f305dfdd22a 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -234,6 +234,7 @@ const THRESHOLDS: [sp_npos_elections::VoteWeight; 9] = parameter_types! { pub static BagThresholds: &'static [sp_npos_elections::VoteWeight] = &THRESHOLDS; + pub static MaxNominations: u32 = 16; } impl pallet_bags_list::Config for Test { @@ -249,7 +250,7 @@ impl onchain::Config for Test { } impl crate::pallet::pallet::Config for Test { - const MAX_NOMINATIONS: u32 = 16; + type MaxNominations = MaxNominations; type Currency = Balances; type UnixTime = Timestamp; type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; @@ -533,7 +534,7 @@ fn post_conditions() { } fn check_count() { - let nominator_count = Nominators::::iter().count() as u32; + let nominator_count = Nominators::::iter_keys().count() as u32; let validator_count = Validators::::iter().count() as u32; assert_eq!(nominator_count, Nominators::::count()); assert_eq!(validator_count, Validators::::count()); diff --git a/frame/staking/src/pallet/impls.rs b/frame/staking/src/pallet/impls.rs index 68b5c19027a9b..ae20550cd40b6 100644 --- a/frame/staking/src/pallet/impls.rs +++ b/frame/staking/src/pallet/impls.rs @@ -19,13 +19,13 @@ use frame_election_provider_support::{ data_provider, ElectionDataProvider, ElectionProvider, SortedListProvider, Supports, - VoteWeight, VoteWeightProvider, + VoteWeight, VoteWeightProvider, VoterOf, }; use frame_support::{ pallet_prelude::*, traits::{ - Currency, CurrencyToVote, EstimateNextNewSession, Get, Imbalance, LockableCurrency, - OnUnbalanced, UnixTime, WithdrawReasons, + Currency, CurrencyToVote, Defensive, EstimateNextNewSession, Get, Imbalance, + LockableCurrency, OnUnbalanced, UnixTime, WithdrawReasons, }, weights::{Weight, WithPostDispatchInfo}, }; @@ -661,9 +661,7 @@ impl Pallet { /// /// All nominations that have been submitted before the last non-zero slash of the validator are /// auto-chilled, but still count towards the limit imposed by `maybe_max_len`. - pub fn get_npos_voters( - maybe_max_len: Option, - ) -> Vec<(T::AccountId, VoteWeight, Vec)> { + pub fn get_npos_voters(maybe_max_len: Option) -> Vec> { let max_allowed_len = { let nominator_count = Nominators::::count() as usize; let validator_count = Validators::::count() as usize; @@ -677,8 +675,13 @@ impl Pallet { let mut validators_taken = 0u32; for (validator, _) in >::iter().take(max_allowed_len) { // Append self vote. - let self_vote = - (validator.clone(), Self::weight_of(&validator), vec![validator.clone()]); + let self_vote = ( + validator.clone(), + Self::weight_of(&validator), + vec![validator.clone()] + .try_into() + .expect("`MaxVotesPerVoter` must be greater than or equal to 1"), + ); all_voters.push(self_vote); validators_taken.saturating_inc(); } @@ -724,7 +727,12 @@ impl Pallet { nominators_taken.saturating_inc(); } } else { - log!(error, "DEFENSIVE: invalid item in `SortedListProvider`: {:?}", nominator) + // this can only happen if: 1. there a pretty bad bug in the bags-list (or whatever + // is the sorted list) logic and the state of the two pallets is no longer + // compatible, or because the nominators is not decodable since they have more + // nomination than `T::MaxNominations`. This can rarely happen, and is not really an + // emergency or bug if it does. + log!(warn, "DEFENSIVE: invalid item in `SortedListProvider`: {:?}, this nominator probably has too many nominations now", nominator) } } @@ -772,13 +780,11 @@ impl Pallet { /// NOTE: you must ALWAYS use this function to add nominator or update their targets. Any access /// to `Nominators` or `VoterList` outside of this function is almost certainly /// wrong. - pub fn do_add_nominator(who: &T::AccountId, nominations: Nominations) { + pub fn do_add_nominator(who: &T::AccountId, nominations: Nominations) { if !Nominators::::contains_key(who) { // maybe update sorted list. Error checking is defensive-only - this should never fail. - if T::SortedListProvider::on_insert(who.clone(), Self::weight_of(who)).is_err() { - log!(warn, "attempt to insert duplicate nominator ({:#?})", who); - debug_assert!(false, "attempt to insert duplicate nominator"); - }; + let _ = T::SortedListProvider::on_insert(who.clone(), Self::weight_of(who)) + .defensive_unwrap_or_default(); debug_assert_eq!(T::SortedListProvider::sanity_check(), Ok(())); } @@ -847,16 +853,14 @@ impl Pallet { impl ElectionDataProvider for Pallet { type AccountId = T::AccountId; type BlockNumber = BlockNumberFor; - const MAXIMUM_VOTES_PER_VOTER: u32 = T::MAX_NOMINATIONS; + type MaxVotesPerVoter = T::MaxNominations; fn desired_targets() -> data_provider::Result { Self::register_weight(T::DbWeight::get().reads(1)); Ok(Self::validator_count()) } - fn voters( - maybe_max_len: Option, - ) -> data_provider::Result)>> { + fn voters(maybe_max_len: Option) -> data_provider::Result>> { // This can never fail -- if `maybe_max_len` is `Some(_)` we handle it. let voters = Self::get_npos_voters(maybe_max_len); debug_assert!(maybe_max_len.map_or(true, |max| voters.len() <= max)); @@ -909,7 +913,11 @@ impl ElectionDataProvider for Pallet { } #[cfg(feature = "runtime-benchmarks")] - fn add_voter(voter: T::AccountId, weight: VoteWeight, targets: Vec) { + fn add_voter( + voter: T::AccountId, + weight: VoteWeight, + targets: BoundedVec, + ) { let stake = >::try_from(weight).unwrap_or_else(|_| { panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.") }); @@ -924,6 +932,7 @@ impl ElectionDataProvider for Pallet { claimed_rewards: vec![], }, ); + Self::do_add_nominator(&voter, Nominations { targets, submitted_in: 0, suppressed: false }); } @@ -959,7 +968,7 @@ impl ElectionDataProvider for Pallet { #[cfg(feature = "runtime-benchmarks")] fn put_snapshot( - voters: Vec<(T::AccountId, VoteWeight, Vec)>, + voters: Vec>, targets: Vec, target_stake: Option, ) { @@ -1001,7 +1010,7 @@ impl ElectionDataProvider for Pallet { ); Self::do_add_nominator( &v, - Nominations { targets: t, submitted_in: 0, suppressed: false }, + Nominations { targets: t.try_into().unwrap(), submitted_in: 0, suppressed: false }, ); }); } diff --git a/frame/staking/src/pallet/mod.rs b/frame/staking/src/pallet/mod.rs index 20864e4829e66..2be75752f101d 100644 --- a/frame/staking/src/pallet/mod.rs +++ b/frame/staking/src/pallet/mod.rs @@ -32,7 +32,7 @@ use sp_runtime::{ DispatchError, Perbill, Percent, }; use sp_staking::{EraIndex, SessionIndex}; -use sp_std::{convert::From, prelude::*, result}; +use sp_std::{convert::From, prelude::*}; mod impls; @@ -50,6 +50,8 @@ const STAKING_ID: LockIdentifier = *b"staking "; #[frame_support::pallet] pub mod pallet { + use frame_election_provider_support::ElectionDataProvider; + use crate::BenchmarkingConfig; use super::*; @@ -94,7 +96,7 @@ pub mod pallet { >; /// Maximum number of nominations per nominator. - const MAX_NOMINATIONS: u32; + type MaxNominations: Get; /// Tokens have been minted and are unused for validator-reward. /// See [Era payout](./index.html#era-payout). @@ -161,15 +163,6 @@ pub mod pallet { type WeightInfo: WeightInfo; } - #[pallet::extra_constants] - impl Pallet { - // TODO: rename to snake case after https://github.com/paritytech/substrate/issues/8826 fixed. - #[allow(non_snake_case)] - fn MaxNominations() -> u32 { - T::MAX_NOMINATIONS - } - } - #[pallet::type_value] pub(crate) fn HistoryDepthOnEmpty() -> u32 { 84u32 @@ -246,11 +239,26 @@ pub mod pallet { #[pallet::storage] pub type MaxValidatorsCount = StorageValue<_, u32, OptionQuery>; - /// The map from nominator stash key to the set of stash keys of all validators to nominate. + /// The map from nominator stash key to their nomination preferences, namely the validators that + /// they wish to support. + /// + /// Note that the keys of this storage map might become non-decodable in case the + /// [`Config::MaxNominations`] configuration is decreased. In this rare case, these nominators + /// are still existent in storage, their key is correct and retrievable (i.e. `contains_key` + /// indicates that they exist), but their value cannot be decoded. Therefore, the non-decodable + /// nominators will effectively not-exist, until they re-submit their preferences such that it + /// is within the bounds of the newly set `Config::MaxNominations`. + /// + /// This implies that `::iter_keys().count()` and `::iter().count()` might return different + /// values for this map. Moreover, the main `::count()` is aligned with the former, namely the + /// number of keys that exist. + /// + /// Lastly, if any of the nominators become non-decodable, they can be chilled immediately via + /// [`Call::chill_other`] dispatchable by anyone. #[pallet::storage] #[pallet::getter(fn nominators)] pub type Nominators = - CountedStorageMap<_, Twox64Concat, T::AccountId, Nominations>; + CountedStorageMap<_, Twox64Concat, T::AccountId, Nominations>; /// The maximum nominator count before we stop allowing new validators to join. /// @@ -681,6 +689,14 @@ pub mod pallet { } fn integrity_test() { + // ensure that we funnel the correct value to the `DataProvider::MaxVotesPerVoter`; + assert_eq!( + T::MaxNominations::get(), + ::MaxVotesPerVoter::get() + ); + // and that MaxNominations is always greater than 1, since we count on this. + assert!(!T::MaxNominations::get().is_zero()); + sp_std::if_std! { sp_io::TestExternalities::new_empty().execute_with(|| assert!( @@ -978,7 +994,7 @@ pub mod pallet { /// /// # /// - The transaction's complexity is proportional to the size of `targets` (N) - /// which is capped at CompactAssignments::LIMIT (MAX_NOMINATIONS). + /// which is capped at CompactAssignments::LIMIT (T::MaxNominations). /// - Both the reads and writes follow a similar pattern. /// # #[pallet::weight(T::WeightInfo::nominate(targets.len() as u32))] @@ -1006,11 +1022,11 @@ pub mod pallet { } ensure!(!targets.is_empty(), Error::::EmptyTargets); - ensure!(targets.len() <= T::MAX_NOMINATIONS as usize, Error::::TooManyTargets); + ensure!(targets.len() <= T::MaxNominations::get() as usize, Error::::TooManyTargets); - let old = Nominators::::get(stash).map_or_else(Vec::new, |x| x.targets); + let old = Nominators::::get(stash).map_or_else(Vec::new, |x| x.targets.into_inner()); - let targets = targets + let targets: BoundedVec<_, _> = targets .into_iter() .map(|t| T::Lookup::lookup(t).map_err(DispatchError::from)) .map(|n| { @@ -1022,11 +1038,13 @@ pub mod pallet { } }) }) - .collect::, _>>()?; + .collect::, _>>()? + .try_into() + .map_err(|_| Error::::TooManyNominators)?; let nominations = Nominations { targets, - // Initial nominations are considered submitted at era 0. See `Nominations` doc + // Initial nominations are considered submitted at era 0. See `Nominations` doc. submitted_in: Self::current_era().unwrap_or(0), suppressed: false, }; @@ -1216,11 +1234,6 @@ pub mod pallet { /// Set the validators who cannot be slashed (if any). /// /// The dispatch origin must be Root. - /// - /// # - /// - O(V) - /// - Write: Invulnerables - /// # #[pallet::weight(T::WeightInfo::set_invulnerables(invulnerables.len() as u32))] pub fn set_invulnerables( origin: OriginFor, @@ -1234,13 +1247,6 @@ pub mod pallet { /// Force a current staker to become completely unstaked, immediately. /// /// The dispatch origin must be Root. - /// - /// # - /// O(S) where S is the number of slashing spans to be removed - /// Reads: Bonded, Slashing Spans, Account, Locks - /// Writes: Bonded, Slashing Spans (if S > 0), Ledger, Payee, Validators, Nominators, - /// Account, Locks Writes Each: SpanSlash * S - /// # #[pallet::weight(T::WeightInfo::force_unstake(*num_slashing_spans))] pub fn force_unstake( origin: OriginFor, @@ -1266,11 +1272,6 @@ pub mod pallet { /// The election process starts multiple blocks before the end of the era. /// If this is called just before a new era is triggered, the election process may not /// have enough blocks to get a result. - /// - /// # - /// - Weight: O(1) - /// - Write: ForceEra - /// # #[pallet::weight(T::WeightInfo::force_new_era_always())] pub fn force_new_era_always(origin: OriginFor) -> DispatchResult { ensure_root(origin)?; @@ -1283,14 +1284,6 @@ pub mod pallet { /// Can be called by the `T::SlashCancelOrigin`. /// /// Parameters: era and indices of the slashes for that era to kill. - /// - /// # - /// Complexity: O(U + S) - /// with U unapplied slashes weighted with U=1000 - /// and S is the number of slash indices to be canceled. - /// - Read: Unapplied Slashes - /// - Write: Unapplied Slashes - /// # #[pallet::weight(T::WeightInfo::cancel_deferred_slash(slash_indices.len() as u32))] pub fn cancel_deferred_slash( origin: OriginFor, @@ -1550,6 +1543,11 @@ pub mod pallet { /// /// If the caller is different than the controller being targeted, the following conditions /// must be met: + /// + /// * `controller` must belong to a nominator who has become non-decodable, + /// + /// Or: + /// /// * A `ChillThreshold` must be set and checked which defines how close to the max /// nominators or validators we must reach before users can start chilling one-another. /// * A `MaxNominatorCount` and `MaxValidatorCount` must be set which is used to determine @@ -1568,6 +1566,11 @@ pub mod pallet { let stash = ledger.stash; // In order for one user to chill another user, the following conditions must be met: + // + // * `controller` belongs to a nominator who has become non-decodable, + // + // Or + // // * A `ChillThreshold` is set which defines how close to the max nominators or // validators we must reach before users can start chilling one-another. // * A `MaxNominatorCount` and `MaxValidatorCount` which is used to determine how close @@ -1577,6 +1580,12 @@ pub mod pallet { // threshold bond required. // // Otherwise, if caller is the same as the controller, this is just like `chill`. + + if Nominators::::contains_key(&stash) && Nominators::::get(&stash).is_none() { + Self::chill_stash(&stash); + return Ok(()) + } + if caller != controller { let threshold = ChillThreshold::::get().ok_or(Error::::CannotChillOther)?; let min_active_bond = if Nominators::::contains_key(&stash) { @@ -1607,6 +1616,28 @@ pub mod pallet { Self::chill_stash(&stash); Ok(()) } + + /// Force a validator to have at least the minimum commission. This will not affect a + /// validator who already has a commission greater than or equal to the minimum. Any account + /// can call this. + #[pallet::weight(T::WeightInfo::force_apply_min_commission())] + pub fn force_apply_min_commission( + origin: OriginFor, + validator_stash: T::AccountId, + ) -> DispatchResult { + ensure_signed(origin)?; + let min_commission = MinCommission::::get(); + Validators::::try_mutate_exists(validator_stash, |maybe_prefs| { + maybe_prefs + .as_mut() + .map(|prefs| { + (prefs.commission < min_commission) + .then(|| prefs.commission = min_commission) + }) + .ok_or(Error::::NotStash) + })?; + Ok(()) + } } } diff --git a/frame/staking/src/tests.rs b/frame/staking/src/tests.rs index 8d465c8c93dc4..4073c069fb6be 100644 --- a/frame/staking/src/tests.rs +++ b/frame/staking/src/tests.rs @@ -4248,7 +4248,11 @@ fn count_check_works() { Validators::::insert(987654321, ValidatorPrefs::default()); Nominators::::insert( 987654321, - Nominations { targets: vec![], submitted_in: Default::default(), suppressed: false }, + Nominations { + targets: Default::default(), + submitted_in: Default::default(), + suppressed: false, + }, ); }) } @@ -4589,6 +4593,100 @@ fn min_commission_works() { }) } +#[test] +fn change_of_max_nominations() { + use frame_election_provider_support::ElectionDataProvider; + ExtBuilder::default() + .add_staker(60, 61, 10, StakerStatus::Nominator(vec![1])) + .add_staker(70, 71, 10, StakerStatus::Nominator(vec![1, 2, 3])) + .balance_factor(10) + .build_and_execute(|| { + // pre-condition + assert_eq!(MaxNominations::get(), 16); + + assert_eq!( + Nominators::::iter() + .map(|(k, n)| (k, n.targets.len())) + .collect::>(), + vec![(70, 3), (101, 2), (60, 1)] + ); + // 3 validators and 3 nominators + assert_eq!(Staking::voters(None).unwrap().len(), 3 + 3); + + // abrupt change from 16 to 4, everyone should be fine. + MaxNominations::set(4); + + assert_eq!( + Nominators::::iter() + .map(|(k, n)| (k, n.targets.len())) + .collect::>(), + vec![(70, 3), (101, 2), (60, 1)] + ); + assert_eq!(Staking::voters(None).unwrap().len(), 3 + 3); + + // abrupt change from 4 to 3, everyone should be fine. + MaxNominations::set(3); + + assert_eq!( + Nominators::::iter() + .map(|(k, n)| (k, n.targets.len())) + .collect::>(), + vec![(70, 3), (101, 2), (60, 1)] + ); + assert_eq!(Staking::voters(None).unwrap().len(), 3 + 3); + + // abrupt change from 3 to 2, this should cause some nominators to be non-decodable, and + // thus non-existent unless if they update. + MaxNominations::set(2); + + assert_eq!( + Nominators::::iter() + .map(|(k, n)| (k, n.targets.len())) + .collect::>(), + vec![(101, 2), (60, 1)] + ); + // 70 is still in storage.. + assert!(Nominators::::contains_key(70)); + // but its value cannot be decoded and default is returned. + assert!(Nominators::::get(70).is_none()); + + assert_eq!(Staking::voters(None).unwrap().len(), 3 + 2); + assert!(Nominators::::contains_key(101)); + + // abrupt change from 2 to 1, this should cause some nominators to be non-decodable, and + // thus non-existent unless if they update. + MaxNominations::set(1); + + assert_eq!( + Nominators::::iter() + .map(|(k, n)| (k, n.targets.len())) + .collect::>(), + vec![(60, 1)] + ); + assert!(Nominators::::contains_key(70)); + assert!(Nominators::::contains_key(60)); + assert!(Nominators::::get(70).is_none()); + assert!(Nominators::::get(60).is_some()); + assert_eq!(Staking::voters(None).unwrap().len(), 3 + 1); + + // now one of them can revive themselves by re-nominating to a proper value. + assert_ok!(Staking::nominate(Origin::signed(71), vec![1])); + assert_eq!( + Nominators::::iter() + .map(|(k, n)| (k, n.targets.len())) + .collect::>(), + vec![(70, 1), (60, 1)] + ); + + // or they can be chilled by any account. + assert!(Nominators::::contains_key(101)); + assert!(Nominators::::get(101).is_none()); + assert_ok!(Staking::chill_other(Origin::signed(70), 100)); + assert!(!Nominators::::contains_key(101)); + assert!(Nominators::::get(101).is_none()); + }) +} + mod sorted_list_provider { use super::*; use frame_election_provider_support::SortedListProvider; @@ -4613,3 +4711,38 @@ mod sorted_list_provider { }); } } + +#[test] +fn force_apply_min_commission_works() { + let prefs = |c| ValidatorPrefs { commission: Perbill::from_percent(c), blocked: false }; + let validators = || Validators::::iter().collect::>(); + ExtBuilder::default().build_and_execute(|| { + assert_ok!(Staking::validate(Origin::signed(30), prefs(10))); + assert_ok!(Staking::validate(Origin::signed(20), prefs(5))); + + // Given + assert_eq!(validators(), vec![(31, prefs(10)), (21, prefs(5)), (11, prefs(0))]); + MinCommission::::set(Perbill::from_percent(5)); + + // When applying to a commission greater than min + assert_ok!(Staking::force_apply_min_commission(Origin::signed(1), 31)); + // Then the commission is not changed + assert_eq!(validators(), vec![(31, prefs(10)), (21, prefs(5)), (11, prefs(0))]); + + // When applying to a commission that is equal to min + assert_ok!(Staking::force_apply_min_commission(Origin::signed(1), 21)); + // Then the commission is not changed + assert_eq!(validators(), vec![(31, prefs(10)), (21, prefs(5)), (11, prefs(0))]); + + // When applying to a commission that is less than the min + assert_ok!(Staking::force_apply_min_commission(Origin::signed(1), 11)); + // Then the commission is bumped to the min + assert_eq!(validators(), vec![(31, prefs(10)), (21, prefs(5)), (11, prefs(5))]); + + // When applying commission to a validator that doesn't exist then storage is not altered + assert_noop!( + Staking::force_apply_min_commission(Origin::signed(1), 420), + Error::::NotStash + ); + }); +} diff --git a/frame/staking/src/weights.rs b/frame/staking/src/weights.rs index 4f5af6fcd5f8e..dcb544283c225 100644 --- a/frame/staking/src/weights.rs +++ b/frame/staking/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_staking //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-11-29, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-02-09, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -72,6 +72,7 @@ pub trait WeightInfo { fn get_npos_targets(v: u32, ) -> Weight; fn set_staking_configs() -> Weight; fn chill_other() -> Weight; + fn force_apply_min_commission() -> Weight; } /// Weights for pallet_staking using the Substrate node and recommended hardware. @@ -84,7 +85,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Balances Locks (r:1 w:1) // Storage: Staking Payee (r:0 w:1) fn bond() -> Weight { - (63_660_000 as Weight) + (37_772_000 as Weight) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } @@ -94,7 +95,7 @@ impl WeightInfo for SubstrateWeight { // Storage: BagsList ListNodes (r:3 w:3) // Storage: BagsList ListBags (r:2 w:2) fn bond_extra() -> Weight { - (103_672_000 as Weight) + (64_816_000 as Weight) .saturating_add(T::DbWeight::get().reads(8 as Weight)) .saturating_add(T::DbWeight::get().writes(7 as Weight)) } @@ -108,7 +109,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking Bonded (r:1 w:0) // Storage: BagsList ListBags (r:2 w:2) fn unbond() -> Weight { - (110_884_000 as Weight) + (71_635_000 as Weight) .saturating_add(T::DbWeight::get().reads(12 as Weight)) .saturating_add(T::DbWeight::get().writes(8 as Weight)) } @@ -117,9 +118,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) fn withdraw_unbonded_update(s: u32, ) -> Weight { - (46_379_000 as Weight) + (30_612_000 as Weight) // Standard Error: 0 - .saturating_add((55_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((59_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -137,7 +138,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Balances Locks (r:1 w:1) // Storage: Staking Payee (r:0 w:1) fn withdraw_unbonded_kill(_s: u32, ) -> Weight { - (91_303_000 as Weight) + (59_116_000 as Weight) .saturating_add(T::DbWeight::get().reads(13 as Weight)) .saturating_add(T::DbWeight::get().writes(11 as Weight)) } @@ -153,16 +154,16 @@ impl WeightInfo for SubstrateWeight { // Storage: BagsList CounterForListNodes (r:1 w:1) // Storage: Staking CounterForValidators (r:1 w:1) fn validate() -> Weight { - (66_587_000 as Weight) + (45_505_000 as Weight) .saturating_add(T::DbWeight::get().reads(12 as Weight)) .saturating_add(T::DbWeight::get().writes(8 as Weight)) } // Storage: Staking Ledger (r:1 w:0) // Storage: Staking Nominators (r:1 w:1) fn kick(k: u32, ) -> Weight { - (21_153_000 as Weight) - // Standard Error: 16_000 - .saturating_add((13_502_000 as Weight).saturating_mul(k as Weight)) + (12_764_000 as Weight) + // Standard Error: 15_000 + .saturating_add((8_301_000 as Weight).saturating_mul(k as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(k as Weight))) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(k as Weight))) @@ -173,15 +174,15 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking MaxNominatorsCount (r:1 w:0) // Storage: Staking Validators (r:2 w:0) // Storage: Staking CurrentEra (r:1 w:0) - // Storage: Staking CounterForNominators (r:1 w:1) // Storage: Staking Bonded (r:1 w:0) // Storage: BagsList ListNodes (r:2 w:2) // Storage: BagsList ListBags (r:1 w:1) // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: Staking CounterForNominators (r:1 w:1) fn nominate(n: u32, ) -> Weight { - (75_456_000 as Weight) - // Standard Error: 12_000 - .saturating_add((5_051_000 as Weight).saturating_mul(n as Weight)) + (51_439_000 as Weight) + // Standard Error: 10_000 + .saturating_add((3_323_000 as Weight).saturating_mul(n as Weight)) .saturating_add(T::DbWeight::get().reads(12 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(n as Weight))) .saturating_add(T::DbWeight::get().writes(6 as Weight)) @@ -194,49 +195,49 @@ impl WeightInfo for SubstrateWeight { // Storage: BagsList ListBags (r:1 w:1) // Storage: BagsList CounterForListNodes (r:1 w:1) fn chill() -> Weight { - (65_332_000 as Weight) + (44_847_000 as Weight) .saturating_add(T::DbWeight::get().reads(8 as Weight)) .saturating_add(T::DbWeight::get().writes(6 as Weight)) } // Storage: Staking Ledger (r:1 w:0) // Storage: Staking Payee (r:0 w:1) fn set_payee() -> Weight { - (11_757_000 as Weight) + (7_795_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Staking Bonded (r:1 w:1) // Storage: Staking Ledger (r:2 w:2) fn set_controller() -> Weight { - (24_252_000 as Weight) + (16_051_000 as Weight) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } // Storage: Staking ValidatorCount (r:0 w:1) fn set_validator_count() -> Weight { - (2_252_000 as Weight) + (1_107_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Staking ForceEra (r:0 w:1) fn force_no_eras() -> Weight { - (2_431_000 as Weight) + (1_126_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Staking ForceEra (r:0 w:1) fn force_new_era() -> Weight { - (2_397_000 as Weight) + (1_183_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Staking ForceEra (r:0 w:1) fn force_new_era_always() -> Weight { - (2_423_000 as Weight) + (1_181_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Staking Invulnerables (r:0 w:1) fn set_invulnerables(v: u32, ) -> Weight { - (2_876_000 as Weight) + (1_705_000 as Weight) // Standard Error: 0 - .saturating_add((53_000 as Weight).saturating_mul(v as Weight)) + .saturating_add((50_000 as Weight).saturating_mul(v as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Staking Bonded (r:1 w:1) @@ -253,18 +254,18 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking Payee (r:0 w:1) // Storage: Staking SpanSlash (r:0 w:2) fn force_unstake(s: u32, ) -> Weight { - (87_540_000 as Weight) + (57_431_000 as Weight) // Standard Error: 1_000 - .saturating_add((1_791_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((801_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(11 as Weight)) .saturating_add(T::DbWeight::get().writes(12 as Weight)) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) } // Storage: Staking UnappliedSlashes (r:1 w:1) fn cancel_deferred_slash(s: u32, ) -> Weight { - (2_769_801_000 as Weight) - // Standard Error: 181_000 - .saturating_add((16_225_000 as Weight).saturating_mul(s as Weight)) + (950_258_000 as Weight) + // Standard Error: 56_000 + .saturating_add((5_001_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -279,9 +280,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking Payee (r:2 w:0) // Storage: System Account (r:2 w:2) fn payout_stakers_dead_controller(n: u32, ) -> Weight { - (103_452_000 as Weight) - // Standard Error: 19_000 - .saturating_add((42_909_000 as Weight).saturating_mul(n as Weight)) + (94_238_000 as Weight) + // Standard Error: 15_000 + .saturating_add((23_978_000 as Weight).saturating_mul(n as Weight)) .saturating_add(T::DbWeight::get().reads(10 as Weight)) .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(n as Weight))) .saturating_add(T::DbWeight::get().writes(2 as Weight)) @@ -299,9 +300,9 @@ impl WeightInfo for SubstrateWeight { // Storage: System Account (r:2 w:2) // Storage: Balances Locks (r:2 w:2) fn payout_stakers_alive_staked(n: u32, ) -> Weight { - (145_995_000 as Weight) - // Standard Error: 27_000 - .saturating_add((55_974_000 as Weight).saturating_mul(n as Weight)) + (109_323_000 as Weight) + // Standard Error: 22_000 + .saturating_add((33_887_000 as Weight).saturating_mul(n as Weight)) .saturating_add(T::DbWeight::get().reads(11 as Weight)) .saturating_add(T::DbWeight::get().reads((5 as Weight).saturating_mul(n as Weight))) .saturating_add(T::DbWeight::get().writes(3 as Weight)) @@ -314,9 +315,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking Bonded (r:1 w:0) // Storage: BagsList ListBags (r:2 w:2) fn rebond(l: u32, ) -> Weight { - (101_568_000 as Weight) + (64_807_000 as Weight) // Standard Error: 2_000 - .saturating_add((66_000 as Weight).saturating_mul(l as Weight)) + .saturating_add((50_000 as Weight).saturating_mul(l as Weight)) .saturating_add(T::DbWeight::get().reads(9 as Weight)) .saturating_add(T::DbWeight::get().writes(8 as Weight)) } @@ -331,8 +332,8 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking ErasStartSessionIndex (r:0 w:1) fn set_history_depth(e: u32, ) -> Weight { (0 as Weight) - // Standard Error: 69_000 - .saturating_add((29_939_000 as Weight).saturating_mul(e as Weight)) + // Standard Error: 61_000 + .saturating_add((20_457_000 as Weight).saturating_mul(e as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) .saturating_add(T::DbWeight::get().writes((7 as Weight).saturating_mul(e as Weight))) @@ -351,9 +352,9 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking Payee (r:0 w:1) // Storage: Staking SpanSlash (r:0 w:1) fn reap_stash(s: u32, ) -> Weight { - (96_886_000 as Weight) - // Standard Error: 1_000 - .saturating_add((1_790_000 as Weight).saturating_mul(s as Weight)) + (62_856_000 as Weight) + // Standard Error: 0 + .saturating_add((802_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(12 as Weight)) .saturating_add(T::DbWeight::get().writes(12 as Weight)) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) @@ -378,10 +379,10 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking ErasStartSessionIndex (r:0 w:1) fn new_era(v: u32, n: u32, ) -> Weight { (0 as Weight) - // Standard Error: 873_000 - .saturating_add((286_141_000 as Weight).saturating_mul(v as Weight)) - // Standard Error: 43_000 - .saturating_add((44_712_000 as Weight).saturating_mul(n as Weight)) + // Standard Error: 804_000 + .saturating_add((226_855_000 as Weight).saturating_mul(v as Weight)) + // Standard Error: 40_000 + .saturating_add((31_928_000 as Weight).saturating_mul(n as Weight)) .saturating_add(T::DbWeight::get().reads(208 as Weight)) .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(v as Weight))) .saturating_add(T::DbWeight::get().reads((4 as Weight).saturating_mul(n as Weight))) @@ -400,9 +401,11 @@ impl WeightInfo for SubstrateWeight { fn get_npos_voters(v: u32, n: u32, s: u32, ) -> Weight { (0 as Weight) // Standard Error: 87_000 - .saturating_add((24_049_000 as Weight).saturating_mul(v as Weight)) + .saturating_add((18_771_000 as Weight).saturating_mul(v as Weight)) // Standard Error: 87_000 - .saturating_add((27_514_000 as Weight).saturating_mul(n as Weight)) + .saturating_add((21_895_000 as Weight).saturating_mul(n as Weight)) + // Standard Error: 2_984_000 + .saturating_add((8_282_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(204 as Weight)) .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(v as Weight))) .saturating_add(T::DbWeight::get().reads((4 as Weight).saturating_mul(n as Weight))) @@ -411,8 +414,8 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking Validators (r:501 w:0) fn get_npos_targets(v: u32, ) -> Weight { (0 as Weight) - // Standard Error: 32_000 - .saturating_add((10_128_000 as Weight).saturating_mul(v as Weight)) + // Standard Error: 28_000 + .saturating_add((7_801_000 as Weight).saturating_mul(v as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(v as Weight))) } @@ -423,12 +426,12 @@ impl WeightInfo for SubstrateWeight { // Storage: Staking MaxNominatorsCount (r:0 w:1) // Storage: Staking MinNominatorBond (r:0 w:1) fn set_staking_configs() -> Weight { - (6_187_000 as Weight) + (3_680_000 as Weight) .saturating_add(T::DbWeight::get().writes(6 as Weight)) } // Storage: Staking Ledger (r:1 w:0) - // Storage: Staking ChillThreshold (r:1 w:0) // Storage: Staking Nominators (r:1 w:1) + // Storage: Staking ChillThreshold (r:1 w:0) // Storage: Staking MaxNominatorsCount (r:1 w:0) // Storage: Staking CounterForNominators (r:1 w:1) // Storage: Staking MinNominatorBond (r:1 w:0) @@ -437,10 +440,17 @@ impl WeightInfo for SubstrateWeight { // Storage: BagsList ListBags (r:1 w:1) // Storage: BagsList CounterForListNodes (r:1 w:1) fn chill_other() -> Weight { - (78_282_000 as Weight) + (55_459_000 as Weight) .saturating_add(T::DbWeight::get().reads(11 as Weight)) .saturating_add(T::DbWeight::get().writes(6 as Weight)) } + // Storage: Staking MinCommission (r:1 w:0) + // Storage: Staking Validators (r:1 w:1) + fn force_apply_min_commission() -> Weight { + (8_939_000 as Weight) + .saturating_add(T::DbWeight::get().reads(2 as Weight)) + .saturating_add(T::DbWeight::get().writes(1 as Weight)) + } } // For backwards compatibility and tests @@ -452,7 +462,7 @@ impl WeightInfo for () { // Storage: Balances Locks (r:1 w:1) // Storage: Staking Payee (r:0 w:1) fn bond() -> Weight { - (63_660_000 as Weight) + (37_772_000 as Weight) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } @@ -462,7 +472,7 @@ impl WeightInfo for () { // Storage: BagsList ListNodes (r:3 w:3) // Storage: BagsList ListBags (r:2 w:2) fn bond_extra() -> Weight { - (103_672_000 as Weight) + (64_816_000 as Weight) .saturating_add(RocksDbWeight::get().reads(8 as Weight)) .saturating_add(RocksDbWeight::get().writes(7 as Weight)) } @@ -476,7 +486,7 @@ impl WeightInfo for () { // Storage: Staking Bonded (r:1 w:0) // Storage: BagsList ListBags (r:2 w:2) fn unbond() -> Weight { - (110_884_000 as Weight) + (71_635_000 as Weight) .saturating_add(RocksDbWeight::get().reads(12 as Weight)) .saturating_add(RocksDbWeight::get().writes(8 as Weight)) } @@ -485,9 +495,9 @@ impl WeightInfo for () { // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) fn withdraw_unbonded_update(s: u32, ) -> Weight { - (46_379_000 as Weight) + (30_612_000 as Weight) // Standard Error: 0 - .saturating_add((55_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((59_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } @@ -505,7 +515,7 @@ impl WeightInfo for () { // Storage: Balances Locks (r:1 w:1) // Storage: Staking Payee (r:0 w:1) fn withdraw_unbonded_kill(_s: u32, ) -> Weight { - (91_303_000 as Weight) + (59_116_000 as Weight) .saturating_add(RocksDbWeight::get().reads(13 as Weight)) .saturating_add(RocksDbWeight::get().writes(11 as Weight)) } @@ -521,16 +531,16 @@ impl WeightInfo for () { // Storage: BagsList CounterForListNodes (r:1 w:1) // Storage: Staking CounterForValidators (r:1 w:1) fn validate() -> Weight { - (66_587_000 as Weight) + (45_505_000 as Weight) .saturating_add(RocksDbWeight::get().reads(12 as Weight)) .saturating_add(RocksDbWeight::get().writes(8 as Weight)) } // Storage: Staking Ledger (r:1 w:0) // Storage: Staking Nominators (r:1 w:1) fn kick(k: u32, ) -> Weight { - (21_153_000 as Weight) - // Standard Error: 16_000 - .saturating_add((13_502_000 as Weight).saturating_mul(k as Weight)) + (12_764_000 as Weight) + // Standard Error: 15_000 + .saturating_add((8_301_000 as Weight).saturating_mul(k as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(k as Weight))) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(k as Weight))) @@ -541,15 +551,15 @@ impl WeightInfo for () { // Storage: Staking MaxNominatorsCount (r:1 w:0) // Storage: Staking Validators (r:2 w:0) // Storage: Staking CurrentEra (r:1 w:0) - // Storage: Staking CounterForNominators (r:1 w:1) // Storage: Staking Bonded (r:1 w:0) // Storage: BagsList ListNodes (r:2 w:2) // Storage: BagsList ListBags (r:1 w:1) // Storage: BagsList CounterForListNodes (r:1 w:1) + // Storage: Staking CounterForNominators (r:1 w:1) fn nominate(n: u32, ) -> Weight { - (75_456_000 as Weight) - // Standard Error: 12_000 - .saturating_add((5_051_000 as Weight).saturating_mul(n as Weight)) + (51_439_000 as Weight) + // Standard Error: 10_000 + .saturating_add((3_323_000 as Weight).saturating_mul(n as Weight)) .saturating_add(RocksDbWeight::get().reads(12 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(n as Weight))) .saturating_add(RocksDbWeight::get().writes(6 as Weight)) @@ -562,49 +572,49 @@ impl WeightInfo for () { // Storage: BagsList ListBags (r:1 w:1) // Storage: BagsList CounterForListNodes (r:1 w:1) fn chill() -> Weight { - (65_332_000 as Weight) + (44_847_000 as Weight) .saturating_add(RocksDbWeight::get().reads(8 as Weight)) .saturating_add(RocksDbWeight::get().writes(6 as Weight)) } // Storage: Staking Ledger (r:1 w:0) // Storage: Staking Payee (r:0 w:1) fn set_payee() -> Weight { - (11_757_000 as Weight) + (7_795_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Staking Bonded (r:1 w:1) // Storage: Staking Ledger (r:2 w:2) fn set_controller() -> Weight { - (24_252_000 as Weight) + (16_051_000 as Weight) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } // Storage: Staking ValidatorCount (r:0 w:1) fn set_validator_count() -> Weight { - (2_252_000 as Weight) + (1_107_000 as Weight) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Staking ForceEra (r:0 w:1) fn force_no_eras() -> Weight { - (2_431_000 as Weight) + (1_126_000 as Weight) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Staking ForceEra (r:0 w:1) fn force_new_era() -> Weight { - (2_397_000 as Weight) + (1_183_000 as Weight) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Staking ForceEra (r:0 w:1) fn force_new_era_always() -> Weight { - (2_423_000 as Weight) + (1_181_000 as Weight) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Staking Invulnerables (r:0 w:1) fn set_invulnerables(v: u32, ) -> Weight { - (2_876_000 as Weight) + (1_705_000 as Weight) // Standard Error: 0 - .saturating_add((53_000 as Weight).saturating_mul(v as Weight)) + .saturating_add((50_000 as Weight).saturating_mul(v as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Staking Bonded (r:1 w:1) @@ -621,18 +631,18 @@ impl WeightInfo for () { // Storage: Staking Payee (r:0 w:1) // Storage: Staking SpanSlash (r:0 w:2) fn force_unstake(s: u32, ) -> Weight { - (87_540_000 as Weight) + (57_431_000 as Weight) // Standard Error: 1_000 - .saturating_add((1_791_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((801_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(11 as Weight)) .saturating_add(RocksDbWeight::get().writes(12 as Weight)) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) } // Storage: Staking UnappliedSlashes (r:1 w:1) fn cancel_deferred_slash(s: u32, ) -> Weight { - (2_769_801_000 as Weight) - // Standard Error: 181_000 - .saturating_add((16_225_000 as Weight).saturating_mul(s as Weight)) + (950_258_000 as Weight) + // Standard Error: 56_000 + .saturating_add((5_001_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -647,9 +657,9 @@ impl WeightInfo for () { // Storage: Staking Payee (r:2 w:0) // Storage: System Account (r:2 w:2) fn payout_stakers_dead_controller(n: u32, ) -> Weight { - (103_452_000 as Weight) - // Standard Error: 19_000 - .saturating_add((42_909_000 as Weight).saturating_mul(n as Weight)) + (94_238_000 as Weight) + // Standard Error: 15_000 + .saturating_add((23_978_000 as Weight).saturating_mul(n as Weight)) .saturating_add(RocksDbWeight::get().reads(10 as Weight)) .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(n as Weight))) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) @@ -667,9 +677,9 @@ impl WeightInfo for () { // Storage: System Account (r:2 w:2) // Storage: Balances Locks (r:2 w:2) fn payout_stakers_alive_staked(n: u32, ) -> Weight { - (145_995_000 as Weight) - // Standard Error: 27_000 - .saturating_add((55_974_000 as Weight).saturating_mul(n as Weight)) + (109_323_000 as Weight) + // Standard Error: 22_000 + .saturating_add((33_887_000 as Weight).saturating_mul(n as Weight)) .saturating_add(RocksDbWeight::get().reads(11 as Weight)) .saturating_add(RocksDbWeight::get().reads((5 as Weight).saturating_mul(n as Weight))) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) @@ -682,9 +692,9 @@ impl WeightInfo for () { // Storage: Staking Bonded (r:1 w:0) // Storage: BagsList ListBags (r:2 w:2) fn rebond(l: u32, ) -> Weight { - (101_568_000 as Weight) + (64_807_000 as Weight) // Standard Error: 2_000 - .saturating_add((66_000 as Weight).saturating_mul(l as Weight)) + .saturating_add((50_000 as Weight).saturating_mul(l as Weight)) .saturating_add(RocksDbWeight::get().reads(9 as Weight)) .saturating_add(RocksDbWeight::get().writes(8 as Weight)) } @@ -699,8 +709,8 @@ impl WeightInfo for () { // Storage: Staking ErasStartSessionIndex (r:0 w:1) fn set_history_depth(e: u32, ) -> Weight { (0 as Weight) - // Standard Error: 69_000 - .saturating_add((29_939_000 as Weight).saturating_mul(e as Weight)) + // Standard Error: 61_000 + .saturating_add((20_457_000 as Weight).saturating_mul(e as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) .saturating_add(RocksDbWeight::get().writes((7 as Weight).saturating_mul(e as Weight))) @@ -719,9 +729,9 @@ impl WeightInfo for () { // Storage: Staking Payee (r:0 w:1) // Storage: Staking SpanSlash (r:0 w:1) fn reap_stash(s: u32, ) -> Weight { - (96_886_000 as Weight) - // Standard Error: 1_000 - .saturating_add((1_790_000 as Weight).saturating_mul(s as Weight)) + (62_856_000 as Weight) + // Standard Error: 0 + .saturating_add((802_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(12 as Weight)) .saturating_add(RocksDbWeight::get().writes(12 as Weight)) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) @@ -746,10 +756,10 @@ impl WeightInfo for () { // Storage: Staking ErasStartSessionIndex (r:0 w:1) fn new_era(v: u32, n: u32, ) -> Weight { (0 as Weight) - // Standard Error: 873_000 - .saturating_add((286_141_000 as Weight).saturating_mul(v as Weight)) - // Standard Error: 43_000 - .saturating_add((44_712_000 as Weight).saturating_mul(n as Weight)) + // Standard Error: 804_000 + .saturating_add((226_855_000 as Weight).saturating_mul(v as Weight)) + // Standard Error: 40_000 + .saturating_add((31_928_000 as Weight).saturating_mul(n as Weight)) .saturating_add(RocksDbWeight::get().reads(208 as Weight)) .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(v as Weight))) .saturating_add(RocksDbWeight::get().reads((4 as Weight).saturating_mul(n as Weight))) @@ -768,9 +778,11 @@ impl WeightInfo for () { fn get_npos_voters(v: u32, n: u32, s: u32, ) -> Weight { (0 as Weight) // Standard Error: 87_000 - .saturating_add((24_049_000 as Weight).saturating_mul(v as Weight)) + .saturating_add((18_771_000 as Weight).saturating_mul(v as Weight)) // Standard Error: 87_000 - .saturating_add((27_514_000 as Weight).saturating_mul(n as Weight)) + .saturating_add((21_895_000 as Weight).saturating_mul(n as Weight)) + // Standard Error: 2_984_000 + .saturating_add((8_282_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(204 as Weight)) .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(v as Weight))) .saturating_add(RocksDbWeight::get().reads((4 as Weight).saturating_mul(n as Weight))) @@ -779,8 +791,8 @@ impl WeightInfo for () { // Storage: Staking Validators (r:501 w:0) fn get_npos_targets(v: u32, ) -> Weight { (0 as Weight) - // Standard Error: 32_000 - .saturating_add((10_128_000 as Weight).saturating_mul(v as Weight)) + // Standard Error: 28_000 + .saturating_add((7_801_000 as Weight).saturating_mul(v as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(v as Weight))) } @@ -791,12 +803,12 @@ impl WeightInfo for () { // Storage: Staking MaxNominatorsCount (r:0 w:1) // Storage: Staking MinNominatorBond (r:0 w:1) fn set_staking_configs() -> Weight { - (6_187_000 as Weight) + (3_680_000 as Weight) .saturating_add(RocksDbWeight::get().writes(6 as Weight)) } // Storage: Staking Ledger (r:1 w:0) - // Storage: Staking ChillThreshold (r:1 w:0) // Storage: Staking Nominators (r:1 w:1) + // Storage: Staking ChillThreshold (r:1 w:0) // Storage: Staking MaxNominatorsCount (r:1 w:0) // Storage: Staking CounterForNominators (r:1 w:1) // Storage: Staking MinNominatorBond (r:1 w:0) @@ -805,8 +817,15 @@ impl WeightInfo for () { // Storage: BagsList ListBags (r:1 w:1) // Storage: BagsList CounterForListNodes (r:1 w:1) fn chill_other() -> Weight { - (78_282_000 as Weight) + (55_459_000 as Weight) .saturating_add(RocksDbWeight::get().reads(11 as Weight)) .saturating_add(RocksDbWeight::get().writes(6 as Weight)) } + // Storage: Staking MinCommission (r:1 w:0) + // Storage: Staking Validators (r:1 w:1) + fn force_apply_min_commission() -> Weight { + (8_939_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(2 as Weight)) + .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + } } diff --git a/frame/sudo/Cargo.toml b/frame/sudo/Cargo.toml index 504eb37b8d009..063ea52d5b8b5 100644 --- a/frame/sudo/Cargo.toml +++ b/frame/sudo/Cargo.toml @@ -16,13 +16,13 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } [features] default = ["std"] diff --git a/frame/support/Cargo.toml b/frame/support/Cargo.toml index d652e5ea43445..a5ba2fad18b3f 100644 --- a/frame/support/Cargo.toml +++ b/frame/support/Cargo.toml @@ -13,15 +13,15 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -serde = { version = "1.0.132", optional = true, features = ["derive"] } +serde = { version = "1.0.136", optional = true, features = ["derive"] } codec = { package = "parity-scale-codec", version = "2.2.0", default-features = false, features = ["derive", "max-encoded-len"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } frame-metadata = { version = "14.2.0", default-features = false, features = ["v14"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-tracing = { version = "4.0.0", default-features = false, path = "../../primitives/tracing" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } sp-arithmetic = { version = "4.0.0", default-features = false, path = "../../primitives/arithmetic" } sp-inherents = { version = "4.0.0-dev", default-features = false, path = "../../primitives/inherents" } sp-staking = { version = "4.0.0-dev", default-features = false, path = "../../primitives/staking" } @@ -29,7 +29,7 @@ tt-call = "1.0.8" frame-support-procedural = { version = "4.0.0-dev", default-features = false, path = "./procedural" } paste = "1.0" once_cell = { version = "1", default-features = false, optional = true } -sp-state-machine = { version = "0.10.0", optional = true, path = "../../primitives/state-machine" } +sp-state-machine = { version = "0.11.0", optional = true, path = "../../primitives/state-machine" } bitflags = "1.3" impl-trait-for-tuples = "0.2.1" smallvec = "1.7.0" diff --git a/frame/support/procedural/src/pallet/expand/error.rs b/frame/support/procedural/src/pallet/expand/error.rs index 4cf572c1797f2..9e2b801083e46 100644 --- a/frame/support/procedural/src/pallet/expand/error.rs +++ b/frame/support/procedural/src/pallet/expand/error.rs @@ -124,11 +124,11 @@ pub fn expand_error(def: &mut Def) -> proc_macro2::TokenStream { >::index::>() .expect("Every active module has an index in the runtime; qed") as u8; - #frame_support::sp_runtime::DispatchError::Module { + #frame_support::sp_runtime::DispatchError::Module(#frame_support::sp_runtime::ModuleError { index, error: err.as_u8(), message: Some(err.as_str()), - } + }) } } ) diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index b5f4ab97767c2..ece5173f2f4ca 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -20,6 +20,7 @@ pub use crate::{ codec::{Codec, Decode, Encode, EncodeAsRef, EncodeLike, HasCompact, Input, Output}, + scale_info::TypeInfo, sp_std::{ fmt, marker, prelude::{Clone, Eq, PartialEq, Vec}, @@ -33,7 +34,7 @@ pub use crate::{ TransactionPriority, WeighData, Weight, WithPostDispatchInfo, }, }; -pub use sp_runtime::{traits::Dispatchable, DispatchError}; +pub use sp_runtime::{traits::Dispatchable, DispatchError, RuntimeDebug}; /// The return type of a `Dispatchable` in frame. When returned explicitly from /// a dispatchable function it allows overriding the default `PostDispatchInfo` @@ -60,6 +61,28 @@ pub trait Callable { // https://github.com/rust-lang/rust/issues/51331 pub type CallableCallFor = >::Call; +/// Origin for the System pallet. +#[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode, TypeInfo)] +pub enum RawOrigin { + /// The system itself ordained this dispatch to happen: this is the highest privilege level. + Root, + /// It is signed by some public key and we provide the `AccountId`. + Signed(AccountId), + /// It is signed by nobody, can be either: + /// * included and agreed upon by the validators anyway, + /// * or unsigned transaction validated by a pallet. + None, +} + +impl From> for RawOrigin { + fn from(s: Option) -> RawOrigin { + match s { + Some(who) => RawOrigin::Signed(who), + None => RawOrigin::None, + } + } +} + /// A type that can be used as a parameter in a dispatchable function. /// /// When using `decl_module` all arguments for call functions must implement this trait. @@ -2582,21 +2605,7 @@ mod tests { type DbWeight: Get; } - #[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, scale_info::TypeInfo)] - pub enum RawOrigin { - Root, - Signed(AccountId), - None, - } - - impl From> for RawOrigin { - fn from(s: Option) -> RawOrigin { - match s { - Some(who) => RawOrigin::Signed(who), - None => RawOrigin::None, - } - } - } + pub use super::super::RawOrigin; pub type Origin = RawOrigin<::AccountId>; } @@ -2638,7 +2647,7 @@ mod tests { } } - #[derive(scale_info::TypeInfo)] + #[derive(Eq, PartialEq, Clone, crate::RuntimeDebug, scale_info::TypeInfo)] pub struct TraitImpl {} impl Config for TraitImpl {} @@ -2679,8 +2688,15 @@ mod tests { } } + #[derive(TypeInfo, crate::RuntimeDebug, Eq, PartialEq, Clone, Encode, Decode)] pub struct OuterOrigin; + impl From::AccountId>> for OuterOrigin { + fn from(_: RawOrigin<::AccountId>) -> Self { + unimplemented!("Not required in tests!") + } + } + impl crate::traits::OriginTrait for OuterOrigin { type Call = ::Call; type PalletsOrigin = OuterOrigin; diff --git a/frame/support/src/error.rs b/frame/support/src/error.rs index abac4a53269a6..4880bba5c5e97 100644 --- a/frame/support/src/error.rs +++ b/frame/support/src/error.rs @@ -153,11 +153,11 @@ macro_rules! decl_error { ::index::<$module<$generic $(, $inst_generic)?>>() .expect("Every active module has an index in the runtime; qed") as u8; - $crate::sp_runtime::DispatchError::Module { + $crate::sp_runtime::DispatchError::Module($crate::sp_runtime::ModuleError { index, error: err.as_u8(), message: Some(err.as_str()), - } + }) } } }; diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index be5706e87aaec..ef60729f6d861 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -114,6 +114,29 @@ impl TypeId for PalletId { const TYPE_ID: [u8; 4] = *b"modl"; } +/// Build a bounded vec from the given literals. +/// +/// The type of the outcome must be known. +/// +/// Will not handle any errors and just panic if the given literals cannot fit in the corresponding +/// bounded vec type. Thus, this is only suitable for testing and non-consensus code. +#[macro_export] +#[cfg(feature = "std")] +macro_rules! bounded_vec { + ($ ($values:expr),* ) => { + { + use $crate::sp_std::convert::TryInto as _; + $crate::sp_std::vec![$($values),*].try_into().unwrap() + } + }; + ( $value:expr ; $repetition:expr ) => { + { + use $crate::sp_std::convert::TryInto as _; + $crate::sp_std::vec![$value ; $repetition].try_into().unwrap() + } + } +} + /// Generate a new type alias for [`storage::types::StorageValue`], /// [`storage::types::StorageMap`], [`storage::types::StorageDoubleMap`] /// and [`storage::types::StorageNMap`]. @@ -751,9 +774,9 @@ macro_rules! assert_noop { $x:expr, $y:expr $(,)? ) => { - let h = $crate::storage_root(); + let h = $crate::storage_root($crate::StateVersion::V1); $crate::assert_err!($x, $y); - assert_eq!(h, $crate::storage_root()); + assert_eq!(h, $crate::storage_root($crate::StateVersion::V1)); }; } @@ -766,9 +789,9 @@ macro_rules! assert_storage_noop { ( $x:expr ) => { - let h = $crate::storage_root(); + let h = $crate::storage_root($crate::StateVersion::V1); $x; - assert_eq!(h, $crate::storage_root()); + assert_eq!(h, $crate::storage_root($crate::StateVersion::V1)); }; } diff --git a/frame/support/src/storage/bounded_vec.rs b/frame/support/src/storage/bounded_vec.rs index 6d7206df6db10..9298a5d98b003 100644 --- a/frame/support/src/storage/bounded_vec.rs +++ b/frame/support/src/storage/bounded_vec.rs @@ -222,16 +222,17 @@ impl> BoundedVec { /// Returns `true` if the item was inserted. pub fn force_insert_keep_left(&mut self, index: usize, element: T) -> bool { // Check against panics. - if Self::bound() < index || self.len() < index { + if Self::bound() < index || self.len() < index || Self::bound() == 0 { return false } // Noop condition. if Self::bound() == index && self.len() <= Self::bound() { return false } - // Cannot panic since self.len() >= index; + // Cannot panic since `Self.bound() > 0` + self.0.truncate(Self::bound() - 1); + // Cannot panic since `self.len() >= index`; self.0.insert(index, element); - self.0.truncate(Self::bound()); true } @@ -663,6 +664,19 @@ pub mod test { assert_eq!(*bounded, vec![1, 0, 2, 3]); } + #[test] + fn constructor_macro_works() { + use frame_support::bounded_vec; + + // With values. Use some brackets to make sure the macro doesn't expand. + let bv: BoundedVec<(u32, u32), ConstU32<3>> = bounded_vec![(1, 2), (1, 2), (1, 2)]; + assert_eq!(bv, vec![(1, 2), (1, 2), (1, 2)]); + + // With repetition. + let bv: BoundedVec<(u32, u32), ConstU32<3>> = bounded_vec![(1, 2); 3]; + assert_eq!(bv, vec![(1, 2), (1, 2), (1, 2)]); + } + #[test] #[should_panic(expected = "insertion index (is 9) should be <= len (is 3)")] fn try_inert_panics_if_oob() { diff --git a/frame/support/src/storage/child.rs b/frame/support/src/storage/child.rs index 7a09be7d3250d..949df84e7e768 100644 --- a/frame/support/src/storage/child.rs +++ b/frame/support/src/storage/child.rs @@ -168,9 +168,10 @@ pub fn put_raw(child_info: &ChildInfo, key: &[u8], value: &[u8]) { } /// Calculate current child root value. -pub fn root(child_info: &ChildInfo, _: StateVersion) -> Vec { +pub fn root(child_info: &ChildInfo, version: StateVersion) -> Vec { match child_info.child_type() { - ChildType::ParentKeyId => sp_io::default_child_storage::root(child_info.storage_key()), + ChildType::ParentKeyId => + sp_io::default_child_storage::root(child_info.storage_key(), version), } } diff --git a/frame/support/src/storage/mod.rs b/frame/support/src/storage/mod.rs index e50577697a60a..3d777fa3ace50 100644 --- a/frame/support/src/storage/mod.rs +++ b/frame/support/src/storage/mod.rs @@ -266,6 +266,8 @@ pub trait StorageMap { ) -> R; /// Mutate the item, only if an `Ok` value is returned. Deletes the item if mutated to a `None`. + /// `f` will always be called with an option representing if the storage item exists (`Some`) + /// or if the storage item does not exist (`None`), independent of the `QueryType`. fn try_mutate_exists, R, E, F: FnOnce(&mut Option) -> Result>( key: KeyArg, f: F, @@ -608,6 +610,8 @@ pub trait StorageDoubleMap { F: FnOnce(&mut Option) -> R; /// Mutate the item, only if an `Ok` value is returned. Deletes the item if mutated to a `None`. + /// `f` will always be called with an option representing if the storage item exists (`Some`) + /// or if the storage item does not exist (`None`), independent of the `QueryType`. fn try_mutate_exists(k1: KArg1, k2: KArg2, f: F) -> Result where KArg1: EncodeLike, @@ -735,6 +739,8 @@ pub trait StorageNMap { F: FnOnce(&mut Option) -> R; /// Mutate the item, only if an `Ok` value is returned. Deletes the item if mutated to a `None`. + /// `f` will always be called with an option representing if the storage item exists (`Some`) + /// or if the storage item does not exist (`None`), independent of the `QueryType`. fn try_mutate_exists(key: KArg, f: F) -> Result where KArg: EncodeLikeTuple + TupleToEncodedIter, diff --git a/frame/support/src/storage/types/counted_map.rs b/frame/support/src/storage/types/counted_map.rs index 0f98b13282a74..9c48267af86e0 100644 --- a/frame/support/src/storage/types/counted_map.rs +++ b/frame/support/src/storage/types/counted_map.rs @@ -190,6 +190,8 @@ where } /// Mutate the item, only if an `Ok` value is returned. Deletes the item if mutated to a `None`. + /// `f` will always be called with an option representing if the storage item exists (`Some`) + /// or if the storage item does not exist (`None`), independent of the `QueryType`. pub fn try_mutate_exists(key: KeyArg, f: F) -> Result where KeyArg: EncodeLike + Clone, @@ -401,6 +403,13 @@ where ) -> crate::storage::PrefixIterator<(Key, Value), OnRemovalCounterUpdate> { ::Map::iter_from(starting_raw_key).convert_on_removal() } + + /// Enumerate all keys in the counted map. + /// + /// If you alter the map while doing this, you'll get undefined results. + pub fn iter_keys() -> crate::storage::KeyPrefixIterator { + ::Map::iter_keys() + } } impl StorageEntryMetadataBuilder diff --git a/frame/support/src/storage/types/double_map.rs b/frame/support/src/storage/types/double_map.rs index 07da0f2239b3b..e864920e488f0 100644 --- a/frame/support/src/storage/types/double_map.rs +++ b/frame/support/src/storage/types/double_map.rs @@ -264,6 +264,8 @@ where } /// Mutate the item, only if an `Ok` value is returned. Deletes the item if mutated to a `None`. + /// `f` will always be called with an option representing if the storage item exists (`Some`) + /// or if the storage item does not exist (`None`), independent of the `QueryType`. pub fn try_mutate_exists(k1: KArg1, k2: KArg2, f: F) -> Result where KArg1: EncodeLike, diff --git a/frame/support/src/storage/types/map.rs b/frame/support/src/storage/types/map.rs index d0b82e1a84e5b..01aa2f44abe5e 100644 --- a/frame/support/src/storage/types/map.rs +++ b/frame/support/src/storage/types/map.rs @@ -174,6 +174,8 @@ where } /// Mutate the item, only if an `Ok` value is returned. Deletes the item if mutated to a `None`. + /// `f` will always be called with an option representing if the storage item exists (`Some`) + /// or if the storage item does not exist (`None`), independent of the `QueryType`. pub fn try_mutate_exists(key: KeyArg, f: F) -> Result where KeyArg: EncodeLike, diff --git a/frame/support/src/storage/types/nmap.rs b/frame/support/src/storage/types/nmap.rs index 03f15e335389b..5b51ed1ffdf49 100755 --- a/frame/support/src/storage/types/nmap.rs +++ b/frame/support/src/storage/types/nmap.rs @@ -217,6 +217,8 @@ where } /// Mutate the item, only if an `Ok` value is returned. Deletes the item if mutated to a `None`. + /// `f` will always be called with an option representing if the storage item exists (`Some`) + /// or if the storage item does not exist (`None`), independent of the `QueryType`. pub fn try_mutate_exists(key: KArg, f: F) -> Result where KArg: EncodeLikeTuple + TupleToEncodedIter, diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index 85a0698759b69..5ee2952e445b7 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -23,7 +23,7 @@ pub mod tokens; pub use tokens::{ currency::{ Currency, LockIdentifier, LockableCurrency, NamedReservableCurrency, ReservableCurrency, - VestingSchedule, + TotalIssuanceOf, VestingSchedule, }, fungible, fungibles, imbalance::{Imbalance, OnUnbalanced, SignedImbalance}, @@ -50,12 +50,13 @@ pub use filter::{ClearFilterGuard, FilterStack, FilterStackGuard, InstanceFilter mod misc; pub use misc::{ + defensive_prelude::{self, *}, Backing, ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstU128, ConstU16, - ConstU32, ConstU64, ConstU8, EnsureInherentsAreFirst, EqualPrivilegeOnly, EstimateCallFee, - ExecuteBlock, ExtrinsicCall, Get, GetBacking, GetDefault, HandleLifetime, IsSubType, IsType, - Len, OffchainWorker, OnKilledAccount, OnNewAccount, PreimageProvider, PreimageRecipient, - PrivilegeCmp, SameOrOther, Time, TryCollect, TryDrop, UnixTime, WrapperKeepOpaque, - WrapperOpaque, + ConstU32, ConstU64, ConstU8, DefensiveSaturating, EnsureInherentsAreFirst, EqualPrivilegeOnly, + EstimateCallFee, ExecuteBlock, ExtrinsicCall, Get, GetBacking, GetDefault, HandleLifetime, + IsSubType, IsType, Len, OffchainWorker, OnKilledAccount, OnNewAccount, PreimageProvider, + PreimageRecipient, PrivilegeCmp, SameOrOther, Time, TryCollect, TryDrop, UnixTime, + WrapperKeepOpaque, WrapperOpaque, }; mod stored_map; @@ -89,4 +90,6 @@ mod dispatch; pub use dispatch::{EnsureOneOf, EnsureOrigin, OriginTrait, UnfilteredDispatchable}; mod voting; -pub use voting::{CurrencyToVote, SaturatingCurrencyToVote, U128CurrencyToVote}; +pub use voting::{ + CurrencyToVote, PollStatus, Polling, SaturatingCurrencyToVote, U128CurrencyToVote, VoteTally, +}; diff --git a/frame/support/src/traits/dispatch.rs b/frame/support/src/traits/dispatch.rs index afac31e662e3f..1a4e9f6f7cc2a 100644 --- a/frame/support/src/traits/dispatch.rs +++ b/frame/support/src/traits/dispatch.rs @@ -17,8 +17,11 @@ //! Traits for dealing with dispatching calls and the origin from which they are dispatched. -use crate::dispatch::DispatchResultWithPostInfo; -use sp_runtime::{traits::BadOrigin, Either}; +use crate::dispatch::{DispatchResultWithPostInfo, Parameter, RawOrigin}; +use sp_runtime::{ + traits::{BadOrigin, Member}, + Either, +}; /// Some sort of check on the origin is performed by this object. pub trait EnsureOrigin { @@ -56,7 +59,7 @@ pub trait OriginTrait: Sized { type Call; /// The caller origin, overarching type of all pallets origins. - type PalletsOrigin; + type PalletsOrigin: Parameter + Member + Into + From>; /// The AccountId used across the system. type AccountId; diff --git a/frame/support/src/traits/misc.rs b/frame/support/src/traits/misc.rs index df21624c3cea0..eaada3ea2c363 100644 --- a/frame/support/src/traits/misc.rs +++ b/frame/support/src/traits/misc.rs @@ -20,9 +20,363 @@ use crate::dispatch::Parameter; use codec::{CompactLen, Decode, DecodeAll, Encode, EncodeLike, Input, MaxEncodedLen}; use scale_info::{build::Fields, meta_type, Path, Type, TypeInfo, TypeParameter}; +use sp_arithmetic::traits::{CheckedAdd, CheckedMul, CheckedSub, Saturating}; use sp_runtime::{traits::Block as BlockT, DispatchError}; use sp_std::{cmp::Ordering, prelude::*}; +const DEFENSIVE_OP_PUBLIC_ERROR: &'static str = "a defensive failure has been triggered; please report the block number at https://github.com/paritytech/substrate/issues"; +const DEFENSIVE_OP_INTERNAL_ERROR: &'static str = "Defensive failure has been triggered!"; + +/// Prelude module for all defensive traits to be imported at once. +pub mod defensive_prelude { + pub use super::{Defensive, DefensiveOption, DefensiveResult}; +} + +/// A trait to handle errors and options when you are really sure that a condition must hold, but +/// not brave enough to `expect` on it, or a default fallback value makes more sense. +/// +/// This trait mostly focuses on methods that eventually unwrap the inner value. See +/// [`DefensiveResult`] and [`DefensiveOption`] for methods that specifically apply to the +/// respective types. +/// +/// Each function in this trait will have two side effects, aside from behaving exactly as the name +/// would suggest: +/// +/// 1. It panics on `#[debug_assertions]`, so if the infallible code is reached in any of the tests, +/// you realize. +/// 2. It will log an error using the runtime logging system. This might help you detect such bugs +/// in production as well. Note that the log message, as of now, are not super expressive. Your +/// best shot of fully diagnosing the error would be to infer the block number of which the log +/// message was emitted, then re-execute that block using `check-block` or `try-runtime` +/// subcommands in substrate client. +pub trait Defensive { + /// Exactly the same as `unwrap_or`, but it does the defensive warnings explained in the trait + /// docs. + fn defensive_unwrap_or(self, other: T) -> T; + + /// Exactly the same as `unwrap_or_else`, but it does the defensive warnings explained in the + /// trait docs. + fn defensive_unwrap_or_else T>(self, f: F) -> T; + + /// Exactly the same as `unwrap_or_default`, but it does the defensive warnings explained in the + /// trait docs. + fn defensive_unwrap_or_default(self) -> T + where + T: Default; + + /// Does not alter the inner value at all, but it will log warnings if the inner value is `None` + /// or `Err`. + /// + /// In some ways, this is like `.defensive_map(|x| x)`. + /// + /// This is useful as: + /// ```nocompile + /// if let Some(inner) = maybe_value().defensive() { + /// .. + /// } + /// ``` + fn defensive(self) -> Self; +} + +/// Subset of methods similar to [`Defensive`] that can only work for a `Result`. +pub trait DefensiveResult { + /// Defensively map the error into another return type, but you are really sure that this + /// conversion should never be needed. + fn defensive_map_err F>(self, o: O) -> Result; + + /// Defensively map and unpack the value to something else (`U`), or call the default callback + /// if `Err`, which should never happen. + fn defensive_map_or_else U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U; + + /// Defensively transform this result into an option, discarding the `Err` variant if it + /// happens, which should never happen. + fn defensive_ok(self) -> Option; + + /// Exactly the same as `map`, but it prints the appropriate warnings if the value being mapped + /// is `Err`. + fn defensive_map U>(self, f: F) -> Result; +} + +/// Subset of methods similar to [`Defensive`] that can only work for a `Option`. +pub trait DefensiveOption { + /// Potentially map and unpack the value to something else (`U`), or call the default callback + /// if `None`, which should never happen. + fn defensive_map_or_else U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U; + + /// Defensively transform this option to a result. + fn defensive_ok_or_else E>(self, err: F) -> Result; + + /// Exactly the same as `map`, but it prints the appropriate warnings if the value being mapped + /// is `None`. + fn defensive_map U>(self, f: F) -> Option; +} + +impl Defensive for Option { + fn defensive_unwrap_or(self, or: T) -> T { + match self { + Some(inner) => inner, + None => { + debug_assert!(false, "{}", DEFENSIVE_OP_INTERNAL_ERROR); + frame_support::log::error!( + target: "runtime", + "{}", + DEFENSIVE_OP_PUBLIC_ERROR + ); + or + }, + } + } + + fn defensive_unwrap_or_else T>(self, f: F) -> T { + match self { + Some(inner) => inner, + None => { + debug_assert!(false, "{}", DEFENSIVE_OP_INTERNAL_ERROR); + frame_support::log::error!( + target: "runtime", + "{}", + DEFENSIVE_OP_PUBLIC_ERROR + ); + f() + }, + } + } + + fn defensive_unwrap_or_default(self) -> T + where + T: Default, + { + match self { + Some(inner) => inner, + None => { + debug_assert!(false, "{}", DEFENSIVE_OP_INTERNAL_ERROR); + frame_support::log::error!( + target: "runtime", + "{}", + DEFENSIVE_OP_PUBLIC_ERROR + ); + Default::default() + }, + } + } + + fn defensive(self) -> Self { + match self { + Some(inner) => Some(inner), + None => { + debug_assert!(false, "{}", DEFENSIVE_OP_INTERNAL_ERROR); + frame_support::log::error!( + target: "runtime", + "{}", + DEFENSIVE_OP_PUBLIC_ERROR + ); + None + }, + } + } +} + +impl Defensive for Result { + fn defensive_unwrap_or(self, or: T) -> T { + match self { + Ok(inner) => inner, + Err(e) => { + debug_assert!(false, "{}: {:?}", DEFENSIVE_OP_INTERNAL_ERROR, e); + frame_support::log::error!( + target: "runtime", + "{}: {:?}", + DEFENSIVE_OP_PUBLIC_ERROR, + e + ); + or + }, + } + } + + fn defensive_unwrap_or_else T>(self, f: F) -> T { + match self { + Ok(inner) => inner, + Err(e) => { + debug_assert!(false, "{}: {:?}", DEFENSIVE_OP_INTERNAL_ERROR, e); + frame_support::log::error!( + target: "runtime", + "{}: {:?}", + DEFENSIVE_OP_PUBLIC_ERROR, + e + ); + f() + }, + } + } + + fn defensive_unwrap_or_default(self) -> T + where + T: Default, + { + match self { + Ok(inner) => inner, + Err(e) => { + debug_assert!(false, "{}: {:?}", DEFENSIVE_OP_INTERNAL_ERROR, e); + frame_support::log::error!( + target: "runtime", + "{}: {:?}", + DEFENSIVE_OP_PUBLIC_ERROR, + e + ); + Default::default() + }, + } + } + + fn defensive(self) -> Self { + match self { + Ok(inner) => Ok(inner), + Err(e) => { + debug_assert!(false, "{}: {:?}", DEFENSIVE_OP_INTERNAL_ERROR, e); + frame_support::log::error!( + target: "runtime", + "{}: {:?}", + DEFENSIVE_OP_PUBLIC_ERROR, + e + ); + Err(e) + }, + } + } +} + +impl DefensiveResult for Result { + fn defensive_map_err F>(self, o: O) -> Result { + self.map_err(|e| { + debug_assert!(false, "{}: {:?}", DEFENSIVE_OP_INTERNAL_ERROR, e); + frame_support::log::error!( + target: "runtime", + "{}: {:?}", + DEFENSIVE_OP_PUBLIC_ERROR, + e + ); + o(e) + }) + } + + fn defensive_map_or_else U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { + self.map_or_else( + |e| { + debug_assert!(false, "{}: {:?}", DEFENSIVE_OP_INTERNAL_ERROR, e); + frame_support::log::error!( + target: "runtime", + "{}: {:?}", + DEFENSIVE_OP_PUBLIC_ERROR, + e + ); + default(e) + }, + f, + ) + } + + fn defensive_ok(self) -> Option { + match self { + Ok(inner) => Some(inner), + Err(e) => { + debug_assert!(false, "{}: {:?}", DEFENSIVE_OP_INTERNAL_ERROR, e); + frame_support::log::error!( + target: "runtime", + "{}: {:?}", + DEFENSIVE_OP_PUBLIC_ERROR, + e + ); + None + }, + } + } + + fn defensive_map U>(self, f: F) -> Result { + match self { + Ok(inner) => Ok(f(inner)), + Err(e) => { + debug_assert!(false, "{}: {:?}", DEFENSIVE_OP_INTERNAL_ERROR, e); + frame_support::log::error!( + target: "runtime", + "{}: {:?}", + DEFENSIVE_OP_PUBLIC_ERROR, + e + ); + Err(e) + }, + } + } +} + +impl DefensiveOption for Option { + fn defensive_map_or_else U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { + self.map_or_else( + || { + debug_assert!(false, "{}", DEFENSIVE_OP_INTERNAL_ERROR); + frame_support::log::error!( + target: "runtime", + "{}", + DEFENSIVE_OP_PUBLIC_ERROR, + ); + default() + }, + f, + ) + } + + fn defensive_ok_or_else E>(self, err: F) -> Result { + self.ok_or_else(|| { + debug_assert!(false, "{}", DEFENSIVE_OP_INTERNAL_ERROR); + frame_support::log::error!( + target: "runtime", + "{}", + DEFENSIVE_OP_PUBLIC_ERROR, + ); + err() + }) + } + + fn defensive_map U>(self, f: F) -> Option { + match self { + Some(inner) => Some(f(inner)), + None => { + debug_assert!(false, "{}", DEFENSIVE_OP_INTERNAL_ERROR); + frame_support::log::error!( + target: "runtime", + "{}", + DEFENSIVE_OP_PUBLIC_ERROR, + ); + None + }, + } + } +} + +/// A variant of [`Defensive`] with the same rationale, for the arithmetic operations where in +/// case an infallible operation fails, it saturates. +pub trait DefensiveSaturating { + /// Add `self` and `other` defensively. + fn defensive_saturating_add(self, other: Self) -> Self; + /// Subtract `other` from `self` defensively. + fn defensive_saturating_sub(self, other: Self) -> Self; + /// Multiply `self` and `other` defensively. + fn defensive_saturating_mul(self, other: Self) -> Self; +} + +// NOTE: A bit unfortunate, since T has to be bound by all the traits needed. Could make it +// `DefensiveSaturating` to mitigate. +impl DefensiveSaturating for T { + fn defensive_saturating_add(self, other: Self) -> Self { + self.checked_add(&other).defensive_unwrap_or_else(|| self.saturating_add(other)) + } + fn defensive_saturating_sub(self, other: Self) -> Self { + self.checked_sub(&other).defensive_unwrap_or_else(|| self.saturating_sub(other)) + } + fn defensive_saturating_mul(self, other: Self) -> Self { + self.checked_mul(&other).defensive_unwrap_or_else(|| self.saturating_mul(other)) + } +} + /// Try and collect into a collection `C`. pub trait TryCollect { type Error; @@ -72,6 +426,7 @@ impl Get for GetDefault { macro_rules! impl_const_get { ($name:ident, $t:ty) => { + #[derive($crate::RuntimeDebug)] pub struct $name; impl Get<$t> for $name { fn get() -> $t { diff --git a/frame/support/src/traits/schedule.rs b/frame/support/src/traits/schedule.rs index 5ba233c29be1f..3b8e6da3e2ef3 100644 --- a/frame/support/src/traits/schedule.rs +++ b/frame/support/src/traits/schedule.rs @@ -125,7 +125,7 @@ pub mod v1 { /// A type that can be used as a scheduler. pub trait Anon { /// An address which can be used for removing a scheduled task. - type Address: Codec + Clone + Eq + EncodeLike + Debug; + type Address: Codec + Clone + Eq + EncodeLike + Debug + TypeInfo; /// Schedule a dispatch to happen at the beginning of some block in the future. /// @@ -280,7 +280,7 @@ pub mod v2 { /// A type that can be used as a scheduler. pub trait Anon { /// An address which can be used for removing a scheduled task. - type Address: Codec + Clone + Eq + EncodeLike + Debug; + type Address: Codec + Clone + Eq + EncodeLike + Debug + TypeInfo; /// A means of expressing a call by the hash of its encoded data. type Hash; diff --git a/frame/support/src/traits/stored_map.rs b/frame/support/src/traits/stored_map.rs index 5173eaeb5def0..3c3ff2eb0ed98 100644 --- a/frame/support/src/traits/stored_map.rs +++ b/frame/support/src/traits/stored_map.rs @@ -29,7 +29,9 @@ pub trait StoredMap { fn get(k: &K) -> T; /// Maybe mutate the item only if an `Ok` value is returned from `f`. Do nothing if an `Err` is - /// returned. It is removed or reset to default value if it has been mutated to `None` + /// returned. It is removed or reset to default value if it has been mutated to `None`. + /// `f` will always be called with an option representing if the storage item exists (`Some`) + /// or if the storage item does not exist (`None`), independent of the `QueryType`. fn try_mutate_exists>( k: &K, f: impl FnOnce(&mut Option) -> Result, diff --git a/frame/support/src/traits/tokens/currency.rs b/frame/support/src/traits/tokens/currency.rs index d5756ee84c47a..d4b5c0c184f85 100644 --- a/frame/support/src/traits/tokens/currency.rs +++ b/frame/support/src/traits/tokens/currency.rs @@ -21,7 +21,10 @@ use super::{ imbalance::{Imbalance, SignedImbalance}, misc::{Balance, ExistenceRequirement, WithdrawReasons}, }; -use crate::dispatch::{DispatchError, DispatchResult}; +use crate::{ + dispatch::{DispatchError, DispatchResult}, + traits::Get, +}; use codec::MaxEncodedLen; use sp_runtime::traits::MaybeSerializeDeserialize; use sp_std::fmt::Debug; @@ -200,6 +203,15 @@ pub trait Currency { ) -> SignedImbalance; } +/// A non-const `Get` implementation parameterised by a `Currency` impl which provides the result +/// of `total_issuance`. +pub struct TotalIssuanceOf, A>(sp_std::marker::PhantomData<(C, A)>); +impl, A> Get for TotalIssuanceOf { + fn get() -> C::Balance { + C::total_issuance() + } +} + #[cfg(feature = "std")] impl Currency for () { type Balance = u32; diff --git a/frame/support/src/traits/voting.rs b/frame/support/src/traits/voting.rs index 719ad7f0f71d0..978c5ce4f6a01 100644 --- a/frame/support/src/traits/voting.rs +++ b/frame/support/src/traits/voting.rs @@ -18,7 +18,14 @@ //! Traits and associated data structures concerned with voting, and moving between tokens and //! votes. -use sp_arithmetic::traits::{SaturatedConversion, UniqueSaturatedFrom, UniqueSaturatedInto}; +use crate::dispatch::{DispatchError, Parameter}; +use codec::HasCompact; +use sp_arithmetic::{ + traits::{SaturatedConversion, UniqueSaturatedFrom, UniqueSaturatedInto}, + Perbill, +}; +use sp_runtime::traits::Member; +use sp_std::prelude::*; /// A trait similar to `Convert` to convert values from `B` an abstract balance type /// into u64 and back from u128. (This conversion is used in election and other places where complex @@ -87,3 +94,74 @@ impl + UniqueSaturatedFrom> CurrencyToVote B::unique_saturated_from(value) } } + +pub trait VoteTally { + fn ayes(&self) -> Votes; + fn turnout(&self) -> Perbill; + fn approval(&self) -> Perbill; + #[cfg(feature = "runtime-benchmarks")] + fn unanimity() -> Self; + #[cfg(feature = "runtime-benchmarks")] + fn from_requirements(turnout: Perbill, approval: Perbill) -> Self; +} + +pub enum PollStatus { + None, + Ongoing(Tally, Class), + Completed(Moment, bool), +} + +impl PollStatus { + pub fn ensure_ongoing(self) -> Option<(Tally, Class)> { + match self { + Self::Ongoing(t, c) => Some((t, c)), + _ => None, + } + } +} + +pub trait Polling { + type Index: Parameter + Member + Ord + PartialOrd + Copy + HasCompact; + type Votes: Parameter + Member + Ord + PartialOrd + Copy + HasCompact; + type Class: Parameter + Member + Ord + PartialOrd; + type Moment; + + /// Provides a vec of values that `T` may take. + fn classes() -> Vec; + + /// `Some` if the referendum `index` can be voted on, along with the tally and class of + /// referendum. + /// + /// Don't use this if you might mutate - use `try_access_poll` instead. + fn as_ongoing(index: Self::Index) -> Option<(Tally, Self::Class)>; + + fn access_poll( + index: Self::Index, + f: impl FnOnce(PollStatus<&mut Tally, Self::Moment, Self::Class>) -> R, + ) -> R; + + fn try_access_poll( + index: Self::Index, + f: impl FnOnce(PollStatus<&mut Tally, Self::Moment, Self::Class>) -> Result, + ) -> Result; + + /// Create an ongoing majority-carries poll of given class lasting given period for the purpose + /// of benchmarking. + /// + /// May return `Err` if it is impossible. + #[cfg(feature = "runtime-benchmarks")] + fn create_ongoing(class: Self::Class) -> Result; + + /// End the given ongoing poll and return the result. + /// + /// Returns `Err` if `index` is not an ongoing poll. + #[cfg(feature = "runtime-benchmarks")] + fn end_ongoing(index: Self::Index, approved: bool) -> Result<(), ()>; + + /// The maximum amount of ongoing polls within any single class. By default it practically + /// unlimited (`u32::max_value()`). + #[cfg(feature = "runtime-benchmarks")] + fn max_ongoing() -> (Self::Class, u32) { + (Self::classes().into_iter().next().expect("Always one class"), u32::max_value()) + } +} diff --git a/frame/support/test/Cargo.toml b/frame/support/test/Cargo.toml index 257cca3218dab..9f26df4869afc 100644 --- a/frame/support/test/Cargo.toml +++ b/frame/support/test/Cargo.toml @@ -12,15 +12,15 @@ repository = "https://github.com/paritytech/substrate/" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -serde = { version = "1.0.132", default-features = false, features = ["derive"] } +serde = { version = "1.0.136", default-features = false, features = ["derive"] } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-arithmetic = { version = "4.0.0", default-features = false, path = "../../../primitives/arithmetic" } -sp-io = { version = "4.0.0", path = "../../../primitives/io", default-features = false } -sp-state-machine = { version = "0.10.0", optional = true, path = "../../../primitives/state-machine" } +sp-io = { version = "5.0.0", path = "../../../primitives/io", default-features = false } +sp-state-machine = { version = "0.11.0", optional = true, path = "../../../primitives/state-machine" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/core" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../../primitives/core" } sp-std = { version = "4.0.0", default-features = false, path = "../../../primitives/std" } sp-version = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/version" } trybuild = "1.0.53" diff --git a/frame/support/test/compile_pass/Cargo.toml b/frame/support/test/compile_pass/Cargo.toml index 93443e33503ca..aaa080f84f1a4 100644 --- a/frame/support/test/compile_pass/Cargo.toml +++ b/frame/support/test/compile_pass/Cargo.toml @@ -14,8 +14,8 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../../../primitives/core" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../../primitives/runtime" } sp-version = { version = "4.0.0-dev", default-features = false, path = "../../../../primitives/version" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../../" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../../../system" } diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index 267d560edf92d..b3f8feb8aa4b2 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -27,7 +27,7 @@ use sp_core::{sr25519, H256}; use sp_runtime::{ generic, traits::{BlakeTwo256, Verify}, - DispatchError, + DispatchError, ModuleError, }; use sp_std::cell::RefCell; @@ -363,47 +363,47 @@ mod origin_test { fn check_modules_error_type() { assert_eq!( Module1_1::fail(system::Origin::::Root.into()), - Err(DispatchError::Module { index: 31, error: 0, message: Some("Something") }), + Err(DispatchError::Module(ModuleError { index: 31, error: 0, message: Some("Something") })), ); assert_eq!( Module2::fail(system::Origin::::Root.into()), - Err(DispatchError::Module { index: 32, error: 0, message: Some("Something") }), + Err(DispatchError::Module(ModuleError { index: 32, error: 0, message: Some("Something") })), ); assert_eq!( Module1_2::fail(system::Origin::::Root.into()), - Err(DispatchError::Module { index: 33, error: 0, message: Some("Something") }), + Err(DispatchError::Module(ModuleError { index: 33, error: 0, message: Some("Something") })), ); assert_eq!( NestedModule3::fail(system::Origin::::Root.into()), - Err(DispatchError::Module { index: 34, error: 0, message: Some("Something") }), + Err(DispatchError::Module(ModuleError { index: 34, error: 0, message: Some("Something") })), ); assert_eq!( Module1_3::fail(system::Origin::::Root.into()), - Err(DispatchError::Module { index: 6, error: 0, message: Some("Something") }), + Err(DispatchError::Module(ModuleError { index: 6, error: 0, message: Some("Something") })), ); assert_eq!( Module1_4::fail(system::Origin::::Root.into()), - Err(DispatchError::Module { index: 3, error: 0, message: Some("Something") }), + Err(DispatchError::Module(ModuleError { index: 3, error: 0, message: Some("Something") })), ); assert_eq!( Module1_5::fail(system::Origin::::Root.into()), - Err(DispatchError::Module { index: 4, error: 0, message: Some("Something") }), + Err(DispatchError::Module(ModuleError { index: 4, error: 0, message: Some("Something") })), ); assert_eq!( Module1_6::fail(system::Origin::::Root.into()), - Err(DispatchError::Module { index: 1, error: 0, message: Some("Something") }), + Err(DispatchError::Module(ModuleError { index: 1, error: 0, message: Some("Something") })), ); assert_eq!( Module1_7::fail(system::Origin::::Root.into()), - Err(DispatchError::Module { index: 2, error: 0, message: Some("Something") }), + Err(DispatchError::Module(ModuleError { index: 2, error: 0, message: Some("Something") })), ); assert_eq!( Module1_8::fail(system::Origin::::Root.into()), - Err(DispatchError::Module { index: 12, error: 0, message: Some("Something") }), + Err(DispatchError::Module(ModuleError { index: 12, error: 0, message: Some("Something") })), ); assert_eq!( Module1_9::fail(system::Origin::::Root.into()), - Err(DispatchError::Module { index: 13, error: 0, message: Some("Something") }), + Err(DispatchError::Module(ModuleError { index: 13, error: 0, message: Some("Something") })), ); } diff --git a/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.rs b/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.rs index 89774eb8a7702..c06333795e3c5 100644 --- a/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.rs +++ b/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.rs @@ -3,20 +3,47 @@ use sp_runtime::{generic, traits::BlakeTwo256}; use sp_core::sr25519; pub type Signature = sr25519::Signature; -pub type BlockNumber = u64; +pub type BlockNumber = u32; pub type Header = generic::Header; pub type Block = generic::Block; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; impl test_pallet::Config for Runtime {} +impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; + type Origin = Origin; + type Index = u64; + type BlockNumber = u32; + type Call = Call; + type Hash = sp_runtime::testing::H256; + type Hashing = sp_runtime::traits::BlakeTwo256; + type AccountId = u64; + type Lookup = sp_runtime::traits::IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = frame_support::traits::ConstU32<250>; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + construct_runtime! { pub enum Runtime where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: test_pallet::{Pallet, Config}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.stderr b/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.stderr index e458265a07cab..6d5a48bf0909a 100644 --- a/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.stderr +++ b/frame/support/test/tests/construct_runtime_ui/no_std_genesis_config.stderr @@ -1,73 +1,27 @@ error: `Pallet` does not have the std feature enabled, this will cause the `test_pallet::GenesisConfig` type to be undefined. - --> $DIR/no_std_genesis_config.rs:13:1 + --> tests/construct_runtime_ui/no_std_genesis_config.rs:40:1 | -13 | / construct_runtime! { -14 | | pub enum Runtime where -15 | | Block = Block, -16 | | NodeBlock = Block, +40 | / construct_runtime! { +41 | | pub enum Runtime where +42 | | Block = Block, +43 | | NodeBlock = Block, ... | -21 | | } -22 | | } +48 | | } +49 | | } | |_^ | = note: this error originates in the macro `test_pallet::__substrate_genesis_config_check::is_std_enabled_for_genesis` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/no_std_genesis_config.rs:19:11 - | -19 | System: system::{Pallet, Call, Storage, Config, Event}, - | ^^^^^^ use of undeclared crate or module `system` - -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/no_std_genesis_config.rs:13:1 - | -13 | / construct_runtime! { -14 | | pub enum Runtime where -15 | | Block = Block, -16 | | NodeBlock = Block, -... | -21 | | } -22 | | } - | |_^ not found in `system` - | - = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing this enum - | -1 | use frame_system::RawOrigin; - | - -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/no_std_genesis_config.rs:13:1 - | -13 | / construct_runtime! { -14 | | pub enum Runtime where -15 | | Block = Block, -16 | | NodeBlock = Block, -... | -21 | | } -22 | | } - | |_^ not found in `system` - | - = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing one of these items - | -1 | use frame_support_test::Pallet; - | -1 | use frame_system::Pallet; - | -1 | use test_pallet::Pallet; - | - error[E0412]: cannot find type `GenesisConfig` in crate `test_pallet` - --> $DIR/no_std_genesis_config.rs:13:1 + --> tests/construct_runtime_ui/no_std_genesis_config.rs:40:1 | -13 | / construct_runtime! { -14 | | pub enum Runtime where -15 | | Block = Block, -16 | | NodeBlock = Block, +40 | / construct_runtime! { +41 | | pub enum Runtime where +42 | | Block = Block, +43 | | NodeBlock = Block, ... | -21 | | } -22 | | } +48 | | } +49 | | } | |_^ not found in `test_pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) @@ -76,14 +30,22 @@ help: consider importing this struct 1 | use frame_system::GenesisConfig; | -error[E0277]: the trait bound `Runtime: frame_system::pallet::Config` is not satisfied - --> $DIR/no_std_genesis_config.rs:11:6 - | -11 | impl test_pallet::Config for Runtime {} - | ^^^^^^^^^^^^^^^^^^^ the trait `frame_system::pallet::Config` is not implemented for `Runtime` - | -note: required by a bound in `Config` - --> $DIR/lib.rs:30:20 - | -30 | pub trait Config: frame_system::Config {} - | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `Config` +error[E0283]: type annotations needed + --> tests/construct_runtime_ui/no_std_genesis_config.rs:40:1 + | +40 | / construct_runtime! { +41 | | pub enum Runtime where +42 | | Block = Block, +43 | | NodeBlock = Block, +... | +48 | | } +49 | | } + | |_^ cannot infer type + | + = note: cannot satisfy `_: std::default::Default` +note: required by `std::default::Default::default` + --> $RUST/core/src/default.rs + | + | fn default() -> Self; + | ^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs index c5b9fcca1f318..1653e830f0b4f 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs @@ -12,20 +12,47 @@ mod pallet { } pub type Signature = sr25519::Signature; -pub type BlockNumber = u64; +pub type BlockNumber = u32; pub type Header = generic::Header; pub type Block = generic::Block; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; impl pallet::Config for Runtime {} +impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; + type Origin = Origin; + type Index = u64; + type BlockNumber = u32; + type Call = Call; + type Hash = sp_runtime::testing::H256; + type Hashing = sp_runtime::traits::BlakeTwo256; + type AccountId = u64; + type Lookup = sp_runtime::traits::IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = frame_support::traits::ConstU32<250>; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + construct_runtime! { pub enum Runtime where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet, Call}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.stderr index c4e567102a892..c162a22bb87b0 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_call_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_call_part.stderr @@ -1,76 +1,16 @@ error: `Pallet` does not have #[pallet::call] defined, perhaps you should remove `Call` from construct_runtime? - --> $DIR/undefined_call_part.rs:5:1 + --> tests/construct_runtime_ui/undefined_call_part.rs:5:1 | 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } +57 | | } +58 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_call_check::is_call_part_defined` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_call_part.rs:28:11 - | -28 | System: system::{Pallet, Call, Storage, Config, Event}, - | ^^^^^^ use of undeclared crate or module `system` - -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_call_part.rs:22:1 - | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, -... | -30 | | } -31 | | } - | |_^ not found in `system` - | - = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing this enum - | -1 | use frame_system::RawOrigin; - | - -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_call_part.rs:22:1 - | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, -... | -30 | | } -31 | | } - | |_^ not found in `system` - | - = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing one of these items - | -1 | use crate::pallet::Pallet; - | -1 | use frame_support_test::Pallet; - | -1 | use frame_system::Pallet; - | -1 | use test_pallet::Pallet; - | - -error[E0277]: the trait bound `Runtime: frame_system::Config` is not satisfied - --> $DIR/undefined_call_part.rs:20:6 - | -20 | impl pallet::Config for Runtime {} - | ^^^^^^^^^^^^^^ the trait `frame_system::Config` is not implemented for `Runtime` - | -note: required by a bound in `pallet::Config` - --> $DIR/undefined_call_part.rs:8:20 - | -8 | pub trait Config: frame_system::Config {} - | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `pallet::Config` diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs index 6aec45f240c90..b8f91cf4bc690 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs @@ -12,20 +12,47 @@ mod pallet { } pub type Signature = sr25519::Signature; -pub type BlockNumber = u64; +pub type BlockNumber = u32; pub type Header = generic::Header; pub type Block = generic::Block; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; impl pallet::Config for Runtime {} +impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; + type Origin = Origin; + type Index = u64; + type BlockNumber = u32; + type Call = Call; + type Hash = sp_runtime::testing::H256; + type Hashing = sp_runtime::traits::BlakeTwo256; + type AccountId = u64; + type Lookup = sp_runtime::traits::IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = frame_support::traits::ConstU32<250>; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + construct_runtime! { pub enum Runtime where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet, Event}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr index da972f6f4b2f4..31229f8c93cb6 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_event_part.stderr @@ -1,36 +1,30 @@ error: `Pallet` does not have #[pallet::event] defined, perhaps you should remove `Event` from construct_runtime? - --> $DIR/undefined_event_part.rs:5:1 + --> tests/construct_runtime_ui/undefined_event_part.rs:5:1 | 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } +57 | | } +58 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_event_check::is_event_part_defined` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_event_part.rs:28:11 - | -28 | System: system::{Pallet, Call, Storage, Config, Event}, - | ^^^^^^ use of undeclared crate or module `system` - error[E0412]: cannot find type `Event` in module `pallet` - --> $DIR/undefined_event_part.rs:22:1 + --> tests/construct_runtime_ui/undefined_event_part.rs:49:1 | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } +57 | | } +58 | | } | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) @@ -40,15 +34,15 @@ help: consider importing this enum | error[E0412]: cannot find type `Event` in module `pallet` - --> $DIR/undefined_event_part.rs:22:1 + --> tests/construct_runtime_ui/undefined_event_part.rs:49:1 | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } +57 | | } +58 | | } | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) @@ -58,57 +52,3 @@ help: consider importing one of these items | 1 | use frame_system::Event; | - -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_event_part.rs:22:1 - | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, -... | -30 | | } -31 | | } - | |_^ not found in `system` - | - = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing this enum - | -1 | use frame_system::RawOrigin; - | - -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_event_part.rs:22:1 - | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, -... | -30 | | } -31 | | } - | |_^ not found in `system` - | - = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing one of these items - | -1 | use crate::pallet::Pallet; - | -1 | use frame_support_test::Pallet; - | -1 | use frame_system::Pallet; - | -1 | use test_pallet::Pallet; - | - -error[E0277]: the trait bound `Runtime: frame_system::Config` is not satisfied - --> $DIR/undefined_event_part.rs:20:6 - | -20 | impl pallet::Config for Runtime {} - | ^^^^^^^^^^^^^^ the trait `frame_system::Config` is not implemented for `Runtime` - | -note: required by a bound in `pallet::Config` - --> $DIR/undefined_event_part.rs:8:20 - | -8 | pub trait Config: frame_system::Config {} - | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `pallet::Config` diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs index 5e08fd96fa1ad..a61d545b3279e 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs @@ -12,20 +12,47 @@ mod pallet { } pub type Signature = sr25519::Signature; -pub type BlockNumber = u64; +pub type BlockNumber = u32; pub type Header = generic::Header; pub type Block = generic::Block; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; impl pallet::Config for Runtime {} +impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; + type Origin = Origin; + type Index = u64; + type BlockNumber = u32; + type Call = Call; + type Hash = sp_runtime::testing::H256; + type Hashing = sp_runtime::traits::BlakeTwo256; + type AccountId = u64; + type Lookup = sp_runtime::traits::IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = frame_support::traits::ConstU32<250>; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + construct_runtime! { pub enum Runtime where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet, Config}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr index 8e40773b65736..e8532aa9a064f 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.stderr @@ -1,78 +1,30 @@ error: `Pallet` does not have #[pallet::genesis_config] defined, perhaps you should remove `Config` from construct_runtime? - --> $DIR/undefined_genesis_config_part.rs:5:1 + --> tests/construct_runtime_ui/undefined_genesis_config_part.rs:5:1 | 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } +57 | | } +58 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_genesis_config_check::is_genesis_config_defined` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_genesis_config_part.rs:28:17 - | -28 | System: system::{Pallet, Call, Storage, Config, Event}, - | ^^^^^^ use of undeclared crate or module `system` - -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_genesis_config_part.rs:22:1 - | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, -... | -30 | | } -31 | | } - | |_^ not found in `system` - | - = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing this enum - | -1 | use frame_system::RawOrigin; - | - -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_genesis_config_part.rs:22:1 - | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, -... | -30 | | } -31 | | } - | |_^ not found in `system` - | - = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing one of these items - | -1 | use crate::pallet::Pallet; - | -1 | use frame_support_test::Pallet; - | -1 | use frame_system::Pallet; - | -1 | use test_pallet::Pallet; - | - error[E0412]: cannot find type `GenesisConfig` in module `pallet` - --> $DIR/undefined_genesis_config_part.rs:22:1 + --> tests/construct_runtime_ui/undefined_genesis_config_part.rs:49:1 | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } +57 | | } +58 | | } | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) @@ -81,14 +33,22 @@ help: consider importing this struct 1 | use frame_system::GenesisConfig; | -error[E0277]: the trait bound `Runtime: frame_system::Config` is not satisfied - --> $DIR/undefined_genesis_config_part.rs:20:6 - | -20 | impl pallet::Config for Runtime {} - | ^^^^^^^^^^^^^^ the trait `frame_system::Config` is not implemented for `Runtime` - | -note: required by a bound in `pallet::Config` - --> $DIR/undefined_genesis_config_part.rs:8:20 - | -8 | pub trait Config: frame_system::Config {} - | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `pallet::Config` +error[E0283]: type annotations needed + --> tests/construct_runtime_ui/undefined_genesis_config_part.rs:49:1 + | +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, +... | +57 | | } +58 | | } + | |_^ cannot infer type + | + = note: cannot satisfy `_: std::default::Default` +note: required by `std::default::Default::default` + --> $RUST/core/src/default.rs + | + | fn default() -> Self; + | ^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs index 06c36a30f5506..6e4764286ab41 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs @@ -12,20 +12,47 @@ mod pallet { } pub type Signature = sr25519::Signature; -pub type BlockNumber = u64; +pub type BlockNumber = u32; pub type Header = generic::Header; pub type Block = generic::Block; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; impl pallet::Config for Runtime {} +impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; + type Origin = Origin; + type Index = u64; + type BlockNumber = u32; + type Call = Call; + type Hash = sp_runtime::testing::H256; + type Hashing = sp_runtime::traits::BlakeTwo256; + type AccountId = u64; + type Lookup = sp_runtime::traits::IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = frame_support::traits::ConstU32<250>; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + construct_runtime! { pub enum Runtime where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet, Inherent}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.stderr index ae461473c3b11..9f646469d86a8 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.stderr @@ -1,76 +1,116 @@ error: `Pallet` does not have #[pallet::inherent] defined, perhaps you should remove `Inherent` from construct_runtime? - --> $DIR/undefined_inherent_part.rs:5:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:5:1 | 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } +57 | | } +58 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_inherent_check::is_inherent_part_defined` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_inherent_part.rs:28:11 +error[E0599]: no function or associated item named `create_inherent` found for struct `pallet::Pallet` in the current scope + --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 | -28 | System: system::{Pallet, Call, Storage, Config, Event}, - | ^^^^^^ use of undeclared crate or module `system` - -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_inherent_part.rs:22:1 - | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +11 | pub struct Pallet(_); + | ------------------------ function or associated item `create_inherent` not found for this +... +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } - | |_^ not found in `system` +57 | | } +58 | | } + | |_^ function or associated item not found in `pallet::Pallet` | + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `create_inherent`, perhaps you need to implement it: + candidate #1: `ProvideInherent` = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing this enum - | -1 | use frame_system::RawOrigin; - | -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_inherent_part.rs:22:1 +error[E0599]: no function or associated item named `is_inherent` found for struct `pallet::Pallet` in the current scope + --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +11 | pub struct Pallet(_); + | ------------------------ function or associated item `is_inherent` not found for this +... +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } - | |_^ not found in `system` +57 | | } +58 | | } + | |_^ function or associated item not found in `pallet::Pallet` | + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `is_inherent`, perhaps you need to implement it: + candidate #1: `ProvideInherent` = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing one of these items - | -1 | use crate::pallet::Pallet; + +error[E0599]: no function or associated item named `check_inherent` found for struct `pallet::Pallet` in the current scope + --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 | -1 | use frame_support_test::Pallet; +11 | pub struct Pallet(_); + | ------------------------ function or associated item `check_inherent` not found for this +... +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, +... | +57 | | } +58 | | } + | |_^ function or associated item not found in `pallet::Pallet` | -1 | use frame_system::Pallet; + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `check_inherent`, perhaps you need to implement it: + candidate #1: `ProvideInherent` + = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0599]: no associated item named `INHERENT_IDENTIFIER` found for struct `pallet::Pallet` in the current scope + --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 | -1 | use test_pallet::Pallet; +11 | pub struct Pallet(_); + | ------------------------ associated item `INHERENT_IDENTIFIER` not found for this +... +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, +... | +57 | | } +58 | | } + | |_^ associated item not found in `pallet::Pallet` | + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `INHERENT_IDENTIFIER`, perhaps you need to implement it: + candidate #1: `ProvideInherent` + = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0277]: the trait bound `Runtime: frame_system::Config` is not satisfied - --> $DIR/undefined_inherent_part.rs:20:6 +error[E0599]: no function or associated item named `is_inherent_required` found for struct `pallet::Pallet` in the current scope + --> tests/construct_runtime_ui/undefined_inherent_part.rs:49:1 | -20 | impl pallet::Config for Runtime {} - | ^^^^^^^^^^^^^^ the trait `frame_system::Config` is not implemented for `Runtime` - | -note: required by a bound in `pallet::Config` - --> $DIR/undefined_inherent_part.rs:8:20 +11 | pub struct Pallet(_); + | ------------------------ function or associated item `is_inherent_required` not found for this +... +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, +... | +57 | | } +58 | | } + | |_^ function or associated item not found in `pallet::Pallet` | -8 | pub trait Config: frame_system::Config {} - | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `pallet::Config` + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following trait defines an item `is_inherent_required`, perhaps you need to implement it: + candidate #1: `ProvideInherent` + = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs index bec5c27ec0346..9233404a865b9 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs @@ -12,20 +12,47 @@ mod pallet { } pub type Signature = sr25519::Signature; -pub type BlockNumber = u64; +pub type BlockNumber = u32; pub type Header = generic::Header; pub type Block = generic::Block; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; impl pallet::Config for Runtime {} +impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; + type Origin = Origin; + type Index = u64; + type BlockNumber = u32; + type Call = Call; + type Hash = sp_runtime::testing::H256; + type Hashing = sp_runtime::traits::BlakeTwo256; + type AccountId = u64; + type Lookup = sp_runtime::traits::IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = frame_support::traits::ConstU32<250>; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + construct_runtime! { pub enum Runtime where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet, Origin}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr index dbdd9f869a2e3..06e845618d44f 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.stderr @@ -1,54 +1,30 @@ error: `Pallet` does not have #[pallet::origin] defined, perhaps you should remove `Origin` from construct_runtime? - --> $DIR/undefined_origin_part.rs:5:1 + --> tests/construct_runtime_ui/undefined_origin_part.rs:5:1 | 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } +57 | | } +58 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_origin_check::is_origin_part_defined` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_origin_part.rs:28:11 - | -28 | System: system::{Pallet, Call, Storage, Config, Event}, - | ^^^^^^ use of undeclared crate or module `system` - -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_origin_part.rs:22:1 - | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, -... | -30 | | } -31 | | } - | |_^ not found in `system` - | - = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing this enum - | -1 | use frame_system::RawOrigin; - | - error[E0412]: cannot find type `Origin` in module `pallet` - --> $DIR/undefined_origin_part.rs:22:1 + --> tests/construct_runtime_ui/undefined_origin_part.rs:49:1 | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } +57 | | } +58 | | } | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) @@ -58,15 +34,15 @@ help: consider importing this type alias | error[E0412]: cannot find type `Origin` in module `pallet` - --> $DIR/undefined_origin_part.rs:22:1 + --> tests/construct_runtime_ui/undefined_origin_part.rs:49:1 | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } +57 | | } +58 | | } | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) @@ -77,38 +53,16 @@ help: consider importing one of these items 1 | use frame_system::Origin; | -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_origin_part.rs:22:1 +error[E0282]: type annotations needed + --> tests/construct_runtime_ui/undefined_origin_part.rs:49:1 | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } - | |_^ not found in `system` +57 | | } +58 | | } + | |_^ cannot infer type for type parameter `AccountId` declared on the enum `RawOrigin` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing one of these items - | -1 | use crate::pallet::Pallet; - | -1 | use frame_support_test::Pallet; - | -1 | use frame_system::Pallet; - | -1 | use test_pallet::Pallet; - | - -error[E0277]: the trait bound `Runtime: frame_system::Config` is not satisfied - --> $DIR/undefined_origin_part.rs:20:6 - | -20 | impl pallet::Config for Runtime {} - | ^^^^^^^^^^^^^^ the trait `frame_system::Config` is not implemented for `Runtime` - | -note: required by a bound in `pallet::Config` - --> $DIR/undefined_origin_part.rs:8:20 - | -8 | pub trait Config: frame_system::Config {} - | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `pallet::Config` diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs index 816f52b91cccb..621683aca3754 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs +++ b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs @@ -12,20 +12,47 @@ mod pallet { } pub type Signature = sr25519::Signature; -pub type BlockNumber = u64; +pub type BlockNumber = u32; pub type Header = generic::Header; pub type Block = generic::Block; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; impl pallet::Config for Runtime {} +impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; + type Origin = Origin; + type Index = u64; + type BlockNumber = u32; + type Call = Call; + type Hash = sp_runtime::testing::H256; + type Hashing = sp_runtime::traits::BlakeTwo256; + type AccountId = u64; + type Lookup = sp_runtime::traits::IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = frame_support::traits::ConstU32<250>; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + construct_runtime! { pub enum Runtime where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic { - System: system::{Pallet, Call, Storage, Config, Event}, + System: frame_system::{Pallet, Call, Storage, Config, Event}, Pallet: pallet::{Pallet, ValidateUnsigned}, } } diff --git a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr index 8126d2f9a3e0f..94226075d9a4b 100644 --- a/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr +++ b/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.stderr @@ -1,76 +1,67 @@ error: `Pallet` does not have #[pallet::validate_unsigned] defined, perhaps you should remove `ValidateUnsigned` from construct_runtime? - --> $DIR/undefined_validate_unsigned_part.rs:5:1 + --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:5:1 | 5 | #[frame_support::pallet] | ^^^^^^^^^^^^^^^^^^^^^^^^ ... -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } +57 | | } +58 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_validate_unsigned_check::is_validate_unsigned_part_defined` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_validate_unsigned_part.rs:28:11 +error[E0599]: no variant or associated item named `Pallet` found for enum `Call` in the current scope + --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:56:3 | -28 | System: system::{Pallet, Call, Storage, Config, Event}, - | ^^^^^^ use of undeclared crate or module `system` +49 | construct_runtime! { + | ------------------ variant or associated item `Pallet` not found here +... +56 | Pallet: pallet::{Pallet, ValidateUnsigned}, + | ^^^^^^ variant or associated item not found in `Call` -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_validate_unsigned_part.rs:22:1 +error[E0599]: no function or associated item named `pre_dispatch` found for struct `pallet::Pallet` in the current scope + --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:49:1 | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +11 | pub struct Pallet(_); + | ------------------------ function or associated item `pre_dispatch` not found for this +... +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } - | |_^ not found in `system` - | +57 | | } +58 | | } + | |_^ function or associated item not found in `pallet::Pallet` + | + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following traits define an item `pre_dispatch`, perhaps you need to implement one of them: + candidate #1: `SignedExtension` + candidate #2: `ValidateUnsigned` = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing this enum - | -1 | use frame_system::RawOrigin; - | -error[E0433]: failed to resolve: use of undeclared crate or module `system` - --> $DIR/undefined_validate_unsigned_part.rs:22:1 +error[E0599]: no function or associated item named `validate_unsigned` found for struct `pallet::Pallet` in the current scope + --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:49:1 | -22 | / construct_runtime! { -23 | | pub enum Runtime where -24 | | Block = Block, -25 | | NodeBlock = Block, +11 | pub struct Pallet(_); + | ------------------------ function or associated item `validate_unsigned` not found for this +... +49 | / construct_runtime! { +50 | | pub enum Runtime where +51 | | Block = Block, +52 | | NodeBlock = Block, ... | -30 | | } -31 | | } - | |_^ not found in `system` - | +57 | | } +58 | | } + | |_^ function or associated item not found in `pallet::Pallet` + | + = help: items from traits can only be used if the trait is implemented and in scope + = note: the following traits define an item `validate_unsigned`, perhaps you need to implement one of them: + candidate #1: `SignedExtension` + candidate #2: `ValidateUnsigned` = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider importing one of these items - | -1 | use crate::pallet::Pallet; - | -1 | use frame_support_test::Pallet; - | -1 | use frame_system::Pallet; - | -1 | use test_pallet::Pallet; - | - -error[E0277]: the trait bound `Runtime: frame_system::Config` is not satisfied - --> $DIR/undefined_validate_unsigned_part.rs:20:6 - | -20 | impl pallet::Config for Runtime {} - | ^^^^^^^^^^^^^^ the trait `frame_system::Config` is not implemented for `Runtime` - | -note: required by a bound in `pallet::Config` - --> $DIR/undefined_validate_unsigned_part.rs:8:20 - | -8 | pub trait Config: frame_system::Config {} - | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `pallet::Config` diff --git a/frame/support/test/tests/pallet.rs b/frame/support/test/tests/pallet.rs index 2cb7b283b66fb..451cb2e7b889e 100644 --- a/frame/support/test/tests/pallet.rs +++ b/frame/support/test/tests/pallet.rs @@ -29,7 +29,7 @@ use sp_io::{ hashing::{blake2_128, twox_128, twox_64}, TestExternalities, }; -use sp_runtime::DispatchError; +use sp_runtime::{DispatchError, ModuleError}; pub struct SomeType1; impl From for u64 { @@ -432,7 +432,7 @@ pub mod pallet { } // Test that a pallet with non generic event and generic genesis_config is correctly handled -// and that a pallet without the attribute generate_storage_info is correctly handled. +// and that a pallet with the attribute without_storage_info is correctly handled. #[frame_support::pallet] pub mod pallet2 { use super::{SomeAssociation1, SomeType1}; @@ -654,7 +654,11 @@ fn error_expand() { ); assert_eq!( DispatchError::from(pallet::Error::::InsufficientProposersBalance), - DispatchError::Module { index: 1, error: 0, message: Some("InsufficientProposersBalance") }, + DispatchError::Module(ModuleError { + index: 1, + error: 0, + message: Some("InsufficientProposersBalance") + }), ); } diff --git a/frame/support/test/tests/pallet_instance.rs b/frame/support/test/tests/pallet_instance.rs index 4a8636919b583..30b9bcda88d1e 100644 --- a/frame/support/test/tests/pallet_instance.rs +++ b/frame/support/test/tests/pallet_instance.rs @@ -25,7 +25,7 @@ use sp_io::{ hashing::{blake2_128, twox_128, twox_64}, TestExternalities, }; -use sp_runtime::DispatchError; +use sp_runtime::{DispatchError, ModuleError}; #[frame_support::pallet] pub mod pallet { @@ -341,7 +341,11 @@ fn error_expand() { ); assert_eq!( DispatchError::from(pallet::Error::::InsufficientProposersBalance), - DispatchError::Module { index: 1, error: 0, message: Some("InsufficientProposersBalance") }, + DispatchError::Module(ModuleError { + index: 1, + error: 0, + message: Some("InsufficientProposersBalance") + }), ); assert_eq!( @@ -358,7 +362,11 @@ fn error_expand() { DispatchError::from( pallet::Error::::InsufficientProposersBalance ), - DispatchError::Module { index: 2, error: 0, message: Some("InsufficientProposersBalance") }, + DispatchError::Module(ModuleError { + index: 2, + error: 0, + message: Some("InsufficientProposersBalance") + }), ); } diff --git a/frame/support/test/tests/system.rs b/frame/support/test/tests/system.rs index 0083835640cb7..b30fd8d5ec561 100644 --- a/frame/support/test/tests/system.rs +++ b/frame/support/test/tests/system.rs @@ -69,23 +69,7 @@ frame_support::decl_error! { } } -/// Origin for the system module. -#[derive(PartialEq, Eq, Clone, sp_runtime::RuntimeDebug, Encode, Decode, scale_info::TypeInfo)] -pub enum RawOrigin { - Root, - Signed(AccountId), - None, -} - -impl From> for RawOrigin { - fn from(s: Option) -> RawOrigin { - match s { - Some(who) => RawOrigin::Signed(who), - None => RawOrigin::None, - } - } -} - +pub use frame_support::dispatch::RawOrigin; pub type Origin = RawOrigin<::AccountId>; #[allow(dead_code)] diff --git a/frame/system/Cargo.toml b/frame/system/Cargo.toml index ae9242087f1a8..5d45544fe7bb0 100644 --- a/frame/system/Cargo.toml +++ b/frame/system/Cargo.toml @@ -13,20 +13,20 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -serde = { version = "1.0.132", optional = true, features = ["derive"] } +serde = { version = "1.0.136", optional = true, features = ["derive"] } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0", path = "../../primitives/io", default-features = false } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-io = { version = "5.0.0", path = "../../primitives/io", default-features = false } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-version = { version = "4.0.0-dev", default-features = false, path = "../../primitives/version" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } log = { version = "0.4.14", default-features = false } [dev-dependencies] criterion = "0.3.3" -sp-externalities = { version = "0.10.0", path = "../../primitives/externalities" } +sp-externalities = { version = "0.11.0", path = "../../primitives/externalities" } substrate-test-runtime-client = { version = "2.0.0", path = "../../test-utils/runtime/client" } [features] diff --git a/frame/system/benchmarking/Cargo.toml b/frame/system/benchmarking/Cargo.toml index 4ca250fa0ec7e..fa86250c199e5 100644 --- a/frame/system/benchmarking/Cargo.toml +++ b/frame/system/benchmarking/Cargo.toml @@ -16,14 +16,14 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../../primitives/std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../../benchmarking" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../../system" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../../support" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/core" } +sp-core = { version = "5.0.0", default-features = false, path = "../../../primitives/core" } [dev-dependencies] -sp-io = { version = "4.0.0", path = "../../../primitives/io" } +sp-io = { version = "5.0.0", path = "../../../primitives/io" } [features] default = ["std"] diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index 9857e2ac806f1..3b4de0c472c47 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -124,6 +124,7 @@ pub use extensions::{ }; // Backward compatible re-export. pub use extensions::check_mortality::CheckMortality as CheckEra; +pub use frame_support::dispatch::RawOrigin; pub use weights::WeightInfo; /// Compute the trie root of a list of extrinsics. @@ -479,11 +480,6 @@ pub mod pallet { } /// Make some on-chain remark and emit event. - /// - /// # - /// - `O(b)` where b is the length of the remark. - /// - 1 event. - /// # #[pallet::weight(T::SystemWeightInfo::remark_with_event(remark.len() as u32))] pub fn remark_with_event( origin: OriginFor, @@ -713,28 +709,6 @@ pub struct EventRecord { pub topics: Vec, } -/// Origin for the System pallet. -#[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode, TypeInfo)] -pub enum RawOrigin { - /// The system itself ordained this dispatch to happen: this is the highest privilege level. - Root, - /// It is signed by some public key and we provide the `AccountId`. - Signed(AccountId), - /// It is signed by nobody, can be either: - /// * included and agreed upon by the validators anyway, - /// * or unsigned transaction validated by a pallet. - None, -} - -impl From> for RawOrigin { - fn from(s: Option) -> RawOrigin { - match s { - Some(who) => RawOrigin::Signed(who), - None => RawOrigin::None, - } - } -} - // Create a Hash with 69 for each byte, // only used to build genesis config. #[cfg(feature = "std")] @@ -1329,7 +1303,8 @@ impl Pallet { >::remove(to_remove); } - let storage_root = T::Hash::decode(&mut &sp_io::storage::root()[..]) + let version = T::Version::get().state_version(); + let storage_root = T::Hash::decode(&mut &sp_io::storage::root(version)[..]) .expect("Node is configured to use the same hash; qed"); ::new( @@ -1645,7 +1620,7 @@ impl Lookup for ChainContext { /// Prelude to be used alongside pallet macro, for ease of use. pub mod pallet_prelude { - pub use crate::{ensure_none, ensure_root, ensure_signed}; + pub use crate::{ensure_none, ensure_root, ensure_signed, ensure_signed_or_root}; /// Type alias for the `Origin` associated type of system config. pub type OriginFor = ::Origin; diff --git a/frame/system/src/weights.rs b/frame/system/src/weights.rs index ff6900032d961..a016fe6e7d037 100644 --- a/frame/system/src/weights.rs +++ b/frame/system/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for frame_system //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/system/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -56,80 +57,80 @@ pub trait WeightInfo { /// Weights for frame_system using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - fn remark(b: u32, ) -> Weight { - (574_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) + fn remark(_b: u32, ) -> Weight { + (0 as Weight) } fn remark_with_event(b: u32, ) -> Weight { (0 as Weight) // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) } + // Storage: System Digest (r:1 w:1) // Storage: unknown [0x3a686561707061676573] (r:0 w:1) fn set_heap_pages() -> Weight { - (1_891_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + (2_864_000 as Weight) + .saturating_add(T::DbWeight::get().reads(1 as Weight)) + .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Skipped Metadata (r:0 w:0) fn set_storage(i: u32, ) -> Weight { (0 as Weight) // Standard Error: 0 - .saturating_add((848_000 as Weight).saturating_mul(i as Weight)) + .saturating_add((389_000 as Weight).saturating_mul(i as Weight)) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) } // Storage: Skipped Metadata (r:0 w:0) fn kill_storage(i: u32, ) -> Weight { - (308_000 as Weight) + (0 as Weight) // Standard Error: 0 - .saturating_add((559_000 as Weight).saturating_mul(i as Weight)) + .saturating_add((285_000 as Weight).saturating_mul(i as Weight)) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) } // Storage: Skipped Metadata (r:0 w:0) fn kill_prefix(p: u32, ) -> Weight { - (7_616_000 as Weight) - // Standard Error: 1_000 - .saturating_add((783_000 as Weight).saturating_mul(p as Weight)) + (753_000 as Weight) + // Standard Error: 0 + .saturating_add((630_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) } } // For backwards compatibility and tests impl WeightInfo for () { - fn remark(b: u32, ) -> Weight { - (574_000 as Weight) - // Standard Error: 0 - .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) + fn remark(_b: u32, ) -> Weight { + (0 as Weight) } fn remark_with_event(b: u32, ) -> Weight { (0 as Weight) // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) + .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) } + // Storage: System Digest (r:1 w:1) // Storage: unknown [0x3a686561707061676573] (r:0 w:1) fn set_heap_pages() -> Weight { - (1_891_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + (2_864_000 as Weight) + .saturating_add(RocksDbWeight::get().reads(1 as Weight)) + .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Skipped Metadata (r:0 w:0) fn set_storage(i: u32, ) -> Weight { (0 as Weight) // Standard Error: 0 - .saturating_add((848_000 as Weight).saturating_mul(i as Weight)) + .saturating_add((389_000 as Weight).saturating_mul(i as Weight)) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) } // Storage: Skipped Metadata (r:0 w:0) fn kill_storage(i: u32, ) -> Weight { - (308_000 as Weight) + (0 as Weight) // Standard Error: 0 - .saturating_add((559_000 as Weight).saturating_mul(i as Weight)) + .saturating_add((285_000 as Weight).saturating_mul(i as Weight)) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(i as Weight))) } // Storage: Skipped Metadata (r:0 w:0) fn kill_prefix(p: u32, ) -> Weight { - (7_616_000 as Weight) - // Standard Error: 1_000 - .saturating_add((783_000 as Weight).saturating_mul(p as Weight)) + (753_000 as Weight) + // Standard Error: 0 + .saturating_add((630_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(p as Weight))) } } diff --git a/frame/timestamp/Cargo.toml b/frame/timestamp/Cargo.toml index b66a91acebaa0..f42a95010587a 100644 --- a/frame/timestamp/Cargo.toml +++ b/frame/timestamp/Cargo.toml @@ -18,8 +18,8 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "2.2.0", default-features = false, features = ["derive", "max-encoded-len"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io", optional = true } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io", optional = true } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-inherents = { version = "4.0.0-dev", default-features = false, path = "../../primitives/inherents" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } @@ -28,8 +28,8 @@ sp-timestamp = { version = "4.0.0-dev", default-features = false, path = "../../ log = { version = "0.4.14", default-features = false } [dev-dependencies] -sp-io ={ version = "4.0.0-dev", path = "../../primitives/io" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-io ={ version = "5.0.0", path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } [features] default = ["std"] diff --git a/frame/timestamp/src/weights.rs b/frame/timestamp/src/weights.rs index fb452ebe35953..33d7d6a4b9e37 100644 --- a/frame/timestamp/src/weights.rs +++ b/frame/timestamp/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_timestamp //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/timestamp/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -55,12 +56,12 @@ impl WeightInfo for SubstrateWeight { // Storage: Timestamp Now (r:1 w:1) // Storage: Babe CurrentSlot (r:1 w:0) fn set() -> Weight { - (10_391_000 as Weight) + (5_247_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } fn on_finalize() -> Weight { - (4_843_000 as Weight) + (2_604_000 as Weight) } } @@ -69,11 +70,11 @@ impl WeightInfo for () { // Storage: Timestamp Now (r:1 w:1) // Storage: Babe CurrentSlot (r:1 w:0) fn set() -> Weight { - (10_391_000 as Weight) + (5_247_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } fn on_finalize() -> Weight { - (4_843_000 as Weight) + (2_604_000 as Weight) } } diff --git a/frame/tips/Cargo.toml b/frame/tips/Cargo.toml index bbe78fd30a56b..f898a255b87c8 100644 --- a/frame/tips/Cargo.toml +++ b/frame/tips/Cargo.toml @@ -16,11 +16,11 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } log = { version = "0.4.0", default-features = false } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.132", features = ["derive"], optional = true } +serde = { version = "1.0.136", features = ["derive"], optional = true } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } @@ -30,7 +30,7 @@ pallet-treasury = { version = "4.0.0-dev", default-features = false, path = "../ frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } [dev-dependencies] -sp-storage = { version = "4.0.0", path = "../../primitives/storage" } +sp-storage = { version = "5.0.0", path = "../../primitives/storage" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } [features] diff --git a/frame/tips/src/weights.rs b/frame/tips/src/weights.rs index 29e85ccad8510..2ba15a0c2fcc0 100644 --- a/frame/tips/src/weights.rs +++ b/frame/tips/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_tips //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/tips/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -56,60 +57,60 @@ pub trait WeightInfo { /// Weights for pallet_tips using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - // Storage: Treasury Reasons (r:1 w:1) - // Storage: Treasury Tips (r:1 w:1) + // Storage: Tips Reasons (r:1 w:1) + // Storage: Tips Tips (r:1 w:1) fn report_awesome(r: u32, ) -> Weight { - (50_921_000 as Weight) + (25_262_000 as Weight) // Standard Error: 0 .saturating_add((2_000 as Weight).saturating_mul(r as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } - // Storage: Treasury Tips (r:1 w:1) - // Storage: Treasury Reasons (r:0 w:1) + // Storage: Tips Tips (r:1 w:1) + // Storage: Tips Reasons (r:0 w:1) fn retract_tip() -> Weight { - (46_352_000 as Weight) + (24_162_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Elections Members (r:1 w:0) - // Storage: Treasury Reasons (r:1 w:1) - // Storage: Treasury Tips (r:0 w:1) + // Storage: Tips Reasons (r:1 w:1) + // Storage: Tips Tips (r:0 w:1) fn tip_new(r: u32, t: u32, ) -> Weight { - (33_338_000 as Weight) + (16_435_000 as Weight) // Standard Error: 0 .saturating_add((2_000 as Weight).saturating_mul(r as Weight)) - // Standard Error: 0 - .saturating_add((115_000 as Weight).saturating_mul(t as Weight)) + // Standard Error: 4_000 + .saturating_add((231_000 as Weight).saturating_mul(t as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Elections Members (r:1 w:0) - // Storage: Treasury Tips (r:1 w:1) + // Storage: Tips Tips (r:1 w:1) fn tip(t: u32, ) -> Weight { - (22_702_000 as Weight) - // Standard Error: 0 - .saturating_add((538_000 as Weight).saturating_mul(t as Weight)) + (10_427_000 as Weight) + // Standard Error: 7_000 + .saturating_add((507_000 as Weight).saturating_mul(t as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } - // Storage: Treasury Tips (r:1 w:1) + // Storage: Tips Tips (r:1 w:1) // Storage: Elections Members (r:1 w:0) // Storage: System Account (r:1 w:1) - // Storage: Treasury Reasons (r:0 w:1) + // Storage: Tips Reasons (r:0 w:1) fn close_tip(t: u32, ) -> Weight { - (84_094_000 as Weight) - // Standard Error: 0 - .saturating_add((283_000 as Weight).saturating_mul(t as Weight)) + (40_901_000 as Weight) + // Standard Error: 10_000 + .saturating_add((281_000 as Weight).saturating_mul(t as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } - // Storage: Treasury Tips (r:1 w:1) - // Storage: Treasury Reasons (r:0 w:1) + // Storage: Tips Tips (r:1 w:1) + // Storage: Tips Reasons (r:0 w:1) fn slash_tip(t: u32, ) -> Weight { - (24_891_000 as Weight) - // Standard Error: 0 - .saturating_add((6_000 as Weight).saturating_mul(t as Weight)) + (14_636_000 as Weight) + // Standard Error: 4_000 + .saturating_add((29_000 as Weight).saturating_mul(t as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -117,60 +118,60 @@ impl WeightInfo for SubstrateWeight { // For backwards compatibility and tests impl WeightInfo for () { - // Storage: Treasury Reasons (r:1 w:1) - // Storage: Treasury Tips (r:1 w:1) + // Storage: Tips Reasons (r:1 w:1) + // Storage: Tips Tips (r:1 w:1) fn report_awesome(r: u32, ) -> Weight { - (50_921_000 as Weight) + (25_262_000 as Weight) // Standard Error: 0 .saturating_add((2_000 as Weight).saturating_mul(r as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } - // Storage: Treasury Tips (r:1 w:1) - // Storage: Treasury Reasons (r:0 w:1) + // Storage: Tips Tips (r:1 w:1) + // Storage: Tips Reasons (r:0 w:1) fn retract_tip() -> Weight { - (46_352_000 as Weight) + (24_162_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Elections Members (r:1 w:0) - // Storage: Treasury Reasons (r:1 w:1) - // Storage: Treasury Tips (r:0 w:1) + // Storage: Tips Reasons (r:1 w:1) + // Storage: Tips Tips (r:0 w:1) fn tip_new(r: u32, t: u32, ) -> Weight { - (33_338_000 as Weight) + (16_435_000 as Weight) // Standard Error: 0 .saturating_add((2_000 as Weight).saturating_mul(r as Weight)) - // Standard Error: 0 - .saturating_add((115_000 as Weight).saturating_mul(t as Weight)) + // Standard Error: 4_000 + .saturating_add((231_000 as Weight).saturating_mul(t as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Elections Members (r:1 w:0) - // Storage: Treasury Tips (r:1 w:1) + // Storage: Tips Tips (r:1 w:1) fn tip(t: u32, ) -> Weight { - (22_702_000 as Weight) - // Standard Error: 0 - .saturating_add((538_000 as Weight).saturating_mul(t as Weight)) + (10_427_000 as Weight) + // Standard Error: 7_000 + .saturating_add((507_000 as Weight).saturating_mul(t as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } - // Storage: Treasury Tips (r:1 w:1) + // Storage: Tips Tips (r:1 w:1) // Storage: Elections Members (r:1 w:0) // Storage: System Account (r:1 w:1) - // Storage: Treasury Reasons (r:0 w:1) + // Storage: Tips Reasons (r:0 w:1) fn close_tip(t: u32, ) -> Weight { - (84_094_000 as Weight) - // Standard Error: 0 - .saturating_add((283_000 as Weight).saturating_mul(t as Weight)) + (40_901_000 as Weight) + // Standard Error: 10_000 + .saturating_add((281_000 as Weight).saturating_mul(t as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } - // Storage: Treasury Tips (r:1 w:1) - // Storage: Treasury Reasons (r:0 w:1) + // Storage: Tips Tips (r:1 w:1) + // Storage: Tips Reasons (r:0 w:1) fn slash_tip(t: u32, ) -> Weight { - (24_891_000 as Weight) - // Standard Error: 0 - .saturating_add((6_000 as Weight).saturating_mul(t as Weight)) + (14_636_000 as Weight) + // Standard Error: 4_000 + .saturating_add((29_000 as Weight).saturating_mul(t as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } diff --git a/frame/transaction-payment/Cargo.toml b/frame/transaction-payment/Cargo.toml index 8cb544159dd70..1f27e355b1d99 100644 --- a/frame/transaction-payment/Cargo.toml +++ b/frame/transaction-payment/Cargo.toml @@ -17,12 +17,12 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = "derive", ] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.132", optional = true } +serde = { version = "1.0.136", optional = true } smallvec = "1.7.0" -sp-core = { version = "4.1.0-dev", path = "../../primitives/core", default-features = false } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io", default-features = false } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../primitives/core", default-features = false } +sp-io = { version = "5.0.0", path = "../../primitives/io", default-features = false } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } diff --git a/frame/transaction-payment/asset-tx-payment/Cargo.toml b/frame/transaction-payment/asset-tx-payment/Cargo.toml index ab2d3302f95b0..6f42595d200c9 100644 --- a/frame/transaction-payment/asset-tx-payment/Cargo.toml +++ b/frame/transaction-payment/asset-tx-payment/Cargo.toml @@ -14,9 +14,9 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] # Substrate dependencies -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/core" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/io" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../../primitives/io" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../../primitives/std" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../../support" } @@ -26,13 +26,13 @@ pallet-transaction-payment = { version = "4.0.0-dev", default-features = false, # Other dependencies codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.132", optional = true } +serde = { version = "1.0.136", optional = true } [dev-dependencies] smallvec = "1.7.0" serde_json = "1.0.74" -sp-storage = { version = "4.0.0", default-features = false, path = "../../../primitives/storage" } +sp-storage = { version = "5.0.0", default-features = false, path = "../../../primitives/storage" } pallet-assets = { version = "4.0.0-dev", path = "../../assets" } pallet-authorship = { version = "4.0.0-dev", path = "../../authorship" } diff --git a/frame/transaction-payment/rpc/Cargo.toml b/frame/transaction-payment/rpc/Cargo.toml index 2486654404aef..844e898ed867f 100644 --- a/frame/transaction-payment/rpc/Cargo.toml +++ b/frame/transaction-payment/rpc/Cargo.toml @@ -20,7 +20,7 @@ jsonrpc-derive = "18.0.0" sp-api = { version = "4.0.0-dev", path = "../../../primitives/api" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } -sp-rpc = { version = "4.0.0-dev", path = "../../../primitives/rpc" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } +sp-rpc = { version = "5.0.0", path = "../../../primitives/rpc" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } pallet-transaction-payment-rpc-runtime-api = { version = "4.0.0-dev", path = "./runtime-api" } diff --git a/frame/transaction-payment/rpc/runtime-api/Cargo.toml b/frame/transaction-payment/rpc/runtime-api/Cargo.toml index 1ad56280ac082..fed57eb5bf736 100644 --- a/frame/transaction-payment/rpc/runtime-api/Cargo.toml +++ b/frame/transaction-payment/rpc/runtime-api/Cargo.toml @@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } sp-api = { version = "4.0.0-dev", default-features = false, path = "../../../../primitives/api" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../../../primitives/runtime" } pallet-transaction-payment = { version = "4.0.0-dev", default-features = false, path = "../../../transaction-payment" } [features] diff --git a/frame/transaction-payment/rpc/src/lib.rs b/frame/transaction-payment/rpc/src/lib.rs index b2ff31618f78a..29d94fa260105 100644 --- a/frame/transaction-payment/rpc/src/lib.rs +++ b/frame/transaction-payment/rpc/src/lib.rs @@ -103,7 +103,7 @@ where api.query_info(&at, uxt, encoded_len).map_err(|e| RpcError { code: ErrorCode::ServerError(Error::RuntimeError.into()), message: "Unable to query dispatch info.".into(), - data: Some(format!("{:?}", e).into()), + data: Some(e.to_string().into()), }) } @@ -127,7 +127,7 @@ where let fee_details = api.query_fee_details(&at, uxt, encoded_len).map_err(|e| RpcError { code: ErrorCode::ServerError(Error::RuntimeError.into()), message: "Unable to query fee details.".into(), - data: Some(format!("{:?}", e).into()), + data: Some(e.to_string().into()), })?; let try_into_rpc_balance = |value: Balance| { diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 16d2ff5827c4f..e4d77a05f284b 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -47,7 +47,7 @@ #![cfg_attr(not(feature = "std"), no_std)] -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_runtime::{ @@ -226,7 +226,7 @@ where } /// Storage releases of the pallet. -#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] enum Releases { /// Original version of the pallet. V1Ancient, @@ -248,7 +248,6 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] pub struct Pallet(_); #[pallet::config] diff --git a/frame/transaction-storage/Cargo.toml b/frame/transaction-storage/Cargo.toml index e4351438811f2..f33607058f37b 100644 --- a/frame/transaction-storage/Cargo.toml +++ b/frame/transaction-storage/Cargo.toml @@ -13,23 +13,23 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -serde = { version = "1.0.132", optional = true } +serde = { version = "1.0.136", optional = true } hex-literal = { version = "0.3.4", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } scale-info = { version = "1.0", default-features = false, features = ["derive"] } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } pallet-balances = { version = "4.0.0-dev", default-features = false, path = "../balances" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } sp-inherents = { version = "4.0.0-dev", default-features = false, path = "../../primitives/inherents" } sp-transaction-storage-proof = { version = "4.0.0-dev", default-features = false, path = "../../primitives/transaction-storage-proof" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } [dev-dependencies] sp-transaction-storage-proof = { version = "4.0.0-dev", default-features = true, path = "../../primitives/transaction-storage-proof" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core", default-features = false } +sp-core = { version = "5.0.0", path = "../../primitives/core", default-features = false } [features] default = ["std"] diff --git a/frame/transaction-storage/src/benchmarking.rs b/frame/transaction-storage/src/benchmarking.rs index d7d9f694b47cb..285b5cba7ad22 100644 --- a/frame/transaction-storage/src/benchmarking.rs +++ b/frame/transaction-storage/src/benchmarking.rs @@ -42,52 +42,64 @@ use crate::Pallet as TransactionStorage; // while hardforcing target chunk key in `build_proof` to [22, 21, 1, 0]. const PROOF: &[u8] = &hex_literal::hex!( " - 0104000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 - 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 - 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 - 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 - 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 - 000000000000000000000000000000014cd0780ffff80e316a478e2f1fcb13cf22fd0b2dbb54a6f53cff93f3ca2f3dfe8 - 7d12a3662c4c0080e316a478e2f1fcb13cf22fd0b2dbb54a6f53cff93f3ca2f3dfe87d12a3662c4c80e316a478e2f1fcb - 13cf22fd0b2dbb54a6f53cff93f3ca2f3dfe87d12a3662c4c80e316a478e2f1fcb13cf22fd0b2dbb54a6f53cff93f3ca2 - f3dfe87d12a3662c4c80e316a478e2f1fcb13cf22fd0b2dbb54a6f53cff93f3ca2f3dfe87d12a3662c4c80e316a478e2f - 1fcb13cf22fd0b2dbb54a6f53cff93f3ca2f3dfe87d12a3662c4c80e316a478e2f1fcb13cf22fd0b2dbb54a6f53cff93f - 3ca2f3dfe87d12a3662c4c80e316a478e2f1fcb13cf22fd0b2dbb54a6f53cff93f3ca2f3dfe87d12a3662c4c80e316a47 - 8e2f1fcb13cf22fd0b2dbb54a6f53cff93f3ca2f3dfe87d12a3662c4c80e316a478e2f1fcb13cf22fd0b2dbb54a6f53cf - f93f3ca2f3dfe87d12a3662c4c80e316a478e2f1fcb13cf22fd0b2dbb54a6f53cff93f3ca2f3dfe87d12a3662c4c80e31 - 6a478e2f1fcb13cf22fd0b2dbb54a6f53cff93f3ca2f3dfe87d12a3662c4c80e316a478e2f1fcb13cf22fd0b2dbb54a6f - 53cff93f3ca2f3dfe87d12a3662c4c80e316a478e2f1fcb13cf22fd0b2dbb54a6f53cff93f3ca2f3dfe87d12a3662c4c8 - 0e316a478e2f1fcb13cf22fd0b2dbb54a6f53cff93f3ca2f3dfe87d12a3662c4cbd05807777809a5d7a720ce5f9d9a012 - fbf25e92c30e732dadba8f312b05e02976313ea64d9f807d43bcbf8a3dc2f6b9e957d129e610c06d411e11743062dc1cf - 3ac289390ae4c8008592aa2d915f52941036afbe72bac4ebe7ce186c4ddc53f118e0ddd4decd8cc809a5d7a720ce5f9d9 - a012fbf25e92c30e732dadba8f312b05e02976313ea64d9f807d43bcbf8a3dc2f6b9e957d129e610c06d411e11743062d - c1cf3ac289390ae4c00809a5d7a720ce5f9d9a012fbf25e92c30e732dadba8f312b05e02976313ea64d9f807d43bcbf8a - 3dc2f6b9e957d129e610c06d411e11743062dc1cf3ac289390ae4c8008592aa2d915f52941036afbe72bac4ebe7ce186c - 4ddc53f118e0ddd4decd8cc809a5d7a720ce5f9d9a012fbf25e92c30e732dadba8f312b05e02976313ea64d9f807d43bc - bf8a3dc2f6b9e957d129e610c06d411e11743062dc1cf3ac289390ae4c8008592aa2d915f52941036afbe72bac4ebe7ce - 186c4ddc53f118e0ddd4decd8cccd0780ffff8081b825bfa9b2ba8f5f253515e7db09eb1ad3d4f02f322d3aa1398e0cb0 - 3bdb31008081b825bfa9b2ba8f5f253515e7db09eb1ad3d4f02f322d3aa1398e0cb03bdb318081b825bfa9b2ba8f5f253 - 515e7db09eb1ad3d4f02f322d3aa1398e0cb03bdb318081b825bfa9b2ba8f5f253515e7db09eb1ad3d4f02f322d3aa139 - 8e0cb03bdb318081b825bfa9b2ba8f5f253515e7db09eb1ad3d4f02f322d3aa1398e0cb03bdb318081b825bfa9b2ba8f5 - f253515e7db09eb1ad3d4f02f322d3aa1398e0cb03bdb318081b825bfa9b2ba8f5f253515e7db09eb1ad3d4f02f322d3a - a1398e0cb03bdb318081b825bfa9b2ba8f5f253515e7db09eb1ad3d4f02f322d3aa1398e0cb03bdb318081b825bfa9b2b - a8f5f253515e7db09eb1ad3d4f02f322d3aa1398e0cb03bdb318081b825bfa9b2ba8f5f253515e7db09eb1ad3d4f02f32 - 2d3aa1398e0cb03bdb318081b825bfa9b2ba8f5f253515e7db09eb1ad3d4f02f322d3aa1398e0cb03bdb318081b825bfa - 9b2ba8f5f253515e7db09eb1ad3d4f02f322d3aa1398e0cb03bdb318081b825bfa9b2ba8f5f253515e7db09eb1ad3d4f0 - 2f322d3aa1398e0cb03bdb318081b825bfa9b2ba8f5f253515e7db09eb1ad3d4f02f322d3aa1398e0cb03bdb318081b82 - 5bfa9b2ba8f5f253515e7db09eb1ad3d4f02f322d3aa1398e0cb03bdb31cd0780ffff80b4f23ac50c8e67d9b280f2b31a - 5707d52b892977acaac84d530bd188544c5f9b80b4f23ac50c8e67d9b280f2b31a5707d52b892977acaac84d530bd1885 - 44c5f9b80b4f23ac50c8e67d9b280f2b31a5707d52b892977acaac84d530bd188544c5f9b80b4f23ac50c8e67d9b280f2 - b31a5707d52b892977acaac84d530bd188544c5f9b80b4f23ac50c8e67d9b280f2b31a5707d52b892977acaac84d530bd - 188544c5f9b0080b4f23ac50c8e67d9b280f2b31a5707d52b892977acaac84d530bd188544c5f9b80b4f23ac50c8e67d9 - b280f2b31a5707d52b892977acaac84d530bd188544c5f9b80b4f23ac50c8e67d9b280f2b31a5707d52b892977acaac84 - d530bd188544c5f9b80b4f23ac50c8e67d9b280f2b31a5707d52b892977acaac84d530bd188544c5f9b80b4f23ac50c8e - 67d9b280f2b31a5707d52b892977acaac84d530bd188544c5f9b80b4f23ac50c8e67d9b280f2b31a5707d52b892977aca - ac84d530bd188544c5f9b80b4f23ac50c8e67d9b280f2b31a5707d52b892977acaac84d530bd188544c5f9b80b4f23ac5 - 0c8e67d9b280f2b31a5707d52b892977acaac84d530bd188544c5f9b80b4f23ac50c8e67d9b280f2b31a5707d52b89297 - 7acaac84d530bd188544c5f9b80b4f23ac50c8e67d9b280f2b31a5707d52b892977acaac84d530bd188544c5f9b104401 - 0000 -" + 0104000000000000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000000000000000 + 0000000000000000000000000000000000000000000000000000000000000000000000000000 + 00000000000000000000000000000000000000000000000000000000000014cd0780ffff8030 + 2eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba0080302eb0a6d2 + f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15 + f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1 + 004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e304 + 8cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697 + eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a + 30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302e + b0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b + 834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e7 + 29d1c1004657e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c10046 + 57e3048cf206d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf2 + 06d697eeb153f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb1 + 53f61a30ba80302eb0a6d2f63b834d15f1e729d1c1004657e3048cf206d697eeb153f61a30ba + bd058077778010fd81bc1359802f0b871aeb95e4410a8ec92b93af10ea767a2027cf4734e8de + 808da338e6b722f7bf2051901bd5bccee5e71d5cf6b1faff338ad7120b0256c28380221ce17f + 19117affa96e077905fe48a99723a065969c638593b7d9ab57b538438010fd81bc1359802f0b + 871aeb95e4410a8ec92b93af10ea767a2027cf4734e8de808da338e6b722f7bf2051901bd5bc + cee5e71d5cf6b1faff338ad7120b0256c283008010fd81bc1359802f0b871aeb95e4410a8ec9 + 2b93af10ea767a2027cf4734e8de808da338e6b722f7bf2051901bd5bccee5e71d5cf6b1faff + 338ad7120b0256c28380221ce17f19117affa96e077905fe48a99723a065969c638593b7d9ab + 57b538438010fd81bc1359802f0b871aeb95e4410a8ec92b93af10ea767a2027cf4734e8de80 + 8da338e6b722f7bf2051901bd5bccee5e71d5cf6b1faff338ad7120b0256c28380221ce17f19 + 117affa96e077905fe48a99723a065969c638593b7d9ab57b53843cd0780ffff804509f59593 + fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939c00804509f59593fd47b1a9 + 7189127ba65a5649cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba6 + 5a5649cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0 + 346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f983 + 6e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf89 + 1a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939c8045 + 09f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939c804509f59593fd + 47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189 + 127ba65a5649cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a56 + 49cfb0346637f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb03466 + 37f9836e155eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e15 + 5eaf891a939c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a93 + 9c804509f59593fd47b1a97189127ba65a5649cfb0346637f9836e155eaf891a939ccd0780ff + ff8078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e + 776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea + 05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f + 015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d + 06feafa3610fc44a5b2ef543cb81008078916e776c64ccea05e958559f015c082d9d06feafa3 + 610fc44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b + 2ef543cb818078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb81 + 8078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e77 + 6c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05 + e958559f015c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f01 + 5c082d9d06feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d06 + feafa3610fc44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d06feafa3610f + c44a5b2ef543cb818078916e776c64ccea05e958559f015c082d9d06feafa3610fc44a5b2ef5 + 43cb811044010000 + " ); type BalanceOf = diff --git a/frame/transaction-storage/src/lib.rs b/frame/transaction-storage/src/lib.rs index 96c247c393a78..d95a60b495121 100644 --- a/frame/transaction-storage/src/lib.rs +++ b/frame/transaction-storage/src/lib.rs @@ -189,7 +189,7 @@ pub mod pallet { // Chunk data and compute storage root let chunk_count = num_chunks(data.len() as u32); let chunks = data.chunks(CHUNK_SIZE).map(|c| c.to_vec()).collect(); - let root = sp_io::trie::blake2_256_ordered_root(chunks); + let root = sp_io::trie::blake2_256_ordered_root(chunks, sp_runtime::StateVersion::V1); let content_hash = sp_io::hashing::blake2_256(&data); let extrinsic_index = >::extrinsic_index() @@ -301,6 +301,7 @@ pub mod pallet { &proof.proof, &encode_index(chunk_index), &proof.chunk, + sp_runtime::StateVersion::V1, ), Error::::InvalidProof ); diff --git a/frame/transaction-storage/src/weights.rs b/frame/transaction-storage/src/weights.rs index ffea996b83d99..a7033da7b80ce 100644 --- a/frame/transaction-storage/src/weights.rs +++ b/frame/transaction-storage/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_transaction_storage //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/transaction-storage/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -62,7 +63,7 @@ impl WeightInfo for SubstrateWeight { fn store(l: u32, ) -> Weight { (0 as Weight) // Standard Error: 0 - .saturating_add((8_000 as Weight).saturating_mul(l as Weight)) + .saturating_add((5_000 as Weight).saturating_mul(l as Weight)) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -73,7 +74,7 @@ impl WeightInfo for SubstrateWeight { // Storage: TransactionStorage BlockTransactions (r:1 w:1) // Storage: TransactionStorage MaxBlockTransactions (r:1 w:0) fn renew() -> Weight { - (67_532_000 as Weight) + (41_286_000 as Weight) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -83,7 +84,7 @@ impl WeightInfo for SubstrateWeight { // Storage: System ParentHash (r:1 w:0) // Storage: TransactionStorage Transactions (r:1 w:0) fn check_proof_max() -> Weight { - (182_886_000 as Weight) + (136_957_000 as Weight) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -100,7 +101,7 @@ impl WeightInfo for () { fn store(l: u32, ) -> Weight { (0 as Weight) // Standard Error: 0 - .saturating_add((8_000 as Weight).saturating_mul(l as Weight)) + .saturating_add((5_000 as Weight).saturating_mul(l as Weight)) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -111,7 +112,7 @@ impl WeightInfo for () { // Storage: TransactionStorage BlockTransactions (r:1 w:1) // Storage: TransactionStorage MaxBlockTransactions (r:1 w:0) fn renew() -> Weight { - (67_532_000 as Weight) + (41_286_000 as Weight) .saturating_add(RocksDbWeight::get().reads(6 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -121,7 +122,7 @@ impl WeightInfo for () { // Storage: System ParentHash (r:1 w:0) // Storage: TransactionStorage Transactions (r:1 w:0) fn check_proof_max() -> Weight { - (182_886_000 as Weight) + (136_957_000 as Weight) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } diff --git a/frame/treasury/Cargo.toml b/frame/treasury/Cargo.toml index 0a2dab417e348..a7a210457f021 100644 --- a/frame/treasury/Cargo.toml +++ b/frame/treasury/Cargo.toml @@ -18,11 +18,11 @@ codec = { package = "parity-scale-codec", version = "2.2.0", default-features = "max-encoded-len", ] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.132", features = ["derive"], optional = true } +serde = { version = "1.0.136", features = ["derive"], optional = true } impl-trait-for-tuples = "0.2.1" sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } @@ -31,8 +31,8 @@ pallet-balances = { version = "4.0.0-dev", default-features = false, path = "../ [dev-dependencies] -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } [features] default = ["std"] diff --git a/frame/treasury/src/lib.rs b/frame/treasury/src/lib.rs index 762c0e592d891..81fca5243afa3 100644 --- a/frame/treasury/src/lib.rs +++ b/frame/treasury/src/lib.rs @@ -193,6 +193,8 @@ pub mod pallet { type SpendFunds: SpendFunds; /// The maximum number of approvals that can wait in the spending queue. + /// + /// NOTE: This parameter is also used within the Bounties Pallet extension if enabled. #[pallet::constant] type MaxApprovals: Get; } diff --git a/frame/treasury/src/weights.rs b/frame/treasury/src/weights.rs index 79635ac2a725d..dcbf5983fa65c 100644 --- a/frame/treasury/src/weights.rs +++ b/frame/treasury/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_treasury //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-07, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/treasury/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -57,34 +58,34 @@ impl WeightInfo for SubstrateWeight { // Storage: Treasury ProposalCount (r:1 w:1) // Storage: Treasury Proposals (r:0 w:1) fn propose_spend() -> Weight { - (41_567_000 as Weight) + (21_673_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Treasury Proposals (r:1 w:1) // Storage: System Account (r:1 w:1) fn reject_proposal() -> Weight { - (38_993_000 as Weight) + (25_353_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Treasury Proposals (r:1 w:0) // Storage: Treasury Approvals (r:1 w:1) fn approve_proposal(p: u32, ) -> Weight { - (13_543_000 as Weight) + (8_164_000 as Weight) // Standard Error: 1_000 - .saturating_add((55_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((57_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Treasury Approvals (r:1 w:1) - // Storage: Treasury BountyApprovals (r:1 w:1) + // Storage: Bounties BountyApprovals (r:1 w:1) // Storage: Treasury Proposals (r:2 w:2) // Storage: System Account (r:4 w:4) fn on_initialize_proposals(p: u32, ) -> Weight { - (51_708_000 as Weight) + (20_762_000 as Weight) // Standard Error: 21_000 - .saturating_add((57_926_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((26_835_000 as Weight).saturating_mul(p as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(p as Weight))) .saturating_add(T::DbWeight::get().writes(2 as Weight)) @@ -97,34 +98,34 @@ impl WeightInfo for () { // Storage: Treasury ProposalCount (r:1 w:1) // Storage: Treasury Proposals (r:0 w:1) fn propose_spend() -> Weight { - (41_567_000 as Weight) + (21_673_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Treasury Proposals (r:1 w:1) // Storage: System Account (r:1 w:1) fn reject_proposal() -> Weight { - (38_993_000 as Weight) + (25_353_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Treasury Proposals (r:1 w:0) // Storage: Treasury Approvals (r:1 w:1) fn approve_proposal(p: u32, ) -> Weight { - (13_543_000 as Weight) + (8_164_000 as Weight) // Standard Error: 1_000 - .saturating_add((55_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((57_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Treasury Approvals (r:1 w:1) - // Storage: Treasury BountyApprovals (r:1 w:1) + // Storage: Bounties BountyApprovals (r:1 w:1) // Storage: Treasury Proposals (r:2 w:2) // Storage: System Account (r:4 w:4) fn on_initialize_proposals(p: u32, ) -> Weight { - (51_708_000 as Weight) + (20_762_000 as Weight) // Standard Error: 21_000 - .saturating_add((57_926_000 as Weight).saturating_mul(p as Weight)) + .saturating_add((26_835_000 as Weight).saturating_mul(p as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(p as Weight))) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) diff --git a/frame/try-runtime/Cargo.toml b/frame/try-runtime/Cargo.toml index 905c58ab00bed..0546c0a898fb2 100644 --- a/frame/try-runtime/Cargo.toml +++ b/frame/try-runtime/Cargo.toml @@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] sp-api = { version = "4.0.0-dev", path = "../../primitives/api", default-features = false } sp-std = { version = "4.0.0", path = "../../primitives/std" , default-features = false } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" , default-features = false } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" , default-features = false } frame-support = { version = "4.0.0-dev", path = "../support", default-features = false } diff --git a/frame/uniques/Cargo.toml b/frame/uniques/Cargo.toml index 38c519f801674..4e0194b17acbc 100644 --- a/frame/uniques/Cargo.toml +++ b/frame/uniques/Cargo.toml @@ -16,7 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } @@ -24,8 +24,8 @@ log = { version = "0.4.14", default-features = false } [dev-dependencies] sp-std = { version = "4.0.0", path = "../../primitives/std" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-io = { version = "4.0.0-dev", path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../primitives/io" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } [features] diff --git a/frame/uniques/src/lib.rs b/frame/uniques/src/lib.rs index 6b05aaeec296b..2956735e5ec3e 100644 --- a/frame/uniques/src/lib.rs +++ b/frame/uniques/src/lib.rs @@ -62,7 +62,6 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] pub struct Pallet(_); #[pallet::config] @@ -72,10 +71,16 @@ pub mod pallet { type Event: From> + IsType<::Event>; /// Identifier for the class of asset. - type ClassId: Member + Parameter + Default + Copy + HasCompact; + type ClassId: Member + Parameter + Default + Copy + HasCompact + MaxEncodedLen; /// The type used to identify a unique asset within an asset class. - type InstanceId: Member + Parameter + Default + Copy + HasCompact + From; + type InstanceId: Member + + Parameter + + Default + + Copy + + HasCompact + + From + + MaxEncodedLen; /// The currency mechanism, used for paying for reserves. type Currency: ReservableCurrency; @@ -1003,21 +1008,18 @@ pub mod pallet { Ok(()) } - /// Set an attribute for an asset class or instance. + /// Clear an attribute for an asset class or instance. /// /// Origin must be either `ForceOrigin` or Signed and the sender should be the Owner of the /// asset `class`. /// - /// If the origin is Signed, then funds of signer are reserved according to the formula: - /// `MetadataDepositBase + DepositPerByte * (key.len + value.len)` taking into - /// account any already reserved funds. + /// Any deposit is freed for the asset class owner. /// - /// - `class`: The identifier of the asset class whose instance's metadata to set. - /// - `instance`: The identifier of the asset instance whose metadata to set. + /// - `class`: The identifier of the asset class whose instance's metadata to clear. + /// - `maybe_instance`: The identifier of the asset instance whose metadata to clear. /// - `key`: The key of the attribute. - /// - `value`: The value to which to set the attribute. /// - /// Emits `AttributeSet`. + /// Emits `AttributeCleared`. /// /// Weight: `O(1)` #[pallet::weight(T::WeightInfo::clear_attribute())] diff --git a/frame/uniques/src/types.rs b/frame/uniques/src/types.rs index 4d1afe694bd8d..b5aee6912fec2 100644 --- a/frame/uniques/src/types.rs +++ b/frame/uniques/src/types.rs @@ -18,7 +18,10 @@ //! Various basic types for use in the assets pallet. use super::*; -use frame_support::{traits::Get, BoundedVec}; +use frame_support::{ + pallet_prelude::{BoundedVec, MaxEncodedLen}, + traits::Get, +}; use scale_info::TypeInfo; pub(super) type DepositBalanceOf = @@ -28,7 +31,7 @@ pub(super) type ClassDetailsFor = pub(super) type InstanceDetailsFor = InstanceDetails<::AccountId, DepositBalanceOf>; -#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo)] +#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct ClassDetails { /// Can change `owner`, `issuer`, `freezer` and `admin` accounts. pub(super) owner: AccountId, @@ -54,7 +57,7 @@ pub struct ClassDetails { } /// Witness data for the destroy transactions. -#[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo)] +#[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct DestroyWitness { /// The total number of outstanding instances of this asset class. #[codec(compact)] @@ -78,7 +81,7 @@ impl ClassDetails { } /// Information concerning the ownership of a single unique asset. -#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, Default, TypeInfo)] +#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, Default, TypeInfo, MaxEncodedLen)] pub struct InstanceDetails { /// The owner of this asset. pub(super) owner: AccountId, @@ -91,8 +94,9 @@ pub struct InstanceDetails { pub(super) deposit: DepositBalance, } -#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, Default, TypeInfo)] +#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, Default, TypeInfo, MaxEncodedLen)] #[scale_info(skip_type_params(StringLimit))] +#[codec(mel_bound(DepositBalance: MaxEncodedLen))] pub struct ClassMetadata> { /// The balance deposited for this metadata. /// @@ -106,8 +110,9 @@ pub struct ClassMetadata> { pub(super) is_frozen: bool, } -#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, Default, TypeInfo)] +#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, Default, TypeInfo, MaxEncodedLen)] #[scale_info(skip_type_params(StringLimit))] +#[codec(mel_bound(DepositBalance: MaxEncodedLen))] pub struct InstanceMetadata> { /// The balance deposited for this metadata. /// diff --git a/frame/uniques/src/weights.rs b/frame/uniques/src/weights.rs index 3a67eb09017be..1df8fe0ff6650 100644 --- a/frame/uniques/src/weights.rs +++ b/frame/uniques/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_uniques //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-11-02, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/uniques/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -75,14 +76,14 @@ impl WeightInfo for SubstrateWeight { // Storage: Uniques Class (r:1 w:1) // Storage: Uniques ClassAccount (r:0 w:1) fn create() -> Weight { - (41_109_000 as Weight) + (24_063_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Uniques Class (r:1 w:1) // Storage: Uniques ClassAccount (r:0 w:1) fn force_create() -> Weight { - (22_986_000 as Weight) + (13_017_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -96,11 +97,11 @@ impl WeightInfo for SubstrateWeight { fn destroy(n: u32, m: u32, a: u32, ) -> Weight { (0 as Weight) // Standard Error: 14_000 - .saturating_add((14_879_000 as Weight).saturating_mul(n as Weight)) + .saturating_add((9_248_000 as Weight).saturating_mul(n as Weight)) // Standard Error: 14_000 - .saturating_add((1_058_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((854_000 as Weight).saturating_mul(m as Weight)) // Standard Error: 14_000 - .saturating_add((956_000 as Weight).saturating_mul(a as Weight)) + .saturating_add((758_000 as Weight).saturating_mul(a as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(n as Weight))) .saturating_add(T::DbWeight::get().writes(3 as Weight)) @@ -112,7 +113,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Uniques Class (r:1 w:1) // Storage: Uniques Account (r:0 w:1) fn mint() -> Weight { - (51_248_000 as Weight) + (29_865_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -120,7 +121,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Uniques Asset (r:1 w:1) // Storage: Uniques Account (r:0 w:1) fn burn() -> Weight { - (53_172_000 as Weight) + (31_603_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -128,7 +129,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Uniques Asset (r:1 w:1) // Storage: Uniques Account (r:0 w:2) fn transfer() -> Weight { - (39_680_000 as Weight) + (23_331_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -137,7 +138,7 @@ impl WeightInfo for SubstrateWeight { fn redeposit(i: u32, ) -> Weight { (0 as Weight) // Standard Error: 12_000 - .saturating_add((22_759_000 as Weight).saturating_mul(i as Weight)) + .saturating_add((11_527_000 as Weight).saturating_mul(i as Weight)) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(i as Weight))) .saturating_add(T::DbWeight::get().writes(1 as Weight)) @@ -146,26 +147,26 @@ impl WeightInfo for SubstrateWeight { // Storage: Uniques Asset (r:1 w:1) // Storage: Uniques Class (r:1 w:0) fn freeze() -> Weight { - (27_833_000 as Weight) + (18_617_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Uniques Asset (r:1 w:1) // Storage: Uniques Class (r:1 w:0) fn thaw() -> Weight { - (27_739_000 as Weight) + (18_618_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Uniques Class (r:1 w:1) fn freeze_class() -> Weight { - (20_890_000 as Weight) + (13_570_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Uniques Class (r:1 w:1) fn thaw_class() -> Weight { - (20_848_000 as Weight) + (13_937_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -173,20 +174,20 @@ impl WeightInfo for SubstrateWeight { // Storage: System Account (r:1 w:1) // Storage: Uniques ClassAccount (r:0 w:2) fn transfer_ownership() -> Weight { - (51_523_000 as Weight) + (31_021_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } // Storage: Uniques Class (r:1 w:1) fn set_team() -> Weight { - (22_034_000 as Weight) + (14_739_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Uniques Class (r:1 w:1) // Storage: Uniques ClassAccount (r:0 w:1) fn force_asset_status() -> Weight { - (25_877_000 as Weight) + (16_826_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -194,7 +195,7 @@ impl WeightInfo for SubstrateWeight { // Storage: Uniques InstanceMetadataOf (r:1 w:0) // Storage: Uniques Attribute (r:1 w:1) fn set_attribute() -> Weight { - (63_365_000 as Weight) + (37_010_000 as Weight) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -202,49 +203,49 @@ impl WeightInfo for SubstrateWeight { // Storage: Uniques InstanceMetadataOf (r:1 w:0) // Storage: Uniques Attribute (r:1 w:1) fn clear_attribute() -> Weight { - (56_849_000 as Weight) + (34_432_000 as Weight) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Uniques Class (r:1 w:1) // Storage: Uniques InstanceMetadataOf (r:1 w:1) fn set_metadata() -> Weight { - (47_982_000 as Weight) + (28_575_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Uniques Class (r:1 w:1) // Storage: Uniques InstanceMetadataOf (r:1 w:1) fn clear_metadata() -> Weight { - (47_340_000 as Weight) + (28_730_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Uniques Class (r:1 w:1) // Storage: Uniques ClassMetadataOf (r:1 w:1) fn set_class_metadata() -> Weight { - (46_897_000 as Weight) + (28_225_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Uniques Class (r:1 w:0) // Storage: Uniques ClassMetadataOf (r:1 w:1) fn clear_class_metadata() -> Weight { - (41_745_000 as Weight) + (26_455_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Uniques Class (r:1 w:0) // Storage: Uniques Asset (r:1 w:1) fn approve_transfer() -> Weight { - (29_828_000 as Weight) + (19_587_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: Uniques Class (r:1 w:0) // Storage: Uniques Asset (r:1 w:1) fn cancel_approval() -> Weight { - (29_759_000 as Weight) + (19_417_000 as Weight) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -255,14 +256,14 @@ impl WeightInfo for () { // Storage: Uniques Class (r:1 w:1) // Storage: Uniques ClassAccount (r:0 w:1) fn create() -> Weight { - (41_109_000 as Weight) + (24_063_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Uniques Class (r:1 w:1) // Storage: Uniques ClassAccount (r:0 w:1) fn force_create() -> Weight { - (22_986_000 as Weight) + (13_017_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -276,11 +277,11 @@ impl WeightInfo for () { fn destroy(n: u32, m: u32, a: u32, ) -> Weight { (0 as Weight) // Standard Error: 14_000 - .saturating_add((14_879_000 as Weight).saturating_mul(n as Weight)) + .saturating_add((9_248_000 as Weight).saturating_mul(n as Weight)) // Standard Error: 14_000 - .saturating_add((1_058_000 as Weight).saturating_mul(m as Weight)) + .saturating_add((854_000 as Weight).saturating_mul(m as Weight)) // Standard Error: 14_000 - .saturating_add((956_000 as Weight).saturating_mul(a as Weight)) + .saturating_add((758_000 as Weight).saturating_mul(a as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(n as Weight))) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) @@ -292,7 +293,7 @@ impl WeightInfo for () { // Storage: Uniques Class (r:1 w:1) // Storage: Uniques Account (r:0 w:1) fn mint() -> Weight { - (51_248_000 as Weight) + (29_865_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } @@ -300,7 +301,7 @@ impl WeightInfo for () { // Storage: Uniques Asset (r:1 w:1) // Storage: Uniques Account (r:0 w:1) fn burn() -> Weight { - (53_172_000 as Weight) + (31_603_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } @@ -308,7 +309,7 @@ impl WeightInfo for () { // Storage: Uniques Asset (r:1 w:1) // Storage: Uniques Account (r:0 w:2) fn transfer() -> Weight { - (39_680_000 as Weight) + (23_331_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } @@ -317,7 +318,7 @@ impl WeightInfo for () { fn redeposit(i: u32, ) -> Weight { (0 as Weight) // Standard Error: 12_000 - .saturating_add((22_759_000 as Weight).saturating_mul(i as Weight)) + .saturating_add((11_527_000 as Weight).saturating_mul(i as Weight)) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(i as Weight))) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) @@ -326,26 +327,26 @@ impl WeightInfo for () { // Storage: Uniques Asset (r:1 w:1) // Storage: Uniques Class (r:1 w:0) fn freeze() -> Weight { - (27_833_000 as Weight) + (18_617_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Uniques Asset (r:1 w:1) // Storage: Uniques Class (r:1 w:0) fn thaw() -> Weight { - (27_739_000 as Weight) + (18_618_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Uniques Class (r:1 w:1) fn freeze_class() -> Weight { - (20_890_000 as Weight) + (13_570_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Uniques Class (r:1 w:1) fn thaw_class() -> Weight { - (20_848_000 as Weight) + (13_937_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } @@ -353,20 +354,20 @@ impl WeightInfo for () { // Storage: System Account (r:1 w:1) // Storage: Uniques ClassAccount (r:0 w:2) fn transfer_ownership() -> Weight { - (51_523_000 as Weight) + (31_021_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } // Storage: Uniques Class (r:1 w:1) fn set_team() -> Weight { - (22_034_000 as Weight) + (14_739_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Uniques Class (r:1 w:1) // Storage: Uniques ClassAccount (r:0 w:1) fn force_asset_status() -> Weight { - (25_877_000 as Weight) + (16_826_000 as Weight) .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -374,7 +375,7 @@ impl WeightInfo for () { // Storage: Uniques InstanceMetadataOf (r:1 w:0) // Storage: Uniques Attribute (r:1 w:1) fn set_attribute() -> Weight { - (63_365_000 as Weight) + (37_010_000 as Weight) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -382,49 +383,49 @@ impl WeightInfo for () { // Storage: Uniques InstanceMetadataOf (r:1 w:0) // Storage: Uniques Attribute (r:1 w:1) fn clear_attribute() -> Weight { - (56_849_000 as Weight) + (34_432_000 as Weight) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Uniques Class (r:1 w:1) // Storage: Uniques InstanceMetadataOf (r:1 w:1) fn set_metadata() -> Weight { - (47_982_000 as Weight) + (28_575_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Uniques Class (r:1 w:1) // Storage: Uniques InstanceMetadataOf (r:1 w:1) fn clear_metadata() -> Weight { - (47_340_000 as Weight) + (28_730_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Uniques Class (r:1 w:1) // Storage: Uniques ClassMetadataOf (r:1 w:1) fn set_class_metadata() -> Weight { - (46_897_000 as Weight) + (28_225_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Uniques Class (r:1 w:0) // Storage: Uniques ClassMetadataOf (r:1 w:1) fn clear_class_metadata() -> Weight { - (41_745_000 as Weight) + (26_455_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Uniques Class (r:1 w:0) // Storage: Uniques Asset (r:1 w:1) fn approve_transfer() -> Weight { - (29_828_000 as Weight) + (19_587_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } // Storage: Uniques Class (r:1 w:0) // Storage: Uniques Asset (r:1 w:1) fn cancel_approval() -> Weight { - (29_759_000 as Weight) + (19_417_000 as Weight) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } diff --git a/frame/utility/Cargo.toml b/frame/utility/Cargo.toml index 85f522975dbbc..ea3977c1b8b29 100644 --- a/frame/utility/Cargo.toml +++ b/frame/utility/Cargo.toml @@ -17,15 +17,15 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } [dev-dependencies] -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } [features] diff --git a/frame/utility/src/weights.rs b/frame/utility/src/weights.rs index 15798007a9ba3..e5f3cb0f58fd4 100644 --- a/frame/utility/src/weights.rs +++ b/frame/utility/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_utility //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-10-30, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/utility/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -55,39 +56,39 @@ pub trait WeightInfo { pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { fn batch(c: u32, ) -> Weight { - (18_293_000 as Weight) - // Standard Error: 3_000 - .saturating_add((5_530_000 as Weight).saturating_mul(c as Weight)) + (18_598_000 as Weight) + // Standard Error: 1_000 + .saturating_add((2_374_000 as Weight).saturating_mul(c as Weight)) } fn as_derivative() -> Weight { - (3_387_000 as Weight) + (1_650_000 as Weight) } fn batch_all(c: u32, ) -> Weight { - (19_223_000 as Weight) - // Standard Error: 4_000 - .saturating_add((5_998_000 as Weight).saturating_mul(c as Weight)) + (13_988_000 as Weight) + // Standard Error: 1_000 + .saturating_add((2_481_000 as Weight).saturating_mul(c as Weight)) } fn dispatch_as() -> Weight { - (14_340_000 as Weight) + (8_463_000 as Weight) } } // For backwards compatibility and tests impl WeightInfo for () { fn batch(c: u32, ) -> Weight { - (18_293_000 as Weight) - // Standard Error: 3_000 - .saturating_add((5_530_000 as Weight).saturating_mul(c as Weight)) + (18_598_000 as Weight) + // Standard Error: 1_000 + .saturating_add((2_374_000 as Weight).saturating_mul(c as Weight)) } fn as_derivative() -> Weight { - (3_387_000 as Weight) + (1_650_000 as Weight) } fn batch_all(c: u32, ) -> Weight { - (19_223_000 as Weight) - // Standard Error: 4_000 - .saturating_add((5_998_000 as Weight).saturating_mul(c as Weight)) + (13_988_000 as Weight) + // Standard Error: 1_000 + .saturating_add((2_481_000 as Weight).saturating_mul(c as Weight)) } fn dispatch_as() -> Weight { - (14_340_000 as Weight) + (8_463_000 as Weight) } } diff --git a/frame/vesting/Cargo.toml b/frame/vesting/Cargo.toml index e488e282cd459..f7dcfd9fa442f 100644 --- a/frame/vesting/Cargo.toml +++ b/frame/vesting/Cargo.toml @@ -18,15 +18,15 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = ] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../support" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../system" } frame-benchmarking = { version = "4.0.0-dev", default-features = false, path = "../benchmarking", optional = true } log = { version = "0.4.0", default-features = false } [dev-dependencies] -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../primitives/io" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } pallet-balances = { version = "4.0.0-dev", path = "../balances" } [features] diff --git a/frame/vesting/src/weights.rs b/frame/vesting/src/weights.rs index 660f839655579..140c1889d6e54 100644 --- a/frame/vesting/src/weights.rs +++ b/frame/vesting/src/weights.rs @@ -1,6 +1,6 @@ // This file is part of Substrate. -// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd. +// Copyright (C) 2022 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,11 +18,11 @@ //! Autogenerated weights for pallet_vesting //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-08-10, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 +//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: -// target/release/substrate +// ./target/production/substrate // benchmark // --chain=dev // --steps=50 @@ -33,8 +33,9 @@ // --wasm-execution=compiled // --heap-pages=4096 // --output=./frame/vesting/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - +// --template=.maintain/frame-weight-template.hbs +// --header=HEADER-APACHE2 +// --raw #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -61,22 +62,22 @@ impl WeightInfo for SubstrateWeight { // Storage: Vesting Vesting (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vest_locked(l: u32, s: u32, ) -> Weight { - (50_642_000 as Weight) + (27_037_000 as Weight) // Standard Error: 1_000 - .saturating_add((144_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 3_000 - .saturating_add((177_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((88_000 as Weight).saturating_mul(l as Weight)) + // Standard Error: 2_000 + .saturating_add((69_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } // Storage: Vesting Vesting (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vest_unlocked(l: u32, s: u32, ) -> Weight { - (50_830_000 as Weight) + (26_627_000 as Weight) // Standard Error: 1_000 - .saturating_add((115_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 3_000 - .saturating_add((112_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((82_000 as Weight).saturating_mul(l as Weight)) + // Standard Error: 2_000 + .saturating_add((53_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(2 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } @@ -84,11 +85,11 @@ impl WeightInfo for SubstrateWeight { // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) fn vest_other_locked(l: u32, s: u32, ) -> Weight { - (52_151_000 as Weight) + (26_672_000 as Weight) // Standard Error: 1_000 - .saturating_add((130_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 3_000 - .saturating_add((162_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((85_000 as Weight).saturating_mul(l as Weight)) + // Standard Error: 2_000 + .saturating_add((77_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -96,11 +97,11 @@ impl WeightInfo for SubstrateWeight { // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) fn vest_other_unlocked(l: u32, s: u32, ) -> Weight { - (51_009_000 as Weight) - // Standard Error: 4_000 - .saturating_add((123_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 9_000 - .saturating_add((118_000 as Weight).saturating_mul(s as Weight)) + (26_682_000 as Weight) + // Standard Error: 1_000 + .saturating_add((74_000 as Weight).saturating_mul(l as Weight)) + // Standard Error: 2_000 + .saturating_add((51_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -108,11 +109,11 @@ impl WeightInfo for SubstrateWeight { // Storage: System Account (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vested_transfer(l: u32, s: u32, ) -> Weight { - (89_517_000 as Weight) - // Standard Error: 5_000 - .saturating_add((114_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 10_000 - .saturating_add((23_000 as Weight).saturating_mul(s as Weight)) + (42_066_000 as Weight) + // Standard Error: 1_000 + .saturating_add((83_000 as Weight).saturating_mul(l as Weight)) + // Standard Error: 3_000 + .saturating_add((43_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -120,11 +121,11 @@ impl WeightInfo for SubstrateWeight { // Storage: System Account (r:2 w:2) // Storage: Balances Locks (r:1 w:1) fn force_vested_transfer(l: u32, s: u32, ) -> Weight { - (87_903_000 as Weight) - // Standard Error: 6_000 - .saturating_add((121_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 12_000 - .saturating_add((56_000 as Weight).saturating_mul(s as Weight)) + (41_672_000 as Weight) + // Standard Error: 1_000 + .saturating_add((84_000 as Weight).saturating_mul(l as Weight)) + // Standard Error: 3_000 + .saturating_add((46_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } @@ -132,11 +133,11 @@ impl WeightInfo for SubstrateWeight { // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) fn not_unlocking_merge_schedules(l: u32, s: u32, ) -> Weight { - (54_463_000 as Weight) + (27_627_000 as Weight) + // Standard Error: 0 + .saturating_add((86_000 as Weight).saturating_mul(l as Weight)) // Standard Error: 2_000 - .saturating_add((123_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 5_000 - .saturating_add((149_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((68_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -144,11 +145,11 @@ impl WeightInfo for SubstrateWeight { // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) fn unlocking_merge_schedules(l: u32, s: u32, ) -> Weight { - (53_674_000 as Weight) + (27_143_000 as Weight) + // Standard Error: 0 + .saturating_add((88_000 as Weight).saturating_mul(l as Weight)) // Standard Error: 1_000 - .saturating_add((137_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 4_000 - .saturating_add((152_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((72_000 as Weight).saturating_mul(s as Weight)) .saturating_add(T::DbWeight::get().reads(3 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } @@ -159,22 +160,22 @@ impl WeightInfo for () { // Storage: Vesting Vesting (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vest_locked(l: u32, s: u32, ) -> Weight { - (50_642_000 as Weight) + (27_037_000 as Weight) // Standard Error: 1_000 - .saturating_add((144_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 3_000 - .saturating_add((177_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((88_000 as Weight).saturating_mul(l as Weight)) + // Standard Error: 2_000 + .saturating_add((69_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } // Storage: Vesting Vesting (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vest_unlocked(l: u32, s: u32, ) -> Weight { - (50_830_000 as Weight) + (26_627_000 as Weight) // Standard Error: 1_000 - .saturating_add((115_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 3_000 - .saturating_add((112_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((82_000 as Weight).saturating_mul(l as Weight)) + // Standard Error: 2_000 + .saturating_add((53_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(2 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } @@ -182,11 +183,11 @@ impl WeightInfo for () { // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) fn vest_other_locked(l: u32, s: u32, ) -> Weight { - (52_151_000 as Weight) + (26_672_000 as Weight) // Standard Error: 1_000 - .saturating_add((130_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 3_000 - .saturating_add((162_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((85_000 as Weight).saturating_mul(l as Weight)) + // Standard Error: 2_000 + .saturating_add((77_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } @@ -194,11 +195,11 @@ impl WeightInfo for () { // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) fn vest_other_unlocked(l: u32, s: u32, ) -> Weight { - (51_009_000 as Weight) - // Standard Error: 4_000 - .saturating_add((123_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 9_000 - .saturating_add((118_000 as Weight).saturating_mul(s as Weight)) + (26_682_000 as Weight) + // Standard Error: 1_000 + .saturating_add((74_000 as Weight).saturating_mul(l as Weight)) + // Standard Error: 2_000 + .saturating_add((51_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } @@ -206,11 +207,11 @@ impl WeightInfo for () { // Storage: System Account (r:1 w:1) // Storage: Balances Locks (r:1 w:1) fn vested_transfer(l: u32, s: u32, ) -> Weight { - (89_517_000 as Weight) - // Standard Error: 5_000 - .saturating_add((114_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 10_000 - .saturating_add((23_000 as Weight).saturating_mul(s as Weight)) + (42_066_000 as Weight) + // Standard Error: 1_000 + .saturating_add((83_000 as Weight).saturating_mul(l as Weight)) + // Standard Error: 3_000 + .saturating_add((43_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } @@ -218,11 +219,11 @@ impl WeightInfo for () { // Storage: System Account (r:2 w:2) // Storage: Balances Locks (r:1 w:1) fn force_vested_transfer(l: u32, s: u32, ) -> Weight { - (87_903_000 as Weight) - // Standard Error: 6_000 - .saturating_add((121_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 12_000 - .saturating_add((56_000 as Weight).saturating_mul(s as Weight)) + (41_672_000 as Weight) + // Standard Error: 1_000 + .saturating_add((84_000 as Weight).saturating_mul(l as Weight)) + // Standard Error: 3_000 + .saturating_add((46_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } @@ -230,11 +231,11 @@ impl WeightInfo for () { // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) fn not_unlocking_merge_schedules(l: u32, s: u32, ) -> Weight { - (54_463_000 as Weight) + (27_627_000 as Weight) + // Standard Error: 0 + .saturating_add((86_000 as Weight).saturating_mul(l as Weight)) // Standard Error: 2_000 - .saturating_add((123_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 5_000 - .saturating_add((149_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((68_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } @@ -242,11 +243,11 @@ impl WeightInfo for () { // Storage: Balances Locks (r:1 w:1) // Storage: System Account (r:1 w:1) fn unlocking_merge_schedules(l: u32, s: u32, ) -> Weight { - (53_674_000 as Weight) + (27_143_000 as Weight) + // Standard Error: 0 + .saturating_add((88_000 as Weight).saturating_mul(l as Weight)) // Standard Error: 1_000 - .saturating_add((137_000 as Weight).saturating_mul(l as Weight)) - // Standard Error: 4_000 - .saturating_add((152_000 as Weight).saturating_mul(s as Weight)) + .saturating_add((72_000 as Weight).saturating_mul(s as Weight)) .saturating_add(RocksDbWeight::get().reads(3 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } diff --git a/primitives/api/Cargo.toml b/primitives/api/Cargo.toml index f2c3e67800dc4..ab81ed85f188d 100644 --- a/primitives/api/Cargo.toml +++ b/primitives/api/Cargo.toml @@ -15,11 +15,11 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } sp-api-proc-macro = { version = "4.0.0-dev", path = "proc-macro" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../core" } +sp-core = { version = "5.0.0", default-features = false, path = "../core" } sp-std = { version = "4.0.0", default-features = false, path = "../std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../runtime" } sp-version = { version = "4.0.0-dev", default-features = false, path = "../version" } -sp-state-machine = { version = "0.10.0", optional = true, path = "../state-machine" } +sp-state-machine = { version = "0.11.0", optional = true, path = "../state-machine" } hash-db = { version = "0.15.2", optional = true } thiserror = { version = "1.0.30", optional = true } diff --git a/primitives/api/proc-macro/src/impl_runtime_apis.rs b/primitives/api/proc-macro/src/impl_runtime_apis.rs index 7241a1c2610de..f6de60e1c99b8 100644 --- a/primitives/api/proc-macro/src/impl_runtime_apis.rs +++ b/primitives/api/proc-macro/src/impl_runtime_apis.rs @@ -297,7 +297,7 @@ fn generate_runtime_api_base_structures() -> Result { let state_version = self.call .runtime_version_at(&at) .map(|v| v.state_version()) - .map_err(|e| format!("Failed to get state version: {:?}", e))?; + .map_err(|e| format!("Failed to get state version: {}", e))?; self.changes.replace(Default::default()).into_storage_changes( backend, diff --git a/primitives/api/test/Cargo.toml b/primitives/api/test/Cargo.toml index 79e302c4c065d..064e6a6c98181 100644 --- a/primitives/api/test/Cargo.toml +++ b/primitives/api/test/Cargo.toml @@ -16,11 +16,11 @@ sp-api = { version = "4.0.0-dev", path = "../" } substrate-test-runtime-client = { version = "2.0.0", path = "../../../test-utils/runtime/client" } sp-version = { version = "4.0.0-dev", path = "../../version" } sp-tracing = { version = "4.0.0", path = "../../tracing" } -sp-runtime = { version = "4.1.0-dev", path = "../../runtime" } +sp-runtime = { version = "5.0.0", path = "../../runtime" } sp-consensus = { version = "0.10.0-dev", path = "../../consensus/common" } sc-block-builder = { version = "0.10.0-dev", path = "../../../client/block-builder" } codec = { package = "parity-scale-codec", version = "2.0.0" } -sp-state-machine = { version = "0.10.0", path = "../../state-machine" } +sp-state-machine = { version = "0.11.0", path = "../../state-machine" } trybuild = "1.0.53" rustversion = "1.0.6" @@ -28,7 +28,7 @@ rustversion = "1.0.6" criterion = "0.3.0" futures = "0.3.9" log = "0.4.14" -sp-core = { version = "4.1.0-dev", path = "../../core" } +sp-core = { version = "5.0.0", path = "../../core" } [[bench]] name = "bench" diff --git a/primitives/application-crypto/Cargo.toml b/primitives/application-crypto/Cargo.toml index 75766905d14f7..818ddbdcc1824 100644 --- a/primitives/application-crypto/Cargo.toml +++ b/primitives/application-crypto/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sp-application-crypto" -version = "4.0.0" +version = "5.0.0" authors = ["Parity Technologies "] edition = "2021" description = "Provides facilities for generating application specific crypto wrapper types." @@ -15,12 +15,12 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-core = { version = "4.1.0-dev", default-features = false, path = "../core" } +sp-core = { version = "5.0.0", default-features = false, path = "../core" } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.132", optional = true, features = ["derive"] } +serde = { version = "1.0.136", optional = true, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../std" } -sp-io = { version = "4.0.0", default-features = false, path = "../io" } +sp-io = { version = "5.0.0", default-features = false, path = "../io" } [features] default = [ "std" ] diff --git a/primitives/application-crypto/test/Cargo.toml b/primitives/application-crypto/test/Cargo.toml index 178932869611f..515be41be3d2e 100644 --- a/primitives/application-crypto/test/Cargo.toml +++ b/primitives/application-crypto/test/Cargo.toml @@ -13,9 +13,9 @@ repository = "https://github.com/paritytech/substrate/" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../core" } -sp-keystore = { version = "0.10.0", path = "../../keystore", default-features = false } +sp-core = { version = "5.0.0", default-features = false, path = "../../core" } +sp-keystore = { version = "0.11.0", path = "../../keystore", default-features = false } substrate-test-runtime-client = { version = "2.0.0", path = "../../../test-utils/runtime/client" } -sp-runtime = { version = "4.1.0-dev", path = "../../runtime" } +sp-runtime = { version = "5.0.0", path = "../../runtime" } sp-api = { version = "4.0.0-dev", path = "../../api" } -sp-application-crypto = { version = "4.0.0", path = "../" } +sp-application-crypto = { version = "5.0.0", path = "../" } diff --git a/primitives/arithmetic/Cargo.toml b/primitives/arithmetic/Cargo.toml index b1ec8639248e9..e3294ff749855 100644 --- a/primitives/arithmetic/Cargo.toml +++ b/primitives/arithmetic/Cargo.toml @@ -23,7 +23,7 @@ integer-sqrt = "0.1.2" static_assertions = "1.1.0" num-traits = { version = "0.2.8", default-features = false } sp-std = { version = "4.0.0", default-features = false, path = "../std" } -serde = { version = "1.0.132", optional = true, features = ["derive"] } +serde = { version = "1.0.136", optional = true, features = ["derive"] } sp-debug-derive = { version = "4.0.0", default-features = false, path = "../debug-derive" } [dev-dependencies] diff --git a/primitives/arithmetic/src/fixed_point.rs b/primitives/arithmetic/src/fixed_point.rs index 206e63af95b1f..1c61d6c3806ae 100644 --- a/primitives/arithmetic/src/fixed_point.rs +++ b/primitives/arithmetic/src/fixed_point.rs @@ -369,6 +369,7 @@ macro_rules! implement_fixed { Default, Copy, Clone, + codec::MaxEncodedLen, PartialEq, Eq, PartialOrd, @@ -667,6 +668,15 @@ macro_rules! implement_fixed { assert!($name::DIV > 0); } + #[test] + fn has_max_encoded_len() { + struct AsMaxEncodedLen { + _data: T, + } + + let _ = AsMaxEncodedLen { _data: $name::min_value() }; + } + #[test] fn from_i129_works() { let a = I129 { value: 1, negative: true }; diff --git a/primitives/arithmetic/src/per_things.rs b/primitives/arithmetic/src/per_things.rs index 21ad0dd52099c..fbd45bb693247 100644 --- a/primitives/arithmetic/src/per_things.rs +++ b/primitives/arithmetic/src/per_things.rs @@ -425,7 +425,7 @@ macro_rules! implement_per_thing { /// #[doc = $title] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] - #[derive(Encode, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, RuntimeDebug, scale_info::TypeInfo)] + #[derive(Encode, Copy, Clone, PartialEq, Eq, codec::MaxEncodedLen, PartialOrd, Ord, RuntimeDebug, scale_info::TypeInfo)] pub struct $name($type); /// Implementation makes any compact encoding of `PerThing::Inner` valid, @@ -905,6 +905,15 @@ macro_rules! implement_per_thing { } } + #[test] + fn has_max_encoded_len() { + struct AsMaxEncodedLen { + _data: T, + } + + let _ = AsMaxEncodedLen { _data: $name(1) }; + } + #[test] fn fail_on_invalid_encoded_value() { let value = <$upper_type>::from($max) * 2; diff --git a/primitives/authority-discovery/Cargo.toml b/primitives/authority-discovery/Cargo.toml index 2fd2c48476920..7c6aa7a6ea002 100644 --- a/primitives/authority-discovery/Cargo.toml +++ b/primitives/authority-discovery/Cargo.toml @@ -13,12 +13,12 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-application-crypto = { version = "4.0.0", default-features = false, path = "../application-crypto" } +sp-application-crypto = { version = "5.0.0", default-features = false, path = "../application-crypto" } codec = { package = "parity-scale-codec", default-features = false, version = "2.0.0" } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../std" } sp-api = { version = "4.0.0-dev", default-features = false, path = "../api" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../runtime" } [features] default = ["std"] diff --git a/primitives/authorship/Cargo.toml b/primitives/authorship/Cargo.toml index 8e97942499aad..4cf8e6e9522d1 100644 --- a/primitives/authorship/Cargo.toml +++ b/primitives/authorship/Cargo.toml @@ -14,7 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] sp-inherents = { version = "4.0.0-dev", default-features = false, path = "../inherents" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../std" } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } async-trait = { version = "0.1.50", optional = true } diff --git a/primitives/beefy/Cargo.toml b/primitives/beefy/Cargo.toml index edcb2244e58fb..9d8ec2a653ea0 100644 --- a/primitives/beefy/Cargo.toml +++ b/primitives/beefy/Cargo.toml @@ -12,15 +12,15 @@ codec = { version = "2.2.0", package = "parity-scale-codec", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-api = { version = "4.0.0-dev", path = "../api", default-features = false } -sp-application-crypto = { version = "4.0.0", path = "../application-crypto", default-features = false } -sp-core = { version = "4.1.0-dev", path = "../core", default-features = false } -sp-runtime = { version = "4.1.0-dev", path = "../runtime", default-features = false } +sp-application-crypto = { version = "5.0.0", path = "../application-crypto", default-features = false } +sp-core = { version = "5.0.0", path = "../core", default-features = false } +sp-runtime = { version = "5.0.0", path = "../runtime", default-features = false } sp-std = { version = "4.0.0", path = "../std", default-features = false } [dev-dependencies] hex = "0.4.3" hex-literal = "0.3" -sp-keystore = { version = "0.10.0", path = "../keystore" } +sp-keystore = { version = "0.11.0", path = "../keystore" } [features] default = ["std"] diff --git a/primitives/beefy/src/mmr.rs b/primitives/beefy/src/mmr.rs index 215214bef2942..29f513629d012 100644 --- a/primitives/beefy/src/mmr.rs +++ b/primitives/beefy/src/mmr.rs @@ -26,7 +26,7 @@ //! but we imagine they will be useful for other chains that either want to bridge with Polkadot //! or are completely standalone, but heavily inspired by Polkadot. -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; /// A standard leaf that gets added every block to the MMR constructed by Substrate's `pallet_mmr`. @@ -81,7 +81,7 @@ impl MmrLeafVersion { } /// Details of the next BEEFY authority set. -#[derive(Debug, Default, PartialEq, Eq, Clone, Encode, Decode, TypeInfo)] +#[derive(Debug, Default, PartialEq, Eq, Clone, Encode, Decode, TypeInfo, MaxEncodedLen)] pub struct BeefyNextAuthoritySet { /// Id of the next set. /// diff --git a/primitives/block-builder/Cargo.toml b/primitives/block-builder/Cargo.toml index 5009207a3f5c3..28f76343c7e98 100644 --- a/primitives/block-builder/Cargo.toml +++ b/primitives/block-builder/Cargo.toml @@ -13,7 +13,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../runtime" } sp-api = { version = "4.0.0-dev", default-features = false, path = "../api" } sp-std = { version = "4.0.0", default-features = false, path = "../std" } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } diff --git a/primitives/blockchain/Cargo.toml b/primitives/blockchain/Cargo.toml index 366d0f3c373e2..89737dbac0c6b 100644 --- a/primitives/blockchain/Cargo.toml +++ b/primitives/blockchain/Cargo.toml @@ -21,7 +21,7 @@ thiserror = "1.0.30" futures = "0.3.9" codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } sp-consensus = { version = "0.10.0-dev", path = "../consensus/common" } -sp-runtime = { version = "4.1.0-dev", path = "../runtime" } -sp-state-machine = { version = "0.10.0", path = "../state-machine" } +sp-runtime = { version = "5.0.0", path = "../runtime" } +sp-state-machine = { version = "0.11.0", path = "../state-machine" } sp-database = { version = "4.0.0-dev", path = "../database" } sp-api = { version = "4.0.0-dev", path = "../api" } diff --git a/primitives/blockchain/src/error.rs b/primitives/blockchain/src/error.rs index bbd65e002a3b3..c82fb9bebf4ee 100644 --- a/primitives/blockchain/src/error.rs +++ b/primitives/blockchain/src/error.rs @@ -69,7 +69,7 @@ pub enum Error { ExtrinsicRootInvalid { received: String, expected: String }, // `inner` cannot be made member, since it lacks `std::error::Error` trait bounds. - #[error("Execution failed: {0:?}")] + #[error("Execution failed: {0}")] Execution(Box), #[error("Blockchain")] diff --git a/primitives/consensus/aura/Cargo.toml b/primitives/consensus/aura/Cargo.toml index f15f0008164d6..e78de2db17b39 100644 --- a/primitives/consensus/aura/Cargo.toml +++ b/primitives/consensus/aura/Cargo.toml @@ -13,12 +13,12 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-application-crypto = { version = "4.0.0", default-features = false, path = "../../application-crypto" } +sp-application-crypto = { version = "5.0.0", default-features = false, path = "../../application-crypto" } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../../std" } sp-api = { version = "4.0.0-dev", default-features = false, path = "../../api" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../runtime" } sp-inherents = { version = "4.0.0-dev", default-features = false, path = "../../inherents" } sp-timestamp = { version = "4.0.0-dev", default-features = false, path = "../../timestamp" } sp-consensus-slots = { version = "0.10.0-dev", default-features = false, path = "../slots" } diff --git a/primitives/consensus/babe/Cargo.toml b/primitives/consensus/babe/Cargo.toml index 1471ca05f591e..b677f44702849 100644 --- a/primitives/consensus/babe/Cargo.toml +++ b/primitives/consensus/babe/Cargo.toml @@ -13,7 +13,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-application-crypto = { version = "4.0.0", default-features = false, path = "../../application-crypto" } +sp-application-crypto = { version = "5.0.0", default-features = false, path = "../../application-crypto" } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } scale-info = { version = "1.0", default-features = false, features = ["derive"] } merlin = { version = "2.0", default-features = false } @@ -22,12 +22,12 @@ sp-api = { version = "4.0.0-dev", default-features = false, path = "../../api" } sp-consensus = { version = "0.10.0-dev", optional = true, path = "../common" } sp-consensus-slots = { version = "0.10.0-dev", default-features = false, path = "../slots" } sp-consensus-vrf = { version = "0.10.0-dev", path = "../vrf", default-features = false } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../core" } +sp-core = { version = "5.0.0", default-features = false, path = "../../core" } sp-inherents = { version = "4.0.0-dev", default-features = false, path = "../../inherents" } -sp-keystore = { version = "0.10.0", default-features = false, path = "../../keystore", optional = true } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../runtime" } +sp-keystore = { version = "0.11.0", default-features = false, path = "../../keystore", optional = true } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../runtime" } sp-timestamp = { version = "4.0.0-dev", path = "../../timestamp", optional = true } -serde = { version = "1.0.132", features = ["derive"], optional = true } +serde = { version = "1.0.136", features = ["derive"], optional = true } async-trait = { version = "0.1.50", optional = true } [features] diff --git a/primitives/consensus/common/Cargo.toml b/primitives/consensus/common/Cargo.toml index 93338d62cfc02..2717de72d1e31 100644 --- a/primitives/consensus/common/Cargo.toml +++ b/primitives/consensus/common/Cargo.toml @@ -20,13 +20,13 @@ codec = { package = "parity-scale-codec", version = "2.0.0", features = [ ] } futures = { version = "0.3.1", features = ["thread-pool"] } log = "0.4.8" -sp-core = { path = "../../core", version = "4.1.0-dev" } +sp-core = { path = "../../core", version = "5.0.0"} sp-inherents = { version = "4.0.0-dev", path = "../../inherents" } -sp-state-machine = { version = "0.10.0", path = "../../state-machine" } +sp-state-machine = { version = "0.11.0", path = "../../state-machine" } futures-timer = "3.0.1" sp-std = { version = "4.0.0", path = "../../std" } sp-version = { version = "4.0.0-dev", path = "../../version" } -sp-runtime = { version = "4.1.0-dev", path = "../../runtime" } +sp-runtime = { version = "5.0.0", path = "../../runtime" } thiserror = "1.0.30" [dev-dependencies] diff --git a/primitives/consensus/common/src/lib.rs b/primitives/consensus/common/src/lib.rs index 492ad83ddf5bd..edf393fa229ad 100644 --- a/primitives/consensus/common/src/lib.rs +++ b/primitives/consensus/common/src/lib.rs @@ -98,7 +98,7 @@ pub trait Environment { + Unpin + 'static; /// Error which can occur upon creation. - type Error: From + std::fmt::Debug + 'static; + type Error: From + std::error::Error + 'static; /// Initialize the proposal logic on top of a specific header. Provide /// the authorities at that header. @@ -191,7 +191,7 @@ mod private { /// Proposers are generic over bits of "consensus data" which are engine-specific. pub trait Proposer { /// Error type which can occur when proposing or evaluating. - type Error: From + std::fmt::Debug + 'static; + type Error: From + std::error::Error + 'static; /// The transaction type used by the backend. type Transaction: Default + Send + 'static; /// Future that resolves to a committed proposal with an optional proof. diff --git a/primitives/consensus/pow/Cargo.toml b/primitives/consensus/pow/Cargo.toml index 810e9c23a6599..f70af90afd6d3 100644 --- a/primitives/consensus/pow/Cargo.toml +++ b/primitives/consensus/pow/Cargo.toml @@ -15,8 +15,8 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] sp-api = { version = "4.0.0-dev", default-features = false, path = "../../api" } sp-std = { version = "4.0.0", default-features = false, path = "../../std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../runtime" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../core" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../../core" } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } [features] diff --git a/primitives/consensus/slots/Cargo.toml b/primitives/consensus/slots/Cargo.toml index ea2a862189826..18506980ae85d 100644 --- a/primitives/consensus/slots/Cargo.toml +++ b/primitives/consensus/slots/Cargo.toml @@ -16,7 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "2.2.0", default-features = false, features = ["derive", "max-encoded-len"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } serde = { version = "1.0", features = ["derive"], optional = true } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../runtime" } sp-arithmetic = { version = "4.0.0", default-features = false, path = "../../arithmetic" } [features] diff --git a/primitives/consensus/vrf/Cargo.toml b/primitives/consensus/vrf/Cargo.toml index 7504a159a3db7..3277a3ff96916 100644 --- a/primitives/consensus/vrf/Cargo.toml +++ b/primitives/consensus/vrf/Cargo.toml @@ -16,8 +16,8 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { version = "2.0.0", package = "parity-scale-codec", default-features = false } schnorrkel = { version = "0.9.1", features = ["preaudit_deprecated", "u64_backend"], default-features = false } sp-std = { version = "4.0.0", path = "../../std", default-features = false } -sp-core = { version = "4.1.0-dev", path = "../../core", default-features = false } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../runtime" } +sp-core = { version = "5.0.0", path = "../../core", default-features = false } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../runtime" } [features] default = ["std"] diff --git a/primitives/core/Cargo.toml b/primitives/core/Cargo.toml index 83228b9251ddf..bd41635a1d7a1 100644 --- a/primitives/core/Cargo.toml +++ b/primitives/core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sp-core" -version = "4.1.0-dev" +version = "5.0.0" authors = ["Parity Technologies "] edition = "2021" license = "Apache-2.0" @@ -19,12 +19,9 @@ codec = { package = "parity-scale-codec", version = "2.2.0", default-features = ] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } log = { version = "0.4.11", default-features = false } -serde = { version = "1.0.132", optional = true, features = ["derive"] } +serde = { version = "1.0.136", optional = true, features = ["derive"] } byteorder = { version = "1.3.2", default-features = false } -primitive-types = { version = "0.10.1", default-features = false, features = [ - "codec", - "scale-info" -] } +primitive-types = { version = "0.10.1", default-features = false, features = ["codec", "scale-info"] } impl-serde = { version = "0.3.0", optional = true } wasmi = { version = "0.9.1", optional = true } hash-db = { version = "0.15.2", default-features = false } @@ -41,21 +38,16 @@ lazy_static = { version = "1.4.0", default-features = false, optional = true } parking_lot = { version = "0.11.2", optional = true } sp-std = { version = "4.0.0", default-features = false, path = "../std" } sp-debug-derive = { version = "4.0.0", default-features = false, path = "../debug-derive" } -sp-storage = { version = "4.0.0", default-features = false, path = "../storage" } -sp-externalities = { version = "0.10.0", optional = true, path = "../externalities" } -parity-util-mem = { version = "0.10.2", default-features = false, features = [ - "primitive-types", -] } +sp-storage = { version = "5.0.0", default-features = false, path = "../storage" } +sp-externalities = { version = "0.11.0", optional = true, path = "../externalities" } +parity-util-mem = { version = "0.10.2", default-features = false, features = ["primitive-types"] } futures = { version = "0.3.1", optional = true } dyn-clonable = { version = "0.9.0", optional = true } thiserror = { version = "1.0.30", optional = true } bitflags = "1.3" # full crypto -ed25519-dalek = { version = "1.0.1", default-features = false, features = [ - "u64_backend", - "alloc", -], optional = true } +ed25519-dalek = { version = "1.0.1", default-features = false, features = ["u64_backend", "alloc"], optional = true } blake2-rfc = { version = "0.2.18", default-features = false, optional = true } tiny-keccak = { version = "2.0.1", features = ["keccak"], optional = true } schnorrkel = { version = "0.9.1", features = [ @@ -67,9 +59,9 @@ hex = { version = "0.4", default-features = false, optional = true } twox-hash = { version = "1.6.2", default-features = false, optional = true } libsecp256k1 = { version = "0.7", default-features = false, features = ["hmac", "static-context"], optional = true } merlin = { version = "2.0", default-features = false, optional = true } -ss58-registry = { version = "1.10.0", default-features = false } +ss58-registry = { version = "1.11.0", default-features = false } sp-core-hashing = { version = "4.0.0", path = "./hashing", default-features = false, optional = true } -sp-runtime-interface = { version = "4.1.0-dev", default-features = false, path = "../runtime-interface" } +sp-runtime-interface = { version = "5.0.0", default-features = false, path = "../runtime-interface" } [dev-dependencies] sp-serializer = { version = "4.0.0-dev", path = "../serializer" } diff --git a/primitives/core/src/crypto.rs b/primitives/core/src/crypto.rs index 41ee9466ad93b..12f8397eee4a4 100644 --- a/primitives/core/src/crypto.rs +++ b/primitives/core/src/crypto.rs @@ -478,9 +478,7 @@ pub trait Public: ByteArray + Derive + CryptoType + PartialEq + Eq + Clone + Sen } /// An opaque 32-byte cryptographic identifier. -#[derive( - Clone, Eq, PartialEq, Ord, PartialOrd, Default, Encode, Decode, MaxEncodedLen, TypeInfo, -)] +#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, MaxEncodedLen, TypeInfo)] #[cfg_attr(feature = "std", derive(Hash))] pub struct AccountId32([u8; 32]); @@ -541,9 +539,9 @@ impl<'a> sp_std::convert::TryFrom<&'a [u8]> for AccountId32 { type Error = (); fn try_from(x: &'a [u8]) -> Result { if x.len() == 32 { - let mut r = AccountId32::default(); - r.0.copy_from_slice(x); - Ok(r) + let mut data = [0; 32]; + data.copy_from_slice(x); + Ok(AccountId32(data)) } else { Err(()) } diff --git a/primitives/core/src/ecdsa.rs b/primitives/core/src/ecdsa.rs index c5e53c7029e66..4d2cae97ef14a 100644 --- a/primitives/core/src/ecdsa.rs +++ b/primitives/core/src/ecdsa.rs @@ -187,7 +187,7 @@ impl<'de> Deserialize<'de> for Public { /// A signature (a 512-bit value, plus 8 bits for recovery ID). #[cfg_attr(feature = "full_crypto", derive(Hash))] -#[derive(Encode, Decode, PassByInner, TypeInfo, PartialEq, Eq)] +#[derive(Encode, Decode, MaxEncodedLen, PassByInner, TypeInfo, PartialEq, Eq)] pub struct Signature(pub [u8; 65]); impl sp_std::convert::TryFrom<&[u8]> for Signature { diff --git a/primitives/core/src/ed25519.rs b/primitives/core/src/ed25519.rs index bb99a4ae02006..be7547201e84d 100644 --- a/primitives/core/src/ed25519.rs +++ b/primitives/core/src/ed25519.rs @@ -212,7 +212,7 @@ impl<'de> Deserialize<'de> for Public { /// A signature (a 512-bit value). #[cfg_attr(feature = "full_crypto", derive(Hash))] -#[derive(Encode, Decode, PassByInner, TypeInfo, PartialEq, Eq)] +#[derive(Encode, Decode, MaxEncodedLen, PassByInner, TypeInfo, PartialEq, Eq)] pub struct Signature(pub [u8; 64]); impl sp_std::convert::TryFrom<&[u8]> for Signature { diff --git a/primitives/core/src/sr25519.rs b/primitives/core/src/sr25519.rs index 4094c4d1b4405..5e18e02c0ffd8 100644 --- a/primitives/core/src/sr25519.rs +++ b/primitives/core/src/sr25519.rs @@ -212,7 +212,7 @@ impl<'de> Deserialize<'de> for Public { /// /// Instead of importing it for the local module, alias it to be available as a public type #[cfg_attr(feature = "full_crypto", derive(Hash))] -#[derive(Encode, Decode, PassByInner, TypeInfo, PartialEq, Eq)] +#[derive(Encode, Decode, MaxEncodedLen, PassByInner, TypeInfo, PartialEq, Eq)] pub struct Signature(pub [u8; 64]); impl sp_std::convert::TryFrom<&[u8]> for Signature { diff --git a/primitives/externalities/Cargo.toml b/primitives/externalities/Cargo.toml index 6c26b436796ee..7b7beb51e7809 100644 --- a/primitives/externalities/Cargo.toml +++ b/primitives/externalities/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sp-externalities" -version = "0.10.0" +version = "0.11.0" license = "Apache-2.0" authors = ["Parity Technologies "] edition = "2021" @@ -14,7 +14,7 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-storage = { version = "4.0.0", path = "../storage", default-features = false } +sp-storage = { version = "5.0.0", path = "../storage", default-features = false } sp-std = { version = "4.0.0", path = "../std", default-features = false } environmental = { version = "1.1.3", default-features = false } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } diff --git a/primitives/finality-grandpa/Cargo.toml b/primitives/finality-grandpa/Cargo.toml index e36c088c35838..a05636d44a563 100644 --- a/primitives/finality-grandpa/Cargo.toml +++ b/primitives/finality-grandpa/Cargo.toml @@ -19,12 +19,12 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = scale-info = { version = "1.0", default-features = false, features = ["derive"] } grandpa = { package = "finality-grandpa", version = "0.14.1", default-features = false, features = ["derive-codec"] } log = { version = "0.4.8", optional = true } -serde = { version = "1.0.132", optional = true, features = ["derive"] } +serde = { version = "1.0.136", optional = true, features = ["derive"] } sp-api = { version = "4.0.0-dev", default-features = false, path = "../api" } -sp-application-crypto = { version = "4.0.0", default-features = false, path = "../application-crypto" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../core" } -sp-keystore = { version = "0.10.0", default-features = false, path = "../keystore", optional = true } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../runtime" } +sp-application-crypto = { version = "5.0.0", default-features = false, path = "../application-crypto" } +sp-core = { version = "5.0.0", default-features = false, path = "../core" } +sp-keystore = { version = "0.11.0", default-features = false, path = "../keystore", optional = true } +sp-runtime = { version = "5.0.0", default-features = false, path = "../runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../std" } [features] diff --git a/primitives/inherents/Cargo.toml b/primitives/inherents/Cargo.toml index 02f084b6e6342..f78f4aea14e47 100644 --- a/primitives/inherents/Cargo.toml +++ b/primitives/inherents/Cargo.toml @@ -16,8 +16,8 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] sp-std = { version = "4.0.0", default-features = false, path = "../std" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../core" } -sp-runtime = { version = "4.1.0-dev", path = "../runtime", optional = true } +sp-core = { version = "5.0.0", default-features = false, path = "../core" } +sp-runtime = { version = "5.0.0", path = "../runtime", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } thiserror = { version = "1.0.30", optional = true } impl-trait-for-tuples = "0.2.0" diff --git a/primitives/io/Cargo.toml b/primitives/io/Cargo.toml index ee3c9e8945eb2..b9cbdbaa70e77 100644 --- a/primitives/io/Cargo.toml +++ b/primitives/io/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sp-io" -version = "4.0.0" +version = "5.0.0" authors = ["Parity Technologies "] edition = "2021" license = "Apache-2.0" @@ -17,15 +17,15 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } hash-db = { version = "0.15.2", default-features = false } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../core" } -sp-keystore = { version = "0.10.0", default-features = false, optional = true, path = "../keystore" } +sp-core = { version = "5.0.0", default-features = false, path = "../core" } +sp-keystore = { version = "0.11.0", default-features = false, optional = true, path = "../keystore" } sp-std = { version = "4.0.0", default-features = false, path = "../std" } libsecp256k1 = { version = "0.7", optional = true } -sp-state-machine = { version = "0.10.0", optional = true, path = "../state-machine" } -sp-wasm-interface = { version = "4.1.0-dev", path = "../wasm-interface", default-features = false } -sp-runtime-interface = { version = "4.1.0-dev", default-features = false, path = "../runtime-interface" } -sp-trie = { version = "4.0.0", optional = true, path = "../trie" } -sp-externalities = { version = "0.10.0", optional = true, path = "../externalities" } +sp-state-machine = { version = "0.11.0", optional = true, path = "../state-machine" } +sp-wasm-interface = { version = "5.0.0", path = "../wasm-interface", default-features = false } +sp-runtime-interface = { version = "5.0.0", default-features = false, path = "../runtime-interface" } +sp-trie = { version = "5.0.0", optional = true, path = "../trie" } +sp-externalities = { version = "0.11.0", optional = true, path = "../externalities" } sp-tracing = { version = "4.0.0", default-features = false, path = "../tracing" } log = { version = "0.4.8", optional = true } futures = { version = "0.3.1", features = ["thread-pool"], optional = true } @@ -66,3 +66,22 @@ with-tracing = [ disable_panic_handler = [] disable_oom = [] disable_allocator = [] + +# This feature flag controls the runtime's behavior when encountering +# a panic or when it runs out of memory, improving the diagnostics. +# +# When enabled the runtime will marshal the relevant error message +# to the host through the `PanicHandler::abort_on_panic` runtime interface. +# This gives the caller direct programmatic access to the error message. +# +# When disabled the error message will only be printed out in the +# logs, with the caller receving a generic "wasm `unreachable` instruction executed" +# error message. +# +# This has no effect if both `disable_panic_handler` and `disable_oom` +# are enabled. +# +# WARNING: Enabling this feature flag requires the `PanicHandler::abort_on_panic` +# host function to be supported by the host. Do *not* enable it for your +# runtime without first upgrading your host client! +improved_panic_error_reporting = [] diff --git a/primitives/io/src/lib.rs b/primitives/io/src/lib.rs index 29f1887bfcd9b..db86fe0964156 100644 --- a/primitives/io/src/lib.rs +++ b/primitives/io/src/lib.rs @@ -202,7 +202,7 @@ pub trait Storage { /// The hashing algorithm is defined by the `Block`. /// /// Returns a `Vec` that holds the SCALE encoded hash. - #[version(2, register_only)] + #[version(2)] fn root(&mut self, version: StateVersion) -> Vec { self.storage_root(version) } @@ -394,7 +394,7 @@ pub trait DefaultChildStorage { /// The hashing algorithm is defined by the `Block`. /// /// Returns a `Vec` that holds the SCALE encoded hash. - #[version(2, register_only)] + #[version(2)] fn root(&mut self, storage_key: &[u8], version: StateVersion) -> Vec { let child_info = ChildInfo::new_default(storage_key); self.child_storage_root(&child_info, version) @@ -418,7 +418,7 @@ pub trait Trie { } /// A trie root formed from the iterated items. - #[version(2, register_only)] + #[version(2)] fn blake2_256_root(input: Vec<(Vec, Vec)>, version: StateVersion) -> H256 { match version { StateVersion::V0 => LayoutV0::::trie_root(input), @@ -432,7 +432,7 @@ pub trait Trie { } /// A trie root formed from the enumerated items. - #[version(2, register_only)] + #[version(2)] fn blake2_256_ordered_root(input: Vec>, version: StateVersion) -> H256 { match version { StateVersion::V0 => LayoutV0::::ordered_trie_root(input), @@ -446,7 +446,7 @@ pub trait Trie { } /// A trie root formed from the iterated items. - #[version(2, register_only)] + #[version(2)] fn keccak_256_root(input: Vec<(Vec, Vec)>, version: StateVersion) -> H256 { match version { StateVersion::V0 => LayoutV0::::trie_root(input), @@ -460,7 +460,7 @@ pub trait Trie { } /// A trie root formed from the enumerated items. - #[version(2, register_only)] + #[version(2)] fn keccak_256_ordered_root(input: Vec>, version: StateVersion) -> H256 { match version { StateVersion::V0 => LayoutV0::::ordered_trie_root(input), @@ -479,7 +479,7 @@ pub trait Trie { } /// Verify trie proof - #[version(2, register_only)] + #[version(2)] fn blake2_256_verify_proof( root: H256, proof: &[Vec], @@ -516,7 +516,7 @@ pub trait Trie { } /// Verify trie proof - #[version(2, register_only)] + #[version(2)] fn keccak_256_verify_proof( root: H256, proof: &[Vec], @@ -1290,6 +1290,17 @@ pub trait Allocator { } } +/// WASM-only interface which allows for aborting the execution in case +/// of an unrecoverable error. +#[runtime_interface(wasm_only)] +pub trait PanicHandler { + /// Aborts the current execution with the given error message. + #[trap_on_return] + fn abort_on_panic(&mut self, message: &str) { + self.register_panic_error_message(message); + } +} + /// Interface that provides functions for logging from within the runtime. #[runtime_interface] pub trait Logging { @@ -1588,14 +1599,14 @@ pub trait RuntimeTasks { } /// Allocator used by Substrate when executing the Wasm runtime. -#[cfg(not(feature = "std"))] +#[cfg(all(target_arch = "wasm32", not(feature = "std")))] struct WasmAllocator; -#[cfg(all(not(feature = "disable_allocator"), not(feature = "std")))] +#[cfg(all(target_arch = "wasm32", not(feature = "disable_allocator"), not(feature = "std")))] #[global_allocator] static ALLOCATOR: WasmAllocator = WasmAllocator; -#[cfg(not(feature = "std"))] +#[cfg(all(target_arch = "wasm32", not(feature = "std")))] mod allocator_impl { use super::*; use core::alloc::{GlobalAlloc, Layout}; @@ -1617,16 +1628,30 @@ mod allocator_impl { #[no_mangle] pub fn panic(info: &core::panic::PanicInfo) -> ! { let message = sp_std::alloc::format!("{}", info); - logging::log(LogLevel::Error, "runtime", message.as_bytes()); - unsafe { core::arch::wasm32::unreachable() }; + #[cfg(feature = "improved_panic_error_reporting")] + { + panic_handler::abort_on_panic(&message); + } + #[cfg(not(feature = "improved_panic_error_reporting"))] + { + logging::log(LogLevel::Error, "runtime", message.as_bytes()); + core::arch::wasm32::unreachable(); + } } /// A default OOM handler for WASM environment. #[cfg(all(not(feature = "disable_oom"), not(feature = "std")))] #[alloc_error_handler] pub fn oom(_: core::alloc::Layout) -> ! { - logging::log(LogLevel::Error, "runtime", b"Runtime memory exhausted. Aborting"); - unsafe { core::arch::wasm32::unreachable() }; + #[cfg(feature = "improved_panic_error_reporting")] + { + panic_handler::abort_on_panic("Runtime memory exhausted."); + } + #[cfg(not(feature = "improved_panic_error_reporting"))] + { + logging::log(LogLevel::Error, "runtime", b"Runtime memory exhausted. Aborting"); + core::arch::wasm32::unreachable(); + } } /// Type alias for Externalities implementation used in tests. @@ -1646,6 +1671,7 @@ pub type SubstrateHostFunctions = ( crypto::HostFunctions, hashing::HostFunctions, allocator::HostFunctions, + panic_handler::HostFunctions, logging::HostFunctions, sandbox::HostFunctions, crate::trie::HostFunctions, diff --git a/primitives/keyring/Cargo.toml b/primitives/keyring/Cargo.toml index a457f4983c163..5cf8a574505aa 100644 --- a/primitives/keyring/Cargo.toml +++ b/primitives/keyring/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sp-keyring" -version = "4.1.0-dev" +version = "5.0.0" authors = ["Parity Technologies "] edition = "2021" license = "Apache-2.0" @@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-core = { version = "4.1.0-dev", path = "../core" } -sp-runtime = { version = "4.1.0-dev", path = "../runtime" } +sp-core = { version = "5.0.0", path = "../core" } +sp-runtime = { version = "5.0.0", path = "../runtime" } lazy_static = "1.4.0" -strum = { version = "0.22.0", features = ["derive"] } +strum = { version = "0.23.0", features = ["derive"] } diff --git a/primitives/keystore/Cargo.toml b/primitives/keystore/Cargo.toml index e918f5d2c6d75..26748d3227d6f 100644 --- a/primitives/keystore/Cargo.toml +++ b/primitives/keystore/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sp-keystore" -version = "0.10.0" +version = "0.11.0" authors = ["Parity Technologies "] edition = "2021" license = "Apache-2.0" @@ -14,21 +14,21 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] async-trait = "0.1.50" -derive_more = "0.99.16" +futures = "0.3.1" +parking_lot = { version = "0.11.2", default-features = false } +serde = { version = "1.0", optional = true } +thiserror = "1.0" + codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } -futures = { version = "0.3.1" } schnorrkel = { version = "0.9.1", features = ["preaudit_deprecated", "u64_backend"], default-features = false } merlin = { version = "2.0", default-features = false } -parking_lot = { version = "0.11.2", default-features = false } -serde = { version = "1.0", optional = true} -sp-core = { version = "4.1.0-dev", path = "../core" } -sp-externalities = { version = "0.10.0", path = "../externalities", default-features = false } +sp-core = { version = "5.0.0", path = "../core" } +sp-externalities = { version = "0.11.0", path = "../externalities", default-features = false } [dev-dependencies] rand = "0.7.2" rand_chacha = "0.2.2" - [features] default = ["std"] std = [ diff --git a/primitives/keystore/src/lib.rs b/primitives/keystore/src/lib.rs index 6c27e3df7ce0d..6540e71bc3fe0 100644 --- a/primitives/keystore/src/lib.rs +++ b/primitives/keystore/src/lib.rs @@ -29,19 +29,19 @@ use sp_core::{ use std::sync::Arc; /// CryptoStore error -#[derive(Debug, derive_more::Display)] +#[derive(Debug, thiserror::Error)] pub enum Error { /// Public key type is not supported - #[display(fmt = "Key not supported: {:?}", _0)] + #[error("Key not supported: {0:?}")] KeyNotSupported(KeyTypeId), /// Validation error - #[display(fmt = "Validation error: {}", _0)] + #[error("Validation error: {0}")] ValidationError(String), /// Keystore unavailable - #[display(fmt = "Keystore unavailable")] + #[error("Keystore unavailable")] Unavailable, /// Programming errors - #[display(fmt = "An unknown keystore error occurred: {}", _0)] + #[error("An unknown keystore error occurred: {0}")] Other(String), } diff --git a/primitives/maybe-compressed-blob/Cargo.toml b/primitives/maybe-compressed-blob/Cargo.toml index dbed41571b149..d8814356df4bb 100644 --- a/primitives/maybe-compressed-blob/Cargo.toml +++ b/primitives/maybe-compressed-blob/Cargo.toml @@ -11,4 +11,5 @@ documentation = "https://docs.rs/sp-maybe-compressed-blob" readme = "README.md" [dependencies] +thiserror = "1.0" zstd = { version = "0.9.0", default-features = false } diff --git a/primitives/maybe-compressed-blob/src/lib.rs b/primitives/maybe-compressed-blob/src/lib.rs index 402ed90be21ca..99c12ed39bc04 100644 --- a/primitives/maybe-compressed-blob/src/lib.rs +++ b/primitives/maybe-compressed-blob/src/lib.rs @@ -18,7 +18,10 @@ //! Handling of blobs that may be compressed, based on an 8-byte magic identifier //! at the head. -use std::{borrow::Cow, io::Read}; +use std::{ + borrow::Cow, + io::{Read, Write}, +}; // An arbitrary prefix, that indicates a blob beginning with should be decompressed with // Zstd compression. @@ -34,25 +37,16 @@ const ZSTD_PREFIX: [u8; 8] = [82, 188, 83, 118, 70, 219, 142, 5]; pub const CODE_BLOB_BOMB_LIMIT: usize = 50 * 1024 * 1024; /// A possible bomb was encountered. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, thiserror::Error)] pub enum Error { /// Decoded size was too large, and the code payload may be a bomb. + #[error("Possible compression bomb encountered")] PossibleBomb, /// The compressed value had an invalid format. + #[error("Blob had invalid format")] Invalid, } -impl std::fmt::Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match *self { - Error::PossibleBomb => write!(f, "Possible compression bomb encountered"), - Error::Invalid => write!(f, "Blob had invalid format"), - } - } -} - -impl std::error::Error for Error {} - fn read_from_decoder( decoder: impl Read, blob_len: usize, @@ -90,8 +84,6 @@ pub fn decompress(blob: &[u8], bomb_limit: usize) -> Result, Error> { /// this will not compress the blob, as the decoder will not be able to be /// able to differentiate it from a compression bomb. pub fn compress(blob: &[u8], bomb_limit: usize) -> Option> { - use std::io::Write; - if blob.len() > bomb_limit { return None } @@ -109,7 +101,6 @@ pub fn compress(blob: &[u8], bomb_limit: usize) -> Option> { #[cfg(test)] mod tests { use super::*; - use std::io::Write; const BOMB_LIMIT: usize = 10; diff --git a/primitives/npos-elections/Cargo.toml b/primitives/npos-elections/Cargo.toml index 062f786aaef1c..88475e10f732c 100644 --- a/primitives/npos-elections/Cargo.toml +++ b/primitives/npos-elections/Cargo.toml @@ -15,12 +15,12 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.132", optional = true, features = ["derive"] } +serde = { version = "1.0.136", optional = true, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../std" } sp-npos-elections-solution-type = { version = "4.0.0-dev", path = "./solution-type" } sp-arithmetic = { version = "4.0.0", default-features = false, path = "../arithmetic" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../core" } -sp-runtime = { version = "4.1.0-dev", path = "../runtime", default-features = false } +sp-core = { version = "5.0.0", default-features = false, path = "../core" } +sp-runtime = { version = "5.0.0", path = "../runtime", default-features = false } [dev-dependencies] substrate-test-utils = { version = "4.0.0-dev", path = "../../test-utils" } diff --git a/primitives/npos-elections/fuzzer/Cargo.toml b/primitives/npos-elections/fuzzer/Cargo.toml index 17423b624760e..335195e9bf5b1 100644 --- a/primitives/npos-elections/fuzzer/Cargo.toml +++ b/primitives/npos-elections/fuzzer/Cargo.toml @@ -14,13 +14,14 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [dependencies] +clap = { version = "3.0", features = ["derive"] } +honggfuzz = "0.5" +rand = { version = "0.8", features = ["std", "small_rng"] } + codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -honggfuzz = "0.5" -rand = { version = "0.7.3", features = ["std", "small_rng"] } sp-npos-elections = { version = "4.0.0-dev", path = ".." } -sp-runtime = { version = "4.1.0-dev", path = "../../runtime" } -structopt = "0.3.25" +sp-runtime = { version = "5.0.0", path = "../../runtime" } [[bin]] name = "reduce" diff --git a/primitives/npos-elections/fuzzer/src/common.rs b/primitives/npos-elections/fuzzer/src/common.rs index 7ca66f72dd92b..1bef899d5e54c 100644 --- a/primitives/npos-elections/fuzzer/src/common.rs +++ b/primitives/npos-elections/fuzzer/src/common.rs @@ -68,7 +68,7 @@ pub fn generate_random_npos_inputs( // always generate a sensible desired number of candidates: elections are uninteresting if we // desire 0 candidates, or a number of candidates >= the actual number of candidates present - let rounds = rng.gen_range(1, candidate_count); + let rounds = rng.gen_range(1..candidate_count); // candidates are easy: just a completely random set of IDs let mut candidates: Vec = Vec::with_capacity(candidate_count); @@ -95,7 +95,7 @@ pub fn generate_random_npos_inputs( let vote_weight = rng.gen(); // it's not interesting if a voter chooses 0 or all candidates, so rule those cases out. - let n_candidates_chosen = rng.gen_range(1, candidates.len()); + let n_candidates_chosen = rng.gen_range(1..candidates.len()); let mut chosen_candidates = Vec::with_capacity(n_candidates_chosen); chosen_candidates.extend(candidates.choose_multiple(&mut rng, n_candidates_chosen)); @@ -132,25 +132,25 @@ pub fn generate_random_npos_result( (1..=target_count).for_each(|acc| { candidates.push(acc); - let stake_var = rng.gen_range(ed, 100 * ed); + let stake_var = rng.gen_range(ed..100 * ed); stake_of.insert(acc, base_stake + stake_var); }); let mut voters = Vec::with_capacity(voter_count as usize); (prefix..=(prefix + voter_count)).for_each(|acc| { - let edge_per_this_voter = rng.gen_range(1, candidates.len()); + let edge_per_this_voter = rng.gen_range(1..candidates.len()); // all possible targets let mut all_targets = candidates.clone(); // we remove and pop into `targets` `edge_per_this_voter` times. let targets = (0..edge_per_this_voter) .map(|_| { let upper = all_targets.len() - 1; - let idx = rng.gen_range(0, upper); + let idx = rng.gen_range(0..upper); all_targets.remove(idx) }) .collect::>(); - let stake_var = rng.gen_range(ed, 100 * ed); + let stake_var = rng.gen_range(ed..100 * ed); let stake = base_stake + stake_var; stake_of.insert(acc, stake); voters.push((acc, stake, targets)); @@ -158,20 +158,10 @@ pub fn generate_random_npos_result( ( match election_type { - ElectionType::Phragmen(conf) => seq_phragmen::( - to_elect, - candidates.clone(), - voters.clone(), - conf, - ) - .unwrap(), - ElectionType::Phragmms(conf) => phragmms::( - to_elect, - candidates.clone(), - voters.clone(), - conf, - ) - .unwrap(), + ElectionType::Phragmen(conf) => + seq_phragmen(to_elect, candidates.clone(), voters.clone(), conf).unwrap(), + ElectionType::Phragmms(conf) => + phragmms(to_elect, candidates.clone(), voters.clone(), conf).unwrap(), }, candidates, voters, diff --git a/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs b/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs index 2af6a4c0f8151..8f782405df527 100644 --- a/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs +++ b/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs @@ -24,7 +24,7 @@ use honggfuzz::fuzz; use rand::{self, SeedableRng}; use sp_npos_elections::{ assignment_ratio_to_staked_normalized, is_score_better, seq_phragmen, to_supports, - EvaluateSupport, VoteWeight, + ElectionResult, EvaluateSupport, VoteWeight, }; use sp_runtime::Perbill; @@ -68,13 +68,8 @@ fn main() { }; if iterations > 0 { - let balanced = seq_phragmen::( - to_elect, - candidates, - voters, - Some((iterations, 0)), - ) - .unwrap(); + let balanced: ElectionResult = + seq_phragmen(to_elect, candidates, voters, Some((iterations, 0))).unwrap(); let balanced_score = { let staked = assignment_ratio_to_staked_normalized( diff --git a/primitives/npos-elections/fuzzer/src/phragmen_pjr.rs b/primitives/npos-elections/fuzzer/src/phragmen_pjr.rs index 59763a58686dd..2396fdfa3b40e 100644 --- a/primitives/npos-elections/fuzzer/src/phragmen_pjr.rs +++ b/primitives/npos-elections/fuzzer/src/phragmen_pjr.rs @@ -42,7 +42,7 @@ use honggfuzz::fuzz; #[cfg(not(fuzzing))] -use structopt::StructOpt; +use clap::Parser; mod common; use common::{generate_random_npos_inputs, to_range}; @@ -67,24 +67,25 @@ fn main() { } #[cfg(not(fuzzing))] -#[derive(Debug, StructOpt)] +#[derive(Debug, Parser)] +#[clap(author, version, about)] struct Opt { /// How many candidates participate in this election - #[structopt(short, long)] + #[clap(short, long)] candidates: Option, /// How many voters participate in this election - #[structopt(short, long)] + #[clap(short, long)] voters: Option, /// Random seed to use in this election - #[structopt(long)] + #[clap(long)] seed: Option, } #[cfg(not(fuzzing))] fn main() { - let opt = Opt::from_args(); + let opt = Opt::parse(); // candidates and voters by default use the maxima, which turn out to be one less than // the constant. iteration( diff --git a/primitives/npos-elections/fuzzer/src/phragmms_balancing.rs b/primitives/npos-elections/fuzzer/src/phragmms_balancing.rs index 0cd49c3f80442..f2b12b137883c 100644 --- a/primitives/npos-elections/fuzzer/src/phragmms_balancing.rs +++ b/primitives/npos-elections/fuzzer/src/phragmms_balancing.rs @@ -23,8 +23,8 @@ use common::*; use honggfuzz::fuzz; use rand::{self, SeedableRng}; use sp_npos_elections::{ - assignment_ratio_to_staked_normalized, is_score_better, phragmms, to_supports, EvaluateSupport, - VoteWeight, + assignment_ratio_to_staked_normalized, is_score_better, phragmms, to_supports, ElectionResult, + EvaluateSupport, VoteWeight, }; use sp_runtime::Perbill; @@ -67,13 +67,8 @@ fn main() { score }; - let balanced = phragmms::( - to_elect, - candidates, - voters, - Some((iterations, 0)), - ) - .unwrap(); + let balanced: ElectionResult = + phragmms(to_elect, candidates, voters, Some((iterations, 0))).unwrap(); let balanced_score = { let staked = diff --git a/primitives/npos-elections/fuzzer/src/reduce.rs b/primitives/npos-elections/fuzzer/src/reduce.rs index ad3f7dc260ef5..a77b40ca56d54 100644 --- a/primitives/npos-elections/fuzzer/src/reduce.rs +++ b/primitives/npos-elections/fuzzer/src/reduce.rs @@ -79,8 +79,7 @@ fn generate_random_phragmen_assignment( let mut targets_to_chose_from = all_targets.clone(); let targets_to_chose = if edge_per_voter_var > 0 { rng.gen_range( - avg_edge_per_voter - edge_per_voter_var, - avg_edge_per_voter + edge_per_voter_var, + avg_edge_per_voter - edge_per_voter_var..avg_edge_per_voter + edge_per_voter_var, ) } else { avg_edge_per_voter @@ -89,11 +88,11 @@ fn generate_random_phragmen_assignment( let distribution = (0..targets_to_chose) .map(|_| { let target = - targets_to_chose_from.remove(rng.gen_range(0, targets_to_chose_from.len())); + targets_to_chose_from.remove(rng.gen_range(0..targets_to_chose_from.len())); if winners.iter().all(|w| *w != target) { winners.push(target.clone()); } - (target, rng.gen_range(1 * KSM, 100 * KSM)) + (target, rng.gen_range(1 * KSM..100 * KSM)) }) .collect::>(); diff --git a/primitives/npos-elections/src/lib.rs b/primitives/npos-elections/src/lib.rs index bb1c38d3077c4..7b3b09a4c7346 100644 --- a/primitives/npos-elections/src/lib.rs +++ b/primitives/npos-elections/src/lib.rs @@ -471,7 +471,7 @@ pub fn is_score_better(this: ElectionScore, that: ElectionScore, ep /// - It drops duplicate targets within a voter. pub fn setup_inputs( initial_candidates: Vec, - initial_voters: Vec<(AccountId, VoteWeight, Vec)>, + initial_voters: Vec<(AccountId, VoteWeight, impl IntoIterator)>, ) -> (Vec>, Vec>) { // used to cache and access candidates index. let mut c_idx_cache = BTreeMap::::new(); @@ -496,7 +496,7 @@ pub fn setup_inputs( let voters = initial_voters .into_iter() .filter_map(|(who, voter_stake, votes)| { - let mut edges: Vec> = Vec::with_capacity(votes.len()); + let mut edges: Vec> = Vec::new(); for v in votes { if edges.iter().any(|e| e.who == v) { // duplicate edge. diff --git a/primitives/npos-elections/src/mock.rs b/primitives/npos-elections/src/mock.rs index 8e8e7ebc1c0c6..85c970d7b418f 100644 --- a/primitives/npos-elections/src/mock.rs +++ b/primitives/npos-elections/src/mock.rs @@ -344,7 +344,7 @@ pub(crate) fn run_and_compare( FS: Fn(&AccountId) -> VoteWeight, { // run fixed point code. - let ElectionResult { winners, assignments } = seq_phragmen::<_, Output>( + let ElectionResult::<_, Output> { winners, assignments } = seq_phragmen( to_elect, candidates.clone(), voters diff --git a/primitives/npos-elections/src/phragmen.rs b/primitives/npos-elections/src/phragmen.rs index c582c5910d69a..e8e925935f774 100644 --- a/primitives/npos-elections/src/phragmen.rs +++ b/primitives/npos-elections/src/phragmen.rs @@ -70,7 +70,7 @@ const DEN: ExtendedBalance = ExtendedBalance::max_value(); pub fn seq_phragmen( to_elect: usize, candidates: Vec, - voters: Vec<(AccountId, VoteWeight, Vec)>, + voters: Vec<(AccountId, VoteWeight, impl IntoIterator)>, balancing: Option<(usize, ExtendedBalance)>, ) -> Result, crate::Error> { let (candidates, voters) = setup_inputs(candidates, voters); diff --git a/primitives/npos-elections/src/phragmms.rs b/primitives/npos-elections/src/phragmms.rs index 7c51da9ee92e0..6220cacd157b2 100644 --- a/primitives/npos-elections/src/phragmms.rs +++ b/primitives/npos-elections/src/phragmms.rs @@ -44,7 +44,7 @@ use sp_std::{prelude::*, rc::Rc}; pub fn phragmms( to_elect: usize, candidates: Vec, - voters: Vec<(AccountId, VoteWeight, Vec)>, + voters: Vec<(AccountId, VoteWeight, impl IntoIterator)>, balancing: Option<(usize, ExtendedBalance)>, ) -> Result, crate::Error> { let (candidates, mut voters) = setup_inputs(candidates, voters); @@ -351,8 +351,8 @@ mod tests { let candidates = vec![1, 2, 3]; let voters = vec![(10, 10, vec![1, 2]), (20, 20, vec![1, 3]), (30, 30, vec![2, 3])]; - let ElectionResult { winners, assignments } = - phragmms::<_, Perbill>(2, candidates, voters, Some((2, 0))).unwrap(); + let ElectionResult::<_, Perbill> { winners, assignments } = + phragmms(2, candidates, voters, Some((2, 0))).unwrap(); assert_eq!(winners, vec![(3, 30), (2, 30)]); assert_eq!( assignments, @@ -383,8 +383,8 @@ mod tests { (130, 1000, vec![61, 71]), ]; - let ElectionResult { winners, assignments: _ } = - phragmms::<_, Perbill>(4, candidates, voters, Some((2, 0))).unwrap(); + let ElectionResult::<_, Perbill> { winners, assignments: _ } = + phragmms(4, candidates, voters, Some((2, 0))).unwrap(); assert_eq!(winners, vec![(11, 3000), (31, 2000), (51, 1500), (61, 1500),]); } @@ -396,8 +396,8 @@ mod tests { // give a bit more to 1 and 3. voters.push((2, u64::MAX, vec![1, 3])); - let ElectionResult { winners, assignments: _ } = - phragmms::<_, Perbill>(2, candidates, voters, Some((2, 0))).unwrap(); + let ElectionResult::<_, Perbill> { winners, assignments: _ } = + phragmms(2, candidates, voters, Some((2, 0))).unwrap(); assert_eq!(winners.into_iter().map(|(w, _)| w).collect::>(), vec![1u32, 3]); } } diff --git a/primitives/npos-elections/src/tests.rs b/primitives/npos-elections/src/tests.rs index e7d0078b1fbe0..c6748b29e9851 100644 --- a/primitives/npos-elections/src/tests.rs +++ b/primitives/npos-elections/src/tests.rs @@ -230,7 +230,7 @@ fn phragmen_poc_works() { let voters = vec![(10, vec![1, 2]), (20, vec![1, 3]), (30, vec![2, 3])]; let stake_of = create_stake_of(&[(10, 10), (20, 20), (30, 30)]); - let ElectionResult { winners, assignments } = seq_phragmen::<_, Perbill>( + let ElectionResult::<_, Perbill> { winners, assignments } = seq_phragmen( 2, candidates, voters @@ -285,7 +285,7 @@ fn phragmen_poc_works_with_balancing() { let voters = vec![(10, vec![1, 2]), (20, vec![1, 3]), (30, vec![2, 3])]; let stake_of = create_stake_of(&[(10, 10), (20, 20), (30, 30)]); - let ElectionResult { winners, assignments } = seq_phragmen::<_, Perbill>( + let ElectionResult::<_, Perbill> { winners, assignments } = seq_phragmen( 2, candidates, voters @@ -372,7 +372,7 @@ fn phragmen_accuracy_on_large_scale_only_candidates() { (5, (u64::MAX - 2).into()), ]); - let ElectionResult { winners, assignments } = seq_phragmen::<_, Perbill>( + let ElectionResult::<_, Perbill> { winners, assignments } = seq_phragmen( 2, candidates.clone(), auto_generate_self_voters(&candidates) @@ -403,7 +403,7 @@ fn phragmen_accuracy_on_large_scale_voters_and_candidates() { (14, u64::MAX.into()), ]); - let ElectionResult { winners, assignments } = seq_phragmen::<_, Perbill>( + let ElectionResult::<_, Perbill> { winners, assignments } = seq_phragmen( 2, candidates, voters @@ -435,7 +435,7 @@ fn phragmen_accuracy_on_small_scale_self_vote() { let voters = auto_generate_self_voters(&candidates); let stake_of = create_stake_of(&[(40, 0), (10, 1), (20, 2), (30, 1)]); - let ElectionResult { winners, assignments } = seq_phragmen::<_, Perbill>( + let ElectionResult::<_, Perbill> { winners, assignments } = seq_phragmen( 3, candidates, voters @@ -465,7 +465,7 @@ fn phragmen_accuracy_on_small_scale_no_self_vote() { (3, 1), ]); - let ElectionResult { winners, assignments } = seq_phragmen::<_, Perbill>( + let ElectionResult::<_, Perbill> { winners, assignments } = seq_phragmen( 3, candidates, voters @@ -501,7 +501,7 @@ fn phragmen_large_scale_test() { (50, 990000000000000000), ]); - let ElectionResult { winners, assignments } = seq_phragmen::<_, Perbill>( + let ElectionResult::<_, Perbill> { winners, assignments } = seq_phragmen( 2, candidates, voters @@ -528,7 +528,7 @@ fn phragmen_large_scale_test_2() { let stake_of = create_stake_of(&[(2, c_budget.into()), (4, c_budget.into()), (50, nom_budget.into())]); - let ElectionResult { winners, assignments } = seq_phragmen::<_, Perbill>( + let ElectionResult::<_, Perbill> { winners, assignments } = seq_phragmen( 2, candidates, voters @@ -597,7 +597,7 @@ fn elect_has_no_entry_barrier() { let voters = vec![(1, vec![10]), (2, vec![20])]; let stake_of = create_stake_of(&[(1, 10), (2, 10)]); - let ElectionResult { winners, assignments: _ } = seq_phragmen::<_, Perbill>( + let ElectionResult::<_, Perbill> { winners, assignments: _ } = seq_phragmen( 3, candidates, voters @@ -618,7 +618,7 @@ fn phragmen_self_votes_should_be_kept() { let voters = vec![(5, vec![5]), (10, vec![10]), (20, vec![20]), (1, vec![10, 20])]; let stake_of = create_stake_of(&[(5, 5), (10, 10), (20, 20), (1, 8)]); - let result = seq_phragmen::<_, Perbill>( + let result: ElectionResult<_, Perbill> = seq_phragmen( 2, candidates, voters @@ -664,8 +664,8 @@ fn duplicate_target_is_ignored() { let candidates = vec![1, 2, 3]; let voters = vec![(10, 100, vec![1, 1, 2, 3]), (20, 100, vec![2, 3]), (30, 50, vec![1, 1, 2])]; - let ElectionResult { winners, assignments } = - seq_phragmen::<_, Perbill>(2, candidates, voters, None).unwrap(); + let ElectionResult::<_, Perbill> { winners, assignments } = + seq_phragmen(2, candidates, voters, None).unwrap(); assert_eq!(winners, vec![(2, 140), (3, 110)]); assert_eq!( @@ -682,8 +682,8 @@ fn duplicate_target_is_ignored_when_winner() { let candidates = vec![1, 2, 3]; let voters = vec![(10, 100, vec![1, 1, 2, 3]), (20, 100, vec![1, 2])]; - let ElectionResult { winners, assignments } = - seq_phragmen::<_, Perbill>(2, candidates, voters, None).unwrap(); + let ElectionResult::<_, Perbill> { winners, assignments } = + seq_phragmen(2, candidates, voters, None).unwrap(); assert_eq!(winners, vec![(1, 100), (2, 100)]); assert_eq!( diff --git a/primitives/offchain/Cargo.toml b/primitives/offchain/Cargo.toml index 7e0ce31d5d0c4..a96cd852bf24d 100644 --- a/primitives/offchain/Cargo.toml +++ b/primitives/offchain/Cargo.toml @@ -13,9 +13,9 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-core = { version = "4.1.0-dev", default-features = false, path = "../core" } +sp-core = { version = "5.0.0", default-features = false, path = "../core" } sp-api = { version = "4.0.0-dev", default-features = false, path = "../api" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../runtime" } [features] default = ["std"] diff --git a/primitives/rpc/Cargo.toml b/primitives/rpc/Cargo.toml index 52fe09b2c7894..240b74baf4747 100644 --- a/primitives/rpc/Cargo.toml +++ b/primitives/rpc/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sp-rpc" -version = "4.0.0-dev" +version = "5.0.0" authors = ["Parity Technologies "] edition = "2021" license = "Apache-2.0" @@ -13,8 +13,8 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -serde = { version = "1.0.132", features = ["derive"] } -sp-core = { version = "4.1.0-dev", path = "../core" } +serde = { version = "1.0.136", features = ["derive"] } +sp-core = { version = "5.0.0", path = "../core" } rustc-hash = "1.1.0" [dev-dependencies] diff --git a/primitives/runtime-interface/Cargo.toml b/primitives/runtime-interface/Cargo.toml index 137780c3c91e8..89805a9db36dd 100644 --- a/primitives/runtime-interface/Cargo.toml +++ b/primitives/runtime-interface/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sp-runtime-interface" -version = "4.1.0-dev" +version = "5.0.0" authors = ["Parity Technologies "] edition = "2021" license = "Apache-2.0" @@ -14,22 +14,22 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-wasm-interface = { version = "4.1.0-dev", path = "../wasm-interface", default-features = false } +sp-wasm-interface = { version = "5.0.0", path = "../wasm-interface", default-features = false } sp-std = { version = "4.0.0", default-features = false, path = "../std" } sp-tracing = { version = "4.0.0", default-features = false, path = "../tracing" } sp-runtime-interface-proc-macro = { version = "4.0.0", path = "proc-macro" } -sp-externalities = { version = "0.10.0", optional = true, path = "../externalities" } +sp-externalities = { version = "0.11.0", optional = true, path = "../externalities" } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } static_assertions = "1.0.0" primitive-types = { version = "0.10.1", default-features = false } -sp-storage = { version = "4.0.0", default-features = false, path = "../storage" } +sp-storage = { version = "5.0.0", default-features = false, path = "../storage" } impl-trait-for-tuples = "0.2.1" [dev-dependencies] sp-runtime-interface-test-wasm = { version = "2.0.0", path = "test-wasm" } -sp-state-machine = { version = "0.10.0", path = "../state-machine" } -sp-core = { version = "4.1.0-dev", path = "../core" } -sp-io = { version = "4.0.0-dev", path = "../io" } +sp-state-machine = { version = "0.11.0", path = "../state-machine" } +sp-core = { version = "5.0.0", path = "../core" } +sp-io = { version = "5.0.0", path = "../io" } rustversion = "1.0.6" trybuild = "1.0.53" diff --git a/primitives/runtime-interface/proc-macro/src/runtime_interface/bare_function_interface.rs b/primitives/runtime-interface/proc-macro/src/runtime_interface/bare_function_interface.rs index a06a1f9bda73e..b5745e25deb4c 100644 --- a/primitives/runtime-interface/proc-macro/src/runtime_interface/bare_function_interface.rs +++ b/primitives/runtime-interface/proc-macro/src/runtime_interface/bare_function_interface.rs @@ -32,11 +32,12 @@ use crate::utils::{ create_exchangeable_host_function_ident, create_function_ident_with_version, generate_crate_access, get_function_argument_names, get_function_arguments, - get_runtime_interface, + get_runtime_interface, RuntimeInterfaceFunction, }; use syn::{ - parse_quote, spanned::Spanned, FnArg, Ident, ItemTrait, Result, Signature, TraitItemMethod, + parse_quote, spanned::Spanned, FnArg, Ident, ItemTrait, Result, Signature, Token, + TraitItemMethod, }; use proc_macro2::{Span, TokenStream}; @@ -74,14 +75,14 @@ pub fn generate(trait_def: &ItemTrait, is_wasm_only: bool, tracing: bool) -> Res /// Generates the bare function implementation for the given method for the host and wasm side. fn function_for_method( - method: &TraitItemMethod, + method: &RuntimeInterfaceFunction, latest_version: u32, is_wasm_only: bool, ) -> Result { let std_impl = if !is_wasm_only { function_std_latest_impl(method, latest_version)? } else { quote!() }; - let no_std_impl = function_no_std_impl(method)?; + let no_std_impl = function_no_std_impl(method, is_wasm_only)?; Ok(quote! { #std_impl @@ -91,20 +92,46 @@ fn function_for_method( } /// Generates the bare function implementation for `cfg(not(feature = "std"))`. -fn function_no_std_impl(method: &TraitItemMethod) -> Result { +fn function_no_std_impl( + method: &RuntimeInterfaceFunction, + is_wasm_only: bool, +) -> Result { let function_name = &method.sig.ident; let host_function_name = create_exchangeable_host_function_ident(&method.sig.ident); let args = get_function_arguments(&method.sig); let arg_names = get_function_argument_names(&method.sig); - let return_value = &method.sig.output; + let return_value = if method.should_trap_on_return() { + syn::ReturnType::Type( + ]>::default(), + Box::new(syn::TypeNever { bang_token: ::default() }.into()), + ) + } else { + method.sig.output.clone() + }; + let maybe_unreachable = if method.should_trap_on_return() { + quote! { + ; core::arch::wasm32::unreachable(); + } + } else { + quote! {} + }; + let attrs = method.attrs.iter().filter(|a| !a.path.is_ident("version")); + let cfg_wasm_only = if is_wasm_only { + quote! { #[cfg(target_arch = "wasm32")] } + } else { + quote! {} + }; + Ok(quote! { + #cfg_wasm_only #[cfg(not(feature = "std"))] #( #attrs )* pub fn #function_name( #( #args, )* ) #return_value { // Call the host function #host_function_name.get()( #( #arg_names, )* ) + #maybe_unreachable } }) } diff --git a/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs b/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs index 626e309cc0e1c..1566bbf302c3b 100644 --- a/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs +++ b/primitives/runtime-interface/proc-macro/src/runtime_interface/host_function_interface.rs @@ -26,7 +26,7 @@ use crate::utils::{ create_host_function_ident, generate_crate_access, get_function_argument_names, get_function_argument_names_and_types_without_ref, get_function_argument_types, get_function_argument_types_ref_and_mut, get_function_argument_types_without_ref, - get_function_arguments, get_runtime_interface, + get_function_arguments, get_runtime_interface, RuntimeInterfaceFunction, }; use syn::{ @@ -205,7 +205,7 @@ fn generate_host_functions_struct( /// implementation of the function. fn generate_host_function_implementation( trait_name: &Ident, - method: &TraitItemMethod, + method: &RuntimeInterfaceFunction, version: u32, is_wasm_only: bool, ) -> Result<(TokenStream, Ident, TokenStream)> { diff --git a/primitives/runtime-interface/proc-macro/src/runtime_interface/trait_decl_impl.rs b/primitives/runtime-interface/proc-macro/src/runtime_interface/trait_decl_impl.rs index c48da3b788518..0ae0f5260286c 100644 --- a/primitives/runtime-interface/proc-macro/src/runtime_interface/trait_decl_impl.rs +++ b/primitives/runtime-interface/proc-macro/src/runtime_interface/trait_decl_impl.rs @@ -153,7 +153,7 @@ fn impl_trait_for_externalities(trait_def: &ItemTrait, is_wasm_only: bool) -> Re let crate_ = generate_crate_access(); let interface = get_runtime_interface(trait_def)?; let methods = interface.all_versions().map(|(version, method)| { - let mut cloned = method.clone(); + let mut cloned = (*method).clone(); cloned.attrs.retain(|a| !a.path.is_ident("version")); cloned.sig.ident = create_function_ident_with_version(&cloned.sig.ident, version); cloned diff --git a/primitives/runtime-interface/proc-macro/src/utils.rs b/primitives/runtime-interface/proc-macro/src/utils.rs index bc690eb21a9bd..19f7fea023c30 100644 --- a/primitives/runtime-interface/proc-macro/src/utils.rs +++ b/primitives/runtime-interface/proc-macro/src/utils.rs @@ -39,18 +39,64 @@ mod attributes { syn::custom_keyword!(register_only); } +/// A concrete, specific version of a runtime interface function. +pub struct RuntimeInterfaceFunction { + item: TraitItemMethod, + should_trap_on_return: bool, +} + +impl std::ops::Deref for RuntimeInterfaceFunction { + type Target = TraitItemMethod; + fn deref(&self) -> &Self::Target { + &self.item + } +} + +impl RuntimeInterfaceFunction { + fn new(item: &TraitItemMethod) -> Result { + let mut item = item.clone(); + let mut should_trap_on_return = false; + item.attrs.retain(|attr| { + if attr.path.is_ident("trap_on_return") { + should_trap_on_return = true; + false + } else { + true + } + }); + + if should_trap_on_return { + if !matches!(item.sig.output, syn::ReturnType::Default) { + return Err(Error::new( + item.sig.ident.span(), + "Methods marked as #[trap_on_return] cannot return anything", + )) + } + } + + Ok(Self { item, should_trap_on_return }) + } + + pub fn should_trap_on_return(&self) -> bool { + self.should_trap_on_return + } +} + /// Runtime interface function with all associated versions of this function. -pub struct RuntimeInterfaceFunction<'a> { +struct RuntimeInterfaceFunctionSet { latest_version_to_call: Option, - versions: BTreeMap, + versions: BTreeMap, } -impl<'a> RuntimeInterfaceFunction<'a> { - fn new(version: VersionAttribute, trait_item: &'a TraitItemMethod) -> Self { - Self { +impl RuntimeInterfaceFunctionSet { + fn new(version: VersionAttribute, trait_item: &TraitItemMethod) -> Result { + Ok(Self { latest_version_to_call: version.is_callable().then(|| version.version), - versions: BTreeMap::from([(version.version, trait_item)]), - } + versions: BTreeMap::from([( + version.version, + RuntimeInterfaceFunction::new(trait_item)?, + )]), + }) } /// Returns the latest version of this runtime interface function plus the actual function @@ -59,11 +105,11 @@ impl<'a> RuntimeInterfaceFunction<'a> { /// This isn't required to be the latest version, because a runtime interface function can be /// annotated with `register_only` to ensure that the host exposes the host function but it /// isn't used when compiling the runtime. - pub fn latest_version_to_call(&self) -> Option<(u32, &TraitItemMethod)> { + pub fn latest_version_to_call(&self) -> Option<(u32, &RuntimeInterfaceFunction)> { self.latest_version_to_call.map(|v| { ( v, - *self.versions.get(&v).expect( + self.versions.get(&v).expect( "If latest_version_to_call has a value, the key with this value is in the versions; qed", ), ) @@ -74,7 +120,7 @@ impl<'a> RuntimeInterfaceFunction<'a> { fn add_version( &mut self, version: VersionAttribute, - trait_item: &'a TraitItemMethod, + trait_item: &TraitItemMethod, ) -> Result<()> { if let Some(existing_item) = self.versions.get(&version.version) { let mut err = Error::new(trait_item.span(), "Duplicated version attribute"); @@ -86,7 +132,8 @@ impl<'a> RuntimeInterfaceFunction<'a> { return Err(err) } - self.versions.insert(version.version, trait_item); + self.versions + .insert(version.version, RuntimeInterfaceFunction::new(trait_item)?); if self.latest_version_to_call.map_or(true, |v| v < version.version) && version.is_callable() { @@ -98,22 +145,24 @@ impl<'a> RuntimeInterfaceFunction<'a> { } /// All functions of a runtime interface grouped by the function names. -pub struct RuntimeInterface<'a> { - items: BTreeMap>, +pub struct RuntimeInterface { + items: BTreeMap, } -impl<'a> RuntimeInterface<'a> { +impl RuntimeInterface { /// Returns an iterator over all runtime interface function - /// [`latest_version_to_call`](RuntimeInterfaceFunction::latest_version). - pub fn latest_versions_to_call(&self) -> impl Iterator { + /// [`latest_version_to_call`](RuntimeInterfaceFunctionSet::latest_version). + pub fn latest_versions_to_call( + &self, + ) -> impl Iterator { self.items.iter().filter_map(|(_, item)| item.latest_version_to_call()) } - pub fn all_versions(&self) -> impl Iterator { + pub fn all_versions(&self) -> impl Iterator { self.items .iter() .flat_map(|(_, item)| item.versions.iter()) - .map(|(v, i)| (*v, *i)) + .map(|(v, i)| (*v, i)) } } @@ -288,8 +337,8 @@ fn get_item_version(item: &TraitItemMethod) -> Result> } /// Returns all runtime interface members, with versions. -pub fn get_runtime_interface<'a>(trait_def: &'a ItemTrait) -> Result> { - let mut functions: BTreeMap> = BTreeMap::new(); +pub fn get_runtime_interface(trait_def: &ItemTrait) -> Result { + let mut functions: BTreeMap = BTreeMap::new(); for item in get_trait_methods(trait_def) { let name = item.sig.ident.clone(); @@ -301,7 +350,7 @@ pub fn get_runtime_interface<'a>(trait_def: &'a ItemTrait) -> Result { - entry.insert(RuntimeInterfaceFunction::new(version, item)); + entry.insert(RuntimeInterfaceFunctionSet::new(version, item)?); }, Entry::Occupied(mut entry) => { entry.get_mut().add_version(version, item)?; diff --git a/primitives/runtime-interface/test-wasm-deprecated/Cargo.toml b/primitives/runtime-interface/test-wasm-deprecated/Cargo.toml index 032de1d215f25..18046626f6508 100644 --- a/primitives/runtime-interface/test-wasm-deprecated/Cargo.toml +++ b/primitives/runtime-interface/test-wasm-deprecated/Cargo.toml @@ -13,10 +13,10 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-runtime-interface = { version = "4.1.0-dev", default-features = false, path = "../" } +sp-runtime-interface = { version = "5.0.0", default-features = false, path = "../" } sp-std = { version = "4.0.0", default-features = false, path = "../../std" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../io" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../io" } +sp-core = { version = "5.0.0", default-features = false, path = "../../core" } [build-dependencies] substrate-wasm-builder = { version = "5.0.0-dev", path = "../../../utils/wasm-builder" } diff --git a/primitives/runtime-interface/test-wasm/Cargo.toml b/primitives/runtime-interface/test-wasm/Cargo.toml index 80ad44569e999..9b6bdf39eb4c0 100644 --- a/primitives/runtime-interface/test-wasm/Cargo.toml +++ b/primitives/runtime-interface/test-wasm/Cargo.toml @@ -13,10 +13,10 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-runtime-interface = { version = "4.1.0-dev", default-features = false, path = "../" } +sp-runtime-interface = { version = "5.0.0", default-features = false, path = "../" } sp-std = { version = "4.0.0", default-features = false, path = "../../std" } -sp-io = { version = "4.0.0-dev", default-features = false, path = "../../io" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../core" } +sp-io = { version = "5.0.0", default-features = false, path = "../../io" } +sp-core = { version = "5.0.0", default-features = false, path = "../../core" } [build-dependencies] substrate-wasm-builder = { version = "5.0.0-dev", path = "../../../utils/wasm-builder" } diff --git a/primitives/runtime-interface/test/Cargo.toml b/primitives/runtime-interface/test/Cargo.toml index 82c6a21b995cc..107a8fcc7f2a4 100644 --- a/primitives/runtime-interface/test/Cargo.toml +++ b/primitives/runtime-interface/test/Cargo.toml @@ -12,13 +12,13 @@ repository = "https://github.com/paritytech/substrate/" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-runtime-interface = { version = "4.1.0-dev", path = "../" } +sp-runtime-interface = { version = "5.0.0", path = "../" } sc-executor = { version = "0.10.0-dev", path = "../../../client/executor" } sc-executor-common = { version = "0.10.0-dev", path = "../../../client/executor/common" } sp-runtime-interface-test-wasm = { version = "2.0.0", path = "../test-wasm" } sp-runtime-interface-test-wasm-deprecated = { version = "2.0.0", path = "../test-wasm-deprecated" } -sp-state-machine = { version = "0.10.0", path = "../../state-machine" } -sp-runtime = { version = "4.1.0-dev", path = "../../runtime" } -sp-io = { version = "4.0.0", path = "../../io" } +sp-state-machine = { version = "0.11.0", path = "../../state-machine" } +sp-runtime = { version = "5.0.0", path = "../../runtime" } +sp-io = { version = "5.0.0", path = "../../io" } tracing = "0.1.29" tracing-core = "0.1.17" diff --git a/primitives/runtime/Cargo.toml b/primitives/runtime/Cargo.toml index e6bb5a1c842e5..7b58482b2c36e 100644 --- a/primitives/runtime/Cargo.toml +++ b/primitives/runtime/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sp-runtime" -version = "4.1.0-dev" +version = "5.0.0" authors = ["Parity Technologies "] edition = "2021" license = "Apache-2.0" @@ -15,14 +15,14 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] -serde = { version = "1.0.132", optional = true, features = ["derive"] } +serde = { version = "1.0.136", optional = true, features = ["derive"] } codec = { package = "parity-scale-codec", version = "2.2.0", default-features = false, features = ["derive", "max-encoded-len"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../core" } -sp-application-crypto = { version = "4.0.0", default-features = false, path = "../application-crypto" } +sp-core = { version = "5.0.0", default-features = false, path = "../core" } +sp-application-crypto = { version = "5.0.0", default-features = false, path = "../application-crypto" } sp-arithmetic = { version = "4.0.0", default-features = false, path = "../arithmetic" } sp-std = { version = "4.0.0", default-features = false, path = "../std" } -sp-io = { version = "4.0.0", default-features = false, path = "../io" } +sp-io = { version = "5.0.0", default-features = false, path = "../io" } log = { version = "0.4.14", default-features = false } paste = "1.0" rand = { version = "0.7.2", optional = true } @@ -34,7 +34,7 @@ either = { version = "1.5", default-features = false } [dev-dependencies] serde_json = "1.0.74" rand = "0.7.2" -sp-state-machine = { version = "0.10.0", path = "../state-machine" } +sp-state-machine = { version = "0.11.0", path = "../state-machine" } sp-api = { version = "4.0.0-dev", path = "../api" } substrate-test-runtime-client = { version = "2.0.0", path = "../../test-utils/runtime/client" } sp-tracing = { version = "4.0.0", path = "../../primitives/tracing" } diff --git a/primitives/runtime/src/generic/unchecked_extrinsic.rs b/primitives/runtime/src/generic/unchecked_extrinsic.rs index d444d0352d5ae..fb333abd6ac6e 100644 --- a/primitives/runtime/src/generic/unchecked_extrinsic.rs +++ b/primitives/runtime/src/generic/unchecked_extrinsic.rs @@ -31,8 +31,12 @@ use scale_info::{build::Fields, meta_type, Path, StaticTypeInfo, Type, TypeInfo, use sp_io::hashing::blake2_256; use sp_std::{fmt, prelude::*}; -/// Current version of the [`UncheckedExtrinsic`] format. -const EXTRINSIC_VERSION: u8 = 4; +/// Current version of the [`UncheckedExtrinsic`] encoded format. +/// +/// This version needs to be bumped if the encoded representation changes. +/// It ensures that if the representation is changed and the format is not known, +/// the decoding fails. +const EXTRINSIC_FORMAT_VERSION: u8 = 4; /// A extrinsic right from the external world. This is unchecked and so /// can contain a signature. @@ -164,7 +168,7 @@ impl ExtrinsicMetadata where Extra: SignedExtension, { - const VERSION: u8 = EXTRINSIC_VERSION; + const VERSION: u8 = EXTRINSIC_FORMAT_VERSION; type SignedExtensions = Extra; } @@ -235,23 +239,33 @@ where { fn decode(input: &mut I) -> Result { // This is a little more complicated than usual since the binary format must be compatible - // with substrate's generic `Vec` type. Basically this just means accepting that there - // will be a prefix of vector length (we don't need - // to use this). - let _length_do_not_remove_me_see_above: Compact = Decode::decode(input)?; + // with SCALE's generic `Vec` type. Basically this just means accepting that there + // will be a prefix of vector length. + let expected_length: Compact = Decode::decode(input)?; + let before_length = input.remaining_len()?; let version = input.read_byte()?; let is_signed = version & 0b1000_0000 != 0; let version = version & 0b0111_1111; - if version != EXTRINSIC_VERSION { + if version != EXTRINSIC_FORMAT_VERSION { return Err("Invalid transaction version".into()) } - Ok(Self { - signature: if is_signed { Some(Decode::decode(input)?) } else { None }, - function: Decode::decode(input)?, - }) + let signature = is_signed.then(|| Decode::decode(input)).transpose()?; + let function = Decode::decode(input)?; + + if let Some((before_length, after_length)) = + input.remaining_len()?.and_then(|a| before_length.map(|b| (b, a))) + { + let length = before_length.saturating_sub(after_length); + + if length != expected_length.0 as usize { + return Err("Invalid length prefix".into()) + } + } + + Ok(Self { signature, function }) } } @@ -268,11 +282,11 @@ where // 1 byte version id. match self.signature.as_ref() { Some(s) => { - tmp.push(EXTRINSIC_VERSION | 0b1000_0000); + tmp.push(EXTRINSIC_FORMAT_VERSION | 0b1000_0000); s.encode_to(&mut tmp); }, None => { - tmp.push(EXTRINSIC_VERSION & 0b0111_1111); + tmp.push(EXTRINSIC_FORMAT_VERSION & 0b0111_1111); }, } self.function.encode_to(&mut tmp); @@ -409,6 +423,17 @@ mod tests { assert_eq!(Ex::decode(&mut &encoded[..]), Ok(ux)); } + #[test] + fn invalid_length_prefix_is_detected() { + let ux = Ex::new_unsigned(vec![0u8; 0]); + let mut encoded = ux.encode(); + + let length = Compact::::decode(&mut &encoded[..]).unwrap(); + Compact(length.0 + 10).encode_to(&mut &mut encoded[..1]); + + assert_eq!(Ex::decode(&mut &encoded[..]), Err("Invalid length prefix".into())); + } + #[test] fn signed_codec_should_work() { let ux = Ex::new_signed( diff --git a/primitives/runtime/src/lib.rs b/primitives/runtime/src/lib.rs index cb9ba9ff297fb..6d32d2322c765 100644 --- a/primitives/runtime/src/lib.rs +++ b/primitives/runtime/src/lib.rs @@ -52,7 +52,7 @@ use sp_core::{ }; use sp_std::{convert::TryFrom, prelude::*}; -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; pub mod curve; @@ -224,7 +224,7 @@ pub type ConsensusEngineId = [u8; 4]; /// Signature verify that can work with any known signature types.. #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -#[derive(Eq, PartialEq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)] +#[derive(Eq, PartialEq, Clone, Encode, Decode, MaxEncodedLen, RuntimeDebug, TypeInfo)] pub enum MultiSignature { /// An Ed25519 signature. Ed25519(ed25519::Signature), @@ -461,9 +461,29 @@ pub type DispatchResult = sp_std::result::Result<(), DispatchError>; /// about the `Dispatchable` that is only known post dispatch. pub type DispatchResultWithInfo = sp_std::result::Result>; -/// Reason why a dispatch call failed. +/// Reason why a pallet call failed. #[derive(Eq, Clone, Copy, Encode, Decode, Debug, TypeInfo)] #[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +pub struct ModuleError { + /// Module index, matching the metadata module index. + pub index: u8, + /// Module specific error value. + pub error: u8, + /// Optional error message. + #[codec(skip)] + #[cfg_attr(feature = "std", serde(skip_deserializing))] + pub message: Option<&'static str>, +} + +impl PartialEq for ModuleError { + fn eq(&self, other: &Self) -> bool { + (self.index == other.index) && (self.error == other.error) + } +} + +/// Reason why a dispatch call failed. +#[derive(Eq, Clone, Copy, Encode, Decode, Debug, TypeInfo, PartialEq)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] pub enum DispatchError { /// Some error occurred. Other( @@ -476,16 +496,7 @@ pub enum DispatchError { /// A bad origin. BadOrigin, /// A custom error in a module. - Module { - /// Module index, matching the metadata module index. - index: u8, - /// Module specific error value. - error: u8, - /// Optional error message. - #[codec(skip)] - #[cfg_attr(feature = "std", serde(skip_deserializing))] - message: Option<&'static str>, - }, + Module(ModuleError), /// At least one consumer is remaining so the account cannot be destroyed. ConsumerRemaining, /// There are no providers so the account cannot be created. @@ -515,8 +526,8 @@ impl DispatchError { /// Return the same error but without the attached message. pub fn stripped(self) -> Self { match self { - DispatchError::Module { index, error, message: Some(_) } => - DispatchError::Module { index, error, message: None }, + DispatchError::Module(ModuleError { index, error, message: Some(_) }) => + DispatchError::Module(ModuleError { index, error, message: None }), m => m, } } @@ -624,7 +635,8 @@ impl From for &'static str { DispatchError::Other(msg) => msg, DispatchError::CannotLookup => "Cannot lookup", DispatchError::BadOrigin => "Bad origin", - DispatchError::Module { message, .. } => message.unwrap_or("Unknown module error"), + DispatchError::Module(ModuleError { message, .. }) => + message.unwrap_or("Unknown module error"), DispatchError::ConsumerRemaining => "Consumer remaining", DispatchError::NoProviders => "No providers", DispatchError::TooManyConsumers => "Too many consumers", @@ -650,7 +662,7 @@ impl traits::Printable for DispatchError { Self::Other(err) => err.print(), Self::CannotLookup => "Cannot lookup".print(), Self::BadOrigin => "Bad origin".print(), - Self::Module { index, error, message } => { + Self::Module(ModuleError { index, error, message }) => { index.print(); error.print(); if let Some(msg) = message { @@ -683,30 +695,6 @@ where } } -impl PartialEq for DispatchError { - fn eq(&self, other: &Self) -> bool { - use DispatchError::*; - - match (self, other) { - (CannotLookup, CannotLookup) | - (BadOrigin, BadOrigin) | - (ConsumerRemaining, ConsumerRemaining) | - (NoProviders, NoProviders) => true, - - (Token(l), Token(r)) => l == r, - (Other(l), Other(r)) => l == r, - (Arithmetic(l), Arithmetic(r)) => l == r, - - ( - Module { index: index_l, error: error_l, .. }, - Module { index: index_r, error: error_r, .. }, - ) => (index_l == index_r) && (error_l == error_r), - - _ => false, - } - } -} - /// This type specifies the outcome of dispatching a call to a module. /// /// In case of failure an error specific to the module is returned. @@ -932,11 +920,18 @@ mod tests { #[test] fn dispatch_error_encoding() { - let error = DispatchError::Module { index: 1, error: 2, message: Some("error message") }; + let error = DispatchError::Module(ModuleError { + index: 1, + error: 2, + message: Some("error message"), + }); let encoded = error.encode(); let decoded = DispatchError::decode(&mut &encoded[..]).unwrap(); assert_eq!(encoded, vec![3, 1, 2]); - assert_eq!(decoded, DispatchError::Module { index: 1, error: 2, message: None }); + assert_eq!( + decoded, + DispatchError::Module(ModuleError { index: 1, error: 2, message: None }) + ); } #[test] @@ -948,9 +943,9 @@ mod tests { Other("bar"), CannotLookup, BadOrigin, - Module { index: 1, error: 1, message: None }, - Module { index: 1, error: 2, message: None }, - Module { index: 2, error: 1, message: None }, + Module(ModuleError { index: 1, error: 1, message: None }), + Module(ModuleError { index: 1, error: 2, message: None }), + Module(ModuleError { index: 2, error: 1, message: None }), ConsumerRemaining, NoProviders, Token(TokenError::NoFunds), @@ -975,8 +970,8 @@ mod tests { // Ignores `message` field in `Module` variant. assert_eq!( - Module { index: 1, error: 1, message: Some("foo") }, - Module { index: 1, error: 1, message: None }, + Module(ModuleError { index: 1, error: 1, message: Some("foo") }), + Module(ModuleError { index: 1, error: 1, message: None }), ); } diff --git a/primitives/runtime/src/traits.rs b/primitives/runtime/src/traits.rs index a6004d07c2ff7..1cea7c4e805c1 100644 --- a/primitives/runtime/src/traits.rs +++ b/primitives/runtime/src/traits.rs @@ -483,12 +483,12 @@ impl Hasher for BlakeTwo256 { impl Hash for BlakeTwo256 { type Output = sp_core::H256; - fn trie_root(input: Vec<(Vec, Vec)>, _: StateVersion) -> Self::Output { - sp_io::trie::blake2_256_root(input) + fn trie_root(input: Vec<(Vec, Vec)>, version: StateVersion) -> Self::Output { + sp_io::trie::blake2_256_root(input, version) } - fn ordered_trie_root(input: Vec>, _: StateVersion) -> Self::Output { - sp_io::trie::blake2_256_ordered_root(input) + fn ordered_trie_root(input: Vec>, version: StateVersion) -> Self::Output { + sp_io::trie::blake2_256_ordered_root(input, version) } } @@ -510,12 +510,12 @@ impl Hasher for Keccak256 { impl Hash for Keccak256 { type Output = sp_core::H256; - fn trie_root(input: Vec<(Vec, Vec)>, _: StateVersion) -> Self::Output { - sp_io::trie::keccak_256_root(input) + fn trie_root(input: Vec<(Vec, Vec)>, version: StateVersion) -> Self::Output { + sp_io::trie::keccak_256_root(input, version) } - fn ordered_trie_root(input: Vec>, _: StateVersion) -> Self::Output { - sp_io::trie::keccak_256_ordered_root(input) + fn ordered_trie_root(input: Vec>, version: StateVersion) -> Self::Output { + sp_io::trie::keccak_256_ordered_root(input, version) } } @@ -748,7 +748,9 @@ pub trait Extrinsic: Sized + MaybeMallocSizeOf { /// Implementor is an [`Extrinsic`] and provides metadata about this extrinsic. pub trait ExtrinsicMetadata { - /// The version of the `Extrinsic`. + /// The format version of the `Extrinsic`. + /// + /// By format is meant the encoded representation of the `Extrinsic`. const VERSION: u8; /// Signed extensions attached to this `Extrinsic`. @@ -1585,7 +1587,7 @@ impl Printable for Tuple { #[cfg(feature = "std")] pub trait BlockIdTo { /// The error type that will be returned by the functions. - type Error: std::fmt::Debug; + type Error: std::error::Error; /// Convert the given `block_id` to the corresponding block hash. fn to_hash( diff --git a/primitives/sandbox/Cargo.toml b/primitives/sandbox/Cargo.toml index 59941c9648ddd..a72786807330d 100644 --- a/primitives/sandbox/Cargo.toml +++ b/primitives/sandbox/Cargo.toml @@ -20,10 +20,10 @@ wasmi = "0.9.0" [dependencies] wasmi = { version = "0.9.0", optional = true } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../core" } +sp-core = { version = "5.0.0", default-features = false, path = "../core" } sp-std = { version = "4.0.0", default-features = false, path = "../std" } -sp-io = { version = "4.0.0", default-features = false, path = "../io" } -sp-wasm-interface = { version = "4.1.0-dev", default-features = false, path = "../wasm-interface" } +sp-io = { version = "5.0.0", default-features = false, path = "../io" } +sp-wasm-interface = { version = "5.0.0", default-features = false, path = "../wasm-interface" } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } log = { version = "0.4", default-features = false } diff --git a/primitives/serializer/Cargo.toml b/primitives/serializer/Cargo.toml index a0413164eb57a..6a9fb5d90ddb4 100644 --- a/primitives/serializer/Cargo.toml +++ b/primitives/serializer/Cargo.toml @@ -14,5 +14,5 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -serde = "1.0.132" +serde = "1.0.136" serde_json = "1.0.74" diff --git a/primitives/session/Cargo.toml b/primitives/session/Cargo.toml index 293f3642b7f33..4138ecb519df6 100644 --- a/primitives/session/Cargo.toml +++ b/primitives/session/Cargo.toml @@ -16,10 +16,10 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-api = { version = "4.0.0-dev", default-features = false, path = "../api" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../core" } +sp-core = { version = "5.0.0", default-features = false, path = "../core" } sp-std = { version = "4.0.0", default-features = false, path = "../std" } sp-staking = { version = "4.0.0-dev", default-features = false, path = "../staking" } -sp-runtime = { version = "4.1.0-dev", optional = true, path = "../runtime" } +sp-runtime = { version = "5.0.0", optional = true, path = "../runtime" } [features] default = [ "std" ] diff --git a/primitives/staking/Cargo.toml b/primitives/staking/Cargo.toml index 6ae972f1814be..54e556dfae122 100644 --- a/primitives/staking/Cargo.toml +++ b/primitives/staking/Cargo.toml @@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../std" } [features] diff --git a/primitives/state-machine/Cargo.toml b/primitives/state-machine/Cargo.toml index c885f99fdb839..15720688c0585 100644 --- a/primitives/state-machine/Cargo.toml +++ b/primitives/state-machine/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sp-state-machine" -version = "0.10.0" +version = "0.11.0" authors = ["Parity Technologies "] description = "Substrate State Machine" edition = "2021" @@ -20,20 +20,20 @@ parking_lot = { version = "0.11.2", optional = true } hash-db = { version = "0.15.2", default-features = false } trie-db = { version = "0.23.0", default-features = false } trie-root = { version = "0.17.0", default-features = false } -sp-trie = { version = "4.0.0", path = "../trie", default-features = false } -sp-core = { version = "4.1.0-dev", path = "../core", default-features = false } +sp-trie = { version = "5.0.0", path = "../trie", default-features = false } +sp-core = { version = "5.0.0", path = "../core", default-features = false } sp-panic-handler = { version = "4.0.0", path = "../panic-handler", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false } num-traits = { version = "0.2.8", default-features = false } rand = { version = "0.7.2", optional = true } -sp-externalities = { version = "0.10.0", path = "../externalities", default-features = false } +sp-externalities = { version = "0.11.0", path = "../externalities", default-features = false } smallvec = "1.7.0" sp-std = { version = "4.0.0", default-features = false, path = "../std" } tracing = { version = "0.1.29", optional = true } [dev-dependencies] hex-literal = "0.3.4" -sp-runtime = { version = "4.1.0-dev", path = "../runtime" } +sp-runtime = { version = "5.0.0", path = "../runtime" } pretty_assertions = "1.0.0" rand = "0.7.2" diff --git a/primitives/state-machine/src/overlayed_changes/mod.rs b/primitives/state-machine/src/overlayed_changes/mod.rs index 89bbb063ef9a7..d75feec0ced9c 100644 --- a/primitives/state-machine/src/overlayed_changes/mod.rs +++ b/primitives/state-machine/src/overlayed_changes/mod.rs @@ -104,7 +104,7 @@ pub struct OverlayedChanges { stats: StateMachineStats, } -/// Transcation index operation. +/// Transaction index operation. #[derive(Debug, Clone)] pub enum IndexOperation { /// Insert transaction into index. diff --git a/primitives/storage/Cargo.toml b/primitives/storage/Cargo.toml index 81e4140bbd36f..7d1a8c03c0a09 100644 --- a/primitives/storage/Cargo.toml +++ b/primitives/storage/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sp-storage" -version = "4.0.0" +version = "5.0.0" authors = ["Parity Technologies "] edition = "2021" description = "Storage related primitives" @@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] sp-std = { version = "4.0.0", default-features = false, path = "../std" } -serde = { version = "1.0.132", optional = true, features = ["derive"] } +serde = { version = "1.0.136", optional = true, features = ["derive"] } impl-serde = { version = "0.3.1", optional = true } ref-cast = "1.0.0" sp-debug-derive = { version = "4.0.0", default-features = false, path = "../debug-derive" } diff --git a/primitives/tasks/Cargo.toml b/primitives/tasks/Cargo.toml index 6ac6c6aa98bec..00943e8657205 100644 --- a/primitives/tasks/Cargo.toml +++ b/primitives/tasks/Cargo.toml @@ -15,10 +15,10 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] log = { version = "0.4.8", optional = true } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../core" } -sp-externalities = { version = "0.10.0", optional = true, path = "../externalities" } -sp-io = { version = "4.0.0", default-features = false, path = "../io" } -sp-runtime-interface = { version = "4.1.0-dev", default-features = false, path = "../runtime-interface" } +sp-core = { version = "5.0.0", default-features = false, path = "../core" } +sp-externalities = { version = "0.11.0", optional = true, path = "../externalities" } +sp-io = { version = "5.0.0", default-features = false, path = "../io" } +sp-runtime-interface = { version = "5.0.0", default-features = false, path = "../runtime-interface" } sp-std = { version = "4.0.0", default-features = false, path = "../std" } [dev-dependencies] diff --git a/primitives/test-primitives/Cargo.toml b/primitives/test-primitives/Cargo.toml index ab2ef0d54ca4b..101a9249bf707 100644 --- a/primitives/test-primitives/Cargo.toml +++ b/primitives/test-primitives/Cargo.toml @@ -12,11 +12,11 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-application-crypto = { version = "4.0.0", default-features = false, path = "../application-crypto" } +sp-application-crypto = { version = "5.0.0", default-features = false, path = "../application-crypto" } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../core" } -serde = { version = "1.0.132", optional = true, features = ["derive"] } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../runtime" } +sp-core = { version = "5.0.0", default-features = false, path = "../core" } +serde = { version = "1.0.136", optional = true, features = ["derive"] } +sp-runtime = { version = "5.0.0", default-features = false, path = "../runtime" } parity-util-mem = { version = "0.10.2", default-features = false, features = ["primitive-types"] } [features] diff --git a/primitives/timestamp/Cargo.toml b/primitives/timestamp/Cargo.toml index e42ca738cd55e..f7ac2e663e397 100644 --- a/primitives/timestamp/Cargo.toml +++ b/primitives/timestamp/Cargo.toml @@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] sp-api = { version = "4.0.0-dev", default-features = false, path = "../api" } sp-std = { version = "4.0.0", default-features = false, path = "../std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../runtime" } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } sp-inherents = { version = "4.0.0-dev", default-features = false, path = "../inherents" } thiserror = { version = "1.0.30", optional = true } diff --git a/primitives/transaction-pool/Cargo.toml b/primitives/transaction-pool/Cargo.toml index fab5f90ffffc0..c8f70bdce9de2 100644 --- a/primitives/transaction-pool/Cargo.toml +++ b/primitives/transaction-pool/Cargo.toml @@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] sp-api = { version = "4.0.0-dev", default-features = false, path = "../api" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../runtime" } [features] default = [ "std" ] diff --git a/primitives/transaction-storage-proof/Cargo.toml b/primitives/transaction-storage-proof/Cargo.toml index 87f7f81cd5868..9e2898fe267e1 100644 --- a/primitives/transaction-storage-proof/Cargo.toml +++ b/primitives/transaction-storage-proof/Cargo.toml @@ -14,10 +14,10 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] sp-inherents = { version = "4.0.0-dev", default-features = false, path = "../inherents" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../runtime" } sp-std = { version = "4.0.0", default-features = false, path = "../std" } -sp-trie = { version = "4.0.0", optional = true, path = "../trie" } -sp-core = { version = "4.1.0-dev", path = "../core", optional = true } +sp-trie = { version = "5.0.0", optional = true, path = "../trie" } +sp-core = { version = "5.0.0", path = "../core", optional = true } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } log = { version = "0.4.8", optional = true } diff --git a/primitives/transaction-storage-proof/src/lib.rs b/primitives/transaction-storage-proof/src/lib.rs index 1efd9474b4fd8..2e5aa3b2b9c71 100644 --- a/primitives/transaction-storage-proof/src/lib.rs +++ b/primitives/transaction-storage-proof/src/lib.rs @@ -143,7 +143,7 @@ pub mod registration { use sp_trie::TrieMut; type Hasher = sp_core::Blake2Hasher; - type TrieLayout = sp_trie::LayoutV0; + type TrieLayout = sp_trie::LayoutV1; /// Create a new inherent data provider instance for a given parent block hash. pub fn new_data_provider( diff --git a/primitives/trie/Cargo.toml b/primitives/trie/Cargo.toml index 4564fa86ced95..e79f2ffb7f845 100644 --- a/primitives/trie/Cargo.toml +++ b/primitives/trie/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sp-trie" -version = "4.0.0" +version = "5.0.0" authors = ["Parity Technologies "] description = "Patricia trie stuff using a parity-scale-codec node format" repository = "https://github.com/paritytech/substrate/" @@ -25,14 +25,14 @@ hash-db = { version = "0.15.2", default-features = false } trie-db = { version = "0.23.0", default-features = false } trie-root = { version = "0.17.0", default-features = false } memory-db = { version = "0.28.0", default-features = false } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../core" } +sp-core = { version = "5.0.0", default-features = false, path = "../core" } [dev-dependencies] trie-bench = "0.29.0" trie-standardmap = "0.15.2" criterion = "0.3.3" hex-literal = "0.3.4" -sp-runtime = { version = "4.1.0-dev", path = "../runtime" } +sp-runtime = { version = "5.0.0", path = "../runtime" } [features] default = ["std"] diff --git a/primitives/version/Cargo.toml b/primitives/version/Cargo.toml index 1bb39eca13640..053ba49fd82fb 100644 --- a/primitives/version/Cargo.toml +++ b/primitives/version/Cargo.toml @@ -15,11 +15,11 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] impl-serde = { version = "0.3.1", optional = true } -serde = { version = "1.0.132", optional = true, features = ["derive"] } +serde = { version = "1.0.136", optional = true, features = ["derive"] } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-std = { version = "4.0.0", default-features = false, path = "../std" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../runtime" } sp-version-proc-macro = { version = "4.0.0-dev", default-features = false, path = "proc-macro" } parity-wasm = { version = "0.42.2", optional = true } sp-core-hashing-proc-macro = { version = "4.0.0-dev", path = "../core/hashing/proc-macro" } diff --git a/primitives/wasm-interface/Cargo.toml b/primitives/wasm-interface/Cargo.toml index 200c686243e02..bb82629ba01e8 100644 --- a/primitives/wasm-interface/Cargo.toml +++ b/primitives/wasm-interface/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sp-wasm-interface" -version = "4.1.0-dev" +version = "5.0.0" authors = ["Parity Technologies "] edition = "2021" license = "Apache-2.0" diff --git a/primitives/wasm-interface/src/lib.rs b/primitives/wasm-interface/src/lib.rs index 21dbf9609ecf3..d57666f126899 100644 --- a/primitives/wasm-interface/src/lib.rs +++ b/primitives/wasm-interface/src/lib.rs @@ -305,6 +305,29 @@ pub trait FunctionContext { fn deallocate_memory(&mut self, ptr: Pointer) -> Result<()>; /// Provides access to the sandbox. fn sandbox(&mut self) -> &mut dyn Sandbox; + + /// Registers a panic error message within the executor. + /// + /// This is meant to be used in situations where the runtime + /// encounters an unrecoverable error and intends to panic. + /// + /// Panicking in WASM is done through the [`unreachable`](https://webassembly.github.io/spec/core/syntax/instructions.html#syntax-instr-control) + /// instruction which causes an unconditional trap and immediately aborts + /// the execution. It does not however allow for any diagnostics to be + /// passed through to the host, so while we do know that *something* went + /// wrong we don't have any direct indication of what *exactly* went wrong. + /// + /// As a workaround we use this method right before the execution is + /// actually aborted to pass an error message to the host so that it + /// can associate it with the next trap, and return that to the caller. + /// + /// A WASM trap should be triggered immediately after calling this method; + /// otherwise the error message might be associated with a completely + /// unrelated trap. + /// + /// It should only be called once, however calling it more than once + /// is harmless and will overwrite the previously set error message. + fn register_panic_error_message(&mut self, message: &str); } /// Sandbox memory identifier. diff --git a/test-utils/client/Cargo.toml b/test-utils/client/Cargo.toml index 902a14b1b3bdf..a74d7b5835273 100644 --- a/test-utils/client/Cargo.toml +++ b/test-utils/client/Cargo.toml @@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "2.0.0" } futures = "0.3.16" hex = "0.4" -serde = "1.0.132" +serde = "1.0.136" serde_json = "1.0.74" sc-client-api = { version = "4.0.0-dev", path = "../../client/api" } sc-client-db = { version = "0.10.0-dev", features = [ @@ -29,9 +29,9 @@ sc-service = { version = "0.10.0-dev", default-features = false, features = [ ], path = "../../client/service" } sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } sp-consensus = { version = "0.10.0-dev", path = "../../primitives/consensus/common" } -sp-core = { version = "4.1.0-dev", path = "../../primitives/core" } -sp-keystore = { version = "0.10.0", path = "../../primitives/keystore" } -sp-keyring = { version = "4.1.0-dev", path = "../../primitives/keyring" } -sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" } -sp-state-machine = { version = "0.10.0", path = "../../primitives/state-machine" } +sp-core = { version = "5.0.0", path = "../../primitives/core" } +sp-keystore = { version = "0.11.0", path = "../../primitives/keystore" } +sp-keyring = { version = "5.0.0", path = "../../primitives/keyring" } +sp-runtime = { version = "5.0.0", path = "../../primitives/runtime" } +sp-state-machine = { version = "0.11.0", path = "../../primitives/state-machine" } async-trait = "0.1.50" diff --git a/test-utils/runtime/Cargo.toml b/test-utils/runtime/Cargo.toml index e88f571366020..6529fa71106eb 100644 --- a/test-utils/runtime/Cargo.toml +++ b/test-utils/runtime/Cargo.toml @@ -13,42 +13,42 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-application-crypto = { version = "4.0.0", default-features = false, path = "../../primitives/application-crypto" } +sp-application-crypto = { version = "5.0.0", default-features = false, path = "../../primitives/application-crypto" } sp-consensus-aura = { version = "0.10.0-dev", default-features = false, path = "../../primitives/consensus/aura" } sp-consensus-babe = { version = "0.10.0-dev", default-features = false, path = "../../primitives/consensus/babe" } sp-block-builder = { version = "4.0.0-dev", default-features = false, path = "../../primitives/block-builder" } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } sp-inherents = { version = "4.0.0-dev", default-features = false, path = "../../primitives/inherents" } -sp-keyring = { version = "4.1.0-dev", optional = true, path = "../../primitives/keyring" } +sp-keyring = { version = "5.0.0", optional = true, path = "../../primitives/keyring" } memory-db = { version = "0.27.0", default-features = false } sp-offchain = { version = "4.0.0-dev", default-features = false, path = "../../primitives/offchain" } -sp-core = { version = "4.1.0-dev", default-features = false, path = "../../primitives/core" } +sp-core = { version = "5.0.0", default-features = false, path = "../../primitives/core" } sp-std = { version = "4.0.0", default-features = false, path = "../../primitives/std" } -sp-runtime-interface = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime-interface" } -sp-io = { version = "4.0.0", default-features = false, path = "../../primitives/io" } +sp-runtime-interface = { version = "5.0.0", default-features = false, path = "../../primitives/runtime-interface" } +sp-io = { version = "5.0.0", default-features = false, path = "../../primitives/io" } frame-support = { version = "4.0.0-dev", default-features = false, path = "../../frame/support" } sp-version = { version = "4.0.0-dev", default-features = false, path = "../../primitives/version" } sp-session = { version = "4.0.0-dev", default-features = false, path = "../../primitives/session" } sp-api = { version = "4.0.0-dev", default-features = false, path = "../../primitives/api" } -sp-runtime = { version = "4.1.0-dev", default-features = false, path = "../../primitives/runtime" } +sp-runtime = { version = "5.0.0", default-features = false, path = "../../primitives/runtime" } pallet-babe = { version = "4.0.0-dev", default-features = false, path = "../../frame/babe" } frame-system = { version = "4.0.0-dev", default-features = false, path = "../../frame/system" } frame-system-rpc-runtime-api = { version = "4.0.0-dev", default-features = false, path = "../../frame/system/rpc/runtime-api" } pallet-timestamp = { version = "4.0.0-dev", default-features = false, path = "../../frame/timestamp" } sp-finality-grandpa = { version = "4.0.0-dev", default-features = false, path = "../../primitives/finality-grandpa" } -sp-trie = { version = "4.0.0", default-features = false, path = "../../primitives/trie" } +sp-trie = { version = "5.0.0", default-features = false, path = "../../primitives/trie" } sp-transaction-pool = { version = "4.0.0-dev", default-features = false, path = "../../primitives/transaction-pool" } trie-db = { version = "0.23.0", default-features = false } parity-util-mem = { version = "0.10.2", default-features = false, features = ["primitive-types"] } sc-service = { version = "0.10.0-dev", default-features = false, optional = true, features = ["test-helpers"], path = "../../client/service" } -sp-state-machine = { version = "0.10.0", default-features = false, path = "../../primitives/state-machine" } -sp-externalities = { version = "0.10.0", default-features = false, path = "../../primitives/externalities" } +sp-state-machine = { version = "0.11.0", default-features = false, path = "../../primitives/state-machine" } +sp-externalities = { version = "0.11.0", default-features = false, path = "../../primitives/externalities" } # 3rd party cfg-if = "1.0" log = { version = "0.4.14", default-features = false } -serde = { version = "1.0.132", optional = true, features = ["derive"] } +serde = { version = "1.0.136", optional = true, features = ["derive"] } [dev-dependencies] sc-block-builder = { version = "0.10.0-dev", path = "../../client/block-builder" } diff --git a/test-utils/runtime/client/Cargo.toml b/test-utils/runtime/client/Cargo.toml index ba0f01cfced99..fd260453ca181 100644 --- a/test-utils/runtime/client/Cargo.toml +++ b/test-utils/runtime/client/Cargo.toml @@ -16,9 +16,9 @@ sp-consensus = { version = "0.10.0-dev", path = "../../../primitives/consensus/c sc-consensus = { version = "0.10.0-dev", path = "../../../client/consensus/common" } sc-block-builder = { version = "0.10.0-dev", path = "../../../client/block-builder" } substrate-test-client = { version = "2.0.0", path = "../../client" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } substrate-test-runtime = { version = "2.0.0", path = "../../runtime" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } sp-api = { version = "4.0.0-dev", path = "../../../primitives/api" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } codec = { package = "parity-scale-codec", version = "2.0.0" } diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 5c9dfeca0a334..861d95efb3087 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -426,7 +426,7 @@ impl GetRuntimeBlockType for Runtime { type RuntimeBlock = Block; } -#[derive(Clone, RuntimeDebug)] +#[derive(Clone, RuntimeDebug, Encode, Decode, PartialEq, Eq, TypeInfo)] pub struct Origin; impl From> for Origin { diff --git a/test-utils/runtime/src/system.rs b/test-utils/runtime/src/system.rs index 977e3212f6fe4..6df35421d3614 100644 --- a/test-utils/runtime/src/system.rs +++ b/test-utils/runtime/src/system.rs @@ -194,9 +194,10 @@ pub fn execute_transaction(utx: Extrinsic) -> ApplyExtrinsicResult { /// Finalize the block. pub fn finalize_block() -> Header { + use sp_core::storage::StateVersion; let extrinsic_index: u32 = storage::unhashed::take(well_known_keys::EXTRINSIC_INDEX).unwrap(); let txs: Vec<_> = (0..extrinsic_index).map(ExtrinsicData::take).collect(); - let extrinsics_root = trie::blake2_256_ordered_root(txs); + let extrinsics_root = trie::blake2_256_ordered_root(txs, StateVersion::V0); let number = ::take().expect("Number is set by `initialize_block`"); let parent_hash = ::take(); let mut digest = ::take().expect("StorageDigest is set by `initialize_block`"); @@ -205,8 +206,8 @@ pub fn finalize_block() -> Header { // This MUST come after all changes to storage are done. Otherwise we will fail the // “Storage root does not match that calculated” assertion. - let storage_root = - Hash::decode(&mut &storage_root()[..]).expect("`storage_root` is a valid hash"); + let storage_root = Hash::decode(&mut &storage_root(StateVersion::V1)[..]) + .expect("`storage_root` is a valid hash"); if let Some(new_authorities) = o_new_authorities { digest.push(generic::DigestItem::Consensus(*b"aura", new_authorities.encode())); diff --git a/test-utils/runtime/transaction-pool/Cargo.toml b/test-utils/runtime/transaction-pool/Cargo.toml index 39221a2d15794..ef2ebd64fb225 100644 --- a/test-utils/runtime/transaction-pool/Cargo.toml +++ b/test-utils/runtime/transaction-pool/Cargo.toml @@ -16,8 +16,8 @@ substrate-test-runtime-client = { version = "2.0.0", path = "../client" } parking_lot = "0.11.2" codec = { package = "parity-scale-codec", version = "2.0.0" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } sc-transaction-pool = { version = "4.0.0-dev", path = "../../../client/transaction-pool" } sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../../client/transaction-pool/api" } futures = "0.3.16" -derive_more = "0.99.16" +thiserror = "1.0" diff --git a/test-utils/runtime/transaction-pool/src/lib.rs b/test-utils/runtime/transaction-pool/src/lib.rs index ba317f57f531a..4008427623499 100644 --- a/test-utils/runtime/transaction-pool/src/lib.rs +++ b/test-utils/runtime/transaction-pool/src/lib.rs @@ -40,8 +40,9 @@ use substrate_test_runtime_client::{ }; /// Error type used by [`TestApi`]. -#[derive(Debug, derive_more::From, derive_more::Display)] -pub struct Error(sc_transaction_pool_api::error::Error); +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub struct Error(#[from] sc_transaction_pool_api::error::Error); impl sc_transaction_pool_api::error::IntoPoolError for Error { fn into_pool_error(self) -> Result { @@ -49,12 +50,6 @@ impl sc_transaction_pool_api::error::IntoPoolError for Error { } } -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - Some(&self.0) - } -} - pub enum IsBestBlock { Yes, No, diff --git a/utils/frame/benchmarking-cli/Cargo.toml b/utils/frame/benchmarking-cli/Cargo.toml index fa91956ec7949..9e2de0e8c358a 100644 --- a/utils/frame/benchmarking-cli/Cargo.toml +++ b/utils/frame/benchmarking-cli/Cargo.toml @@ -15,19 +15,20 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] frame-benchmarking = { version = "4.0.0-dev", path = "../../../frame/benchmarking" } frame-support = { version = "4.0.0-dev", path = "../../../frame/support" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } sc-service = { version = "0.10.0-dev", default-features = false, path = "../../../client/service" } sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" } sc-client-db = { version = "0.10.0-dev", path = "../../../client/db" } sc-executor = { version = "0.10.0-dev", path = "../../../client/executor" } -sp-externalities = { version = "0.10.0", path = "../../../primitives/externalities" } -sp-keystore = { version = "0.10.0", path = "../../../primitives/keystore" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } -sp-state-machine = { version = "0.10.0", path = "../../../primitives/state-machine" } +sp-externalities = { version = "0.11.0", path = "../../../primitives/externalities" } +sp-keystore = { version = "0.11.0", path = "../../../primitives/keystore" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } +sp-state-machine = { version = "0.11.0", path = "../../../primitives/state-machine" } codec = { version = "2.0.0", package = "parity-scale-codec" } -structopt = "0.3.25" +clap = { version = "3.0", features = ["derive"] } chrono = "0.4" -serde = "1.0.132" +serde = "1.0.136" +serde_json = "1.0.74" handlebars = "4.1.6" Inflector = "0.11.4" linked-hash-map = "0.5.4" diff --git a/utils/frame/benchmarking-cli/src/command.rs b/utils/frame/benchmarking-cli/src/command.rs index a5046dbaad2ac..0ced8b28ce016 100644 --- a/utils/frame/benchmarking-cli/src/command.rs +++ b/utils/frame/benchmarking-cli/src/command.rs @@ -35,7 +35,7 @@ use sp_externalities::Extensions; use sp_keystore::{testing::KeyStore, KeystoreExt, SyncCryptoStorePtr}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use sp_state_machine::StateMachine; -use std::{fmt::Debug, sync::Arc, time}; +use std::{fmt::Debug, fs, sync::Arc, time}; // This takes multiple benchmark batches and combines all the results where the pallet, instance, // and benchmark are the same. @@ -165,7 +165,7 @@ impl BenchmarkCmd { sp_core::testing::TaskExecutor::new(), ) .execute(strategy.into()) - .map_err(|e| format!("Error getting benchmark list: {:?}", e))?; + .map_err(|e| format!("Error getting benchmark list: {}", e))?; let (list, storage_info) = <(Vec, Vec) as Decode>::decode(&mut &result[..]) @@ -265,7 +265,7 @@ impl BenchmarkCmd { ) .execute(strategy.into()) .map_err(|e| { - format!("Error executing and verifying runtime benchmark: {:?}", e) + format!("Error executing and verifying runtime benchmark: {}", e) })?; } // Do one loop of DB tracking. @@ -290,7 +290,7 @@ impl BenchmarkCmd { sp_core::testing::TaskExecutor::new(), ) .execute(strategy.into()) - .map_err(|e| format!("Error executing runtime benchmark: {:?}", e))?; + .map_err(|e| format!("Error executing runtime benchmark: {}", e))?; let batch = , String> as Decode>::decode( @@ -322,7 +322,7 @@ impl BenchmarkCmd { sp_core::testing::TaskExecutor::new(), ) .execute(strategy.into()) - .map_err(|e| format!("Error executing runtime benchmark: {:?}", e))?; + .map_err(|e| format!("Error executing runtime benchmark: {}", e))?; let batch = , String> as Decode>::decode( @@ -357,55 +357,61 @@ impl BenchmarkCmd { // are together. let batches: Vec = combine_batches(batches, batches_db); + // Create the weights.rs file. if let Some(output_path) = &self.output { crate::writer::write_results(&batches, &storage_info, output_path, self)?; } + // Jsonify the result and write it to a file or stdout if desired. + if !self.jsonify(&batches)? { + // Print the summary only if `jsonify` did not write to stdout. + self.print_summary(&batches, &storage_info) + } + Ok(()) + } + + /// Jsonifies the passed batches and writes them to stdout or into a file. + /// Can be configured via `--json` and `--json-file`. + /// Returns whether it wrote to stdout. + fn jsonify(&self, batches: &Vec) -> Result { + if self.json_output || self.json_file.is_some() { + let json = serde_json::to_string_pretty(&batches) + .map_err(|e| format!("Serializing into JSON: {:?}", e))?; + + if let Some(path) = &self.json_file { + fs::write(path, json)?; + } else { + println!("{}", json); + return Ok(true) + } + } + + Ok(false) + } + + /// Prints the results as human-readable summary without raw timing data. + fn print_summary( + &self, + batches: &Vec, + storage_info: &Vec, + ) { for batch in batches.into_iter() { // Print benchmark metadata println!( - "Pallet: {:?}, Extrinsic: {:?}, Lowest values: {:?}, Highest values: {:?}, Steps: {:?}, Repeat: {:?}", - String::from_utf8(batch.pallet).expect("Encoded from String; qed"), - String::from_utf8(batch.benchmark).expect("Encoded from String; qed"), - self.lowest_range_values, - self.highest_range_values, - self.steps, - self.repeat, - ); + "Pallet: {:?}, Extrinsic: {:?}, Lowest values: {:?}, Highest values: {:?}, Steps: {:?}, Repeat: {:?}", + String::from_utf8(batch.pallet.clone()).expect("Encoded from String; qed"), + String::from_utf8(batch.benchmark.clone()).expect("Encoded from String; qed"), + self.lowest_range_values, + self.highest_range_values, + self.steps, + self.repeat, + ); // Skip raw data + analysis if there are no results if batch.time_results.is_empty() { continue } - if self.raw_data { - // Print the table header - batch.time_results[0] - .components - .iter() - .for_each(|param| print!("{:?},", param.0)); - - print!("extrinsic_time_ns,storage_root_time_ns,reads,repeat_reads,writes,repeat_writes,proof_size_bytes\n"); - // Print the values - batch.time_results.iter().for_each(|result| { - let parameters = &result.components; - parameters.iter().for_each(|param| print!("{:?},", param.1)); - // Print extrinsic time and storage root time - print!( - "{:?},{:?},{:?},{:?},{:?},{:?},{:?}\n", - result.extrinsic_time, - result.storage_root_time, - result.reads, - result.repeat_reads, - result.writes, - result.repeat_writes, - result.proof_size, - ); - }); - - println!(); - } - if !self.no_storage_info { let mut comments: Vec = Default::default(); crate::writer::add_storage_comments( @@ -460,8 +466,6 @@ impl BenchmarkCmd { println!(""); } } - - Ok(()) } } diff --git a/utils/frame/benchmarking-cli/src/lib.rs b/utils/frame/benchmarking-cli/src/lib.rs index 664e526ae0d7b..3b0f4843d2065 100644 --- a/utils/frame/benchmarking-cli/src/lib.rs +++ b/utils/frame/benchmarking-cli/src/lib.rs @@ -19,7 +19,7 @@ mod command; mod writer; use sc_cli::{ExecutionStrategy, WasmExecutionMethod}; -use std::fmt::Debug; +use std::{fmt::Debug, path::PathBuf}; // Add a more relaxed parsing for pallet names by allowing pallet directory names with `-` to be // used like crate names with `_` @@ -28,124 +28,123 @@ fn parse_pallet_name(pallet: &str) -> String { } /// The `benchmark` command used to benchmark FRAME Pallets. -#[derive(Debug, structopt::StructOpt)] +#[derive(Debug, clap::Parser)] pub struct BenchmarkCmd { /// Select a FRAME Pallet to benchmark, or `*` for all (in which case `extrinsic` must be `*`). - #[structopt(short, long, parse(from_str = parse_pallet_name), required_unless = "list")] + #[clap(short, long, parse(from_str = parse_pallet_name), required_unless_present = "list")] pub pallet: Option, /// Select an extrinsic inside the pallet to benchmark, or `*` for all. - #[structopt(short, long, required_unless = "list")] + #[clap(short, long, required_unless_present = "list")] pub extrinsic: Option, /// Select how many samples we should take across the variable components. - #[structopt(short, long, default_value = "1")] + #[clap(short, long, default_value = "1")] pub steps: u32, /// Indicates lowest values for each of the component ranges. - #[structopt(long = "low", use_delimiter = true)] + #[clap(long = "low", use_delimiter = true)] pub lowest_range_values: Vec, /// Indicates highest values for each of the component ranges. - #[structopt(long = "high", use_delimiter = true)] + #[clap(long = "high", use_delimiter = true)] pub highest_range_values: Vec, /// Select how many repetitions of this benchmark should run from within the wasm. - #[structopt(short, long, default_value = "1")] + #[clap(short, long, default_value = "1")] pub repeat: u32, /// Select how many repetitions of this benchmark should run from the client. /// /// NOTE: Using this alone may give slower results, but will afford you maximum Wasm memory. - #[structopt(long, default_value = "1")] + #[clap(long, default_value = "1")] pub external_repeat: u32, - /// Print the raw results. - #[structopt(long = "raw")] - pub raw_data: bool, + /// Print the raw results in JSON format. + #[clap(long = "json")] + pub json_output: bool, + + /// Write the raw results in JSON format into the give file. + #[clap(long, conflicts_with = "json-output")] + pub json_file: Option, /// Don't print the median-slopes linear regression analysis. - #[structopt(long)] + #[clap(long)] pub no_median_slopes: bool, /// Don't print the min-squares linear regression analysis. - #[structopt(long)] + #[clap(long)] pub no_min_squares: bool, /// Output the benchmarks to a Rust file at the given path. - #[structopt(long)] - pub output: Option, + #[clap(long)] + pub output: Option, /// Add a header file to your outputted benchmarks - #[structopt(long)] - pub header: Option, + #[clap(long)] + pub header: Option, /// Path to Handlebars template file used for outputting benchmark results. (Optional) - #[structopt(long)] - pub template: Option, + #[clap(long)] + pub template: Option, /// Which analysis function to use when outputting benchmarks: /// * min-squares (default) /// * median-slopes /// * max (max of min squares and median slopes for each value) - #[structopt(long)] + #[clap(long)] pub output_analysis: Option, /// Set the heap pages while running benchmarks. If not set, the default value from the client /// is used. - #[structopt(long)] + #[clap(long)] pub heap_pages: Option, /// Disable verification logic when running benchmarks. - #[structopt(long)] + #[clap(long)] pub no_verify: bool, /// Display and run extra benchmarks that would otherwise not be needed for weight /// construction. - #[structopt(long)] + #[clap(long)] pub extra: bool, /// Estimate PoV size. - #[structopt(long)] + #[clap(long)] pub record_proof: bool, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub shared_params: sc_cli::SharedParams, /// The execution strategy that should be used for benchmarks - #[structopt( - long = "execution", - value_name = "STRATEGY", - possible_values = &ExecutionStrategy::variants(), - case_insensitive = true, - )] + #[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)] pub execution: Option, /// Method for executing Wasm runtime code. - #[structopt( + #[clap( long = "wasm-execution", value_name = "METHOD", - possible_values = &WasmExecutionMethod::variants(), - case_insensitive = true, + possible_values = WasmExecutionMethod::variants(), + ignore_case = true, default_value = "compiled" )] pub wasm_method: WasmExecutionMethod, /// Limit the memory the database cache can use. - #[structopt(long = "db-cache", value_name = "MiB", default_value = "1024")] + #[clap(long = "db-cache", value_name = "MiB", default_value = "1024")] pub database_cache_size: u32, /// List the benchmarks that match your query rather than running them. /// /// When nothing is provided, we list all benchmarks. - #[structopt(long)] + #[clap(long)] pub list: bool, /// If enabled, the storage info is not displayed in the output next to the analysis. /// /// This is independent of the storage info appearing in the *output file*. Use a Handlebar /// template for that purpose. - #[structopt(long)] + #[clap(long)] pub no_storage_info: bool, } diff --git a/utils/frame/frame-utilities-cli/Cargo.toml b/utils/frame/frame-utilities-cli/Cargo.toml index d256bba4b5b32..50a00db1d4d38 100644 --- a/utils/frame/frame-utilities-cli/Cargo.toml +++ b/utils/frame/frame-utilities-cli/Cargo.toml @@ -11,10 +11,11 @@ documentation = "https://docs.rs/substrate-frame-cli" readme = "README.md" [dependencies] -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } +clap = { version = "3.0", features = ["derive"] } + +sp-core = { version = "5.0.0", path = "../../../primitives/core" } sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } -structopt = "0.3.25" +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } frame-system = { version = "4.0.0-dev", path = "../../../frame/system" } frame-support = { version = "4.0.0-dev", path = "../../../frame/support" } diff --git a/utils/frame/frame-utilities-cli/src/pallet_id.rs b/utils/frame/frame-utilities-cli/src/pallet_id.rs index 2e139c639fd43..c39bee8b87463 100644 --- a/utils/frame/frame-utilities-cli/src/pallet_id.rs +++ b/utils/frame/frame-utilities-cli/src/pallet_id.rs @@ -17,6 +17,7 @@ //! Implementation of the `palletid` subcommand +use clap::Parser; use frame_support::PalletId; use sc_cli::{ utils::print_from_uri, with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams, @@ -24,35 +25,34 @@ use sc_cli::{ }; use sp_core::crypto::{unwrap_or_default_ss58_version, Ss58AddressFormat, Ss58Codec}; use sp_runtime::traits::AccountIdConversion; -use structopt::StructOpt; /// The `palletid` command -#[derive(Debug, StructOpt)] -#[structopt(name = "palletid", about = "Inspect a module ID address")] +#[derive(Debug, Parser)] +#[clap(name = "palletid", about = "Inspect a module ID address")] pub struct PalletIdCmd { /// The module ID used to derive the account id: String, /// network address format - #[structopt( + #[clap( long, value_name = "NETWORK", possible_values = &Ss58AddressFormat::all_names()[..], parse(try_from_str = Ss58AddressFormat::try_from), - case_insensitive = true, + ignore_case = true, )] pub network: Option, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub output_scheme: OutputTypeFlag, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub crypto_scheme: CryptoSchemeFlag, #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub keystore_params: KeystoreParams, } diff --git a/utils/frame/generate-bags/Cargo.toml b/utils/frame/generate-bags/Cargo.toml index 594683938517b..5bda705a581a9 100644 --- a/utils/frame/generate-bags/Cargo.toml +++ b/utils/frame/generate-bags/Cargo.toml @@ -17,10 +17,9 @@ frame-system = { version = "4.0.0-dev", path = "../../../frame/system" } pallet-staking = { version = "4.0.0-dev", path = "../../../frame/staking" } # primitives -sp-io = { version = "4.0.0", path = "../../../primitives/io" } +sp-io = { version = "5.0.0", path = "../../../primitives/io" } # third party chrono = { version = "0.4.19" } git2 = { version = "0.13.25", default-features = false } num-format = { version = "0.4.0" } -structopt = "0.3.25" diff --git a/utils/frame/generate-bags/node-runtime/Cargo.toml b/utils/frame/generate-bags/node-runtime/Cargo.toml index b5a7e0b898c92..11dee7b8b68ec 100644 --- a/utils/frame/generate-bags/node-runtime/Cargo.toml +++ b/utils/frame/generate-bags/node-runtime/Cargo.toml @@ -14,4 +14,4 @@ node-runtime = { version = "3.0.0-dev", path = "../../../../bin/node/runtime" } generate-bags = { version = "4.0.0-dev", path = "../" } # third-party -structopt = "0.3.25" +clap = { version = "3.0", features = ["derive"] } diff --git a/utils/frame/generate-bags/node-runtime/src/main.rs b/utils/frame/generate-bags/node-runtime/src/main.rs index 72d1f0d8d22b9..12bcf8d28cf2b 100644 --- a/utils/frame/generate-bags/node-runtime/src/main.rs +++ b/utils/frame/generate-bags/node-runtime/src/main.rs @@ -17,30 +17,31 @@ //! Make the set of bag thresholds to be used with pallet-bags-list. +use clap::Parser; use generate_bags::generate_thresholds; use std::path::PathBuf; -use structopt::StructOpt; -#[derive(Debug, StructOpt)] +#[derive(Debug, Parser)] +// #[clap(author, version, about)] struct Opt { /// How many bags to generate. - #[structopt(long, default_value = "200")] + #[clap(long, default_value = "200")] n_bags: usize, /// Where to write the output. output: PathBuf, /// The total issuance of the currency used to create `VoteWeight`. - #[structopt(short, long)] + #[clap(short, long)] total_issuance: u128, /// The minimum account balance (i.e. existential deposit) for the currency used to create /// `VoteWeight`. - #[structopt(short, long)] + #[clap(short, long)] minimum_balance: u128, } fn main() -> Result<(), std::io::Error> { - let Opt { n_bags, output, total_issuance, minimum_balance } = Opt::from_args(); + let Opt { n_bags, output, total_issuance, minimum_balance } = Opt::parse(); generate_thresholds::(n_bags, &output, total_issuance, minimum_balance) } diff --git a/utils/frame/remote-externalities/Cargo.toml b/utils/frame/remote-externalities/Cargo.toml index 6d926846b4a36..cf8a0f6069879 100644 --- a/utils/frame/remote-externalities/Cargo.toml +++ b/utils/frame/remote-externalities/Cargo.toml @@ -13,18 +13,18 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -jsonrpsee = { version = "0.4.1", features = ["ws-client", "macros"] } +jsonrpsee = { version = "0.8", features = ["ws-client", "macros"] } env_logger = "0.9" frame-support = { path = "../../../frame/support", optional = true, version = "4.0.0-dev" } log = "0.4.11" codec = { package = "parity-scale-codec", version = "2.0.0" } serde_json = "1.0" -serde = "1.0.132" +serde = "1.0.136" -sp-io = { version = "4.0.0-dev", path = "../../../primitives/io" } -sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } -sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } +sp-io = { version = "5.0.0", path = "../../../primitives/io" } +sp-core = { version = "5.0.0", path = "../../../primitives/core" } +sp-runtime = { version = "5.0.0", path = "../../../primitives/runtime" } sp-version = { version = "4.0.0-dev", path = "../../../primitives/version" } [dev-dependencies] diff --git a/utils/frame/remote-externalities/src/lib.rs b/utils/frame/remote-externalities/src/lib.rs index 16aa60db1841c..d6dfd1c59d4ee 100644 --- a/utils/frame/remote-externalities/src/lib.rs +++ b/utils/frame/remote-externalities/src/lib.rs @@ -23,9 +23,9 @@ use codec::{Decode, Encode}; use jsonrpsee::{ + core::{client::ClientT, Error as RpcError}, proc_macros::rpc, rpc_params, - types::{traits::Client, Error as RpcError}, ws_client::{WsClient, WsClientBuilder}, }; @@ -44,6 +44,7 @@ use sp_runtime::traits::Block as BlockT; use std::{ fs, path::{Path, PathBuf}, + sync::Arc, }; pub mod rpc_api; @@ -123,21 +124,52 @@ impl> From

for SnapshotConfig { } /// Description of the transport protocol (for online execution). -#[derive(Debug)] -pub struct Transport { - uri: String, - client: Option, +#[derive(Debug, Clone)] +pub enum Transport { + /// Use the `URI` to open a new WebSocket connection. + Uri(String), + /// Use existing WebSocket connection. + RemoteClient(Arc), } -impl Clone for Transport { - fn clone(&self) -> Self { - Self { uri: self.uri.clone(), client: None } +impl Transport { + fn as_client(&self) -> Option<&WsClient> { + match self { + Self::RemoteClient(client) => Some(&*client), + _ => None, + } + } + + // Open a new WebSocket connection if it's not connected. + async fn map_uri(&mut self) -> Result<(), &'static str> { + if let Self::Uri(uri) = self { + log::debug!(target: LOG_TARGET, "initializing remote client to {:?}", uri); + + let ws_client = WsClientBuilder::default() + .max_request_body_size(u32::MAX) + .build(&uri) + .await + .map_err(|e| { + log::error!(target: LOG_TARGET, "error: {:?}", e); + "failed to build ws client" + })?; + + *self = Self::RemoteClient(Arc::new(ws_client)) + } + + Ok(()) } } impl From for Transport { - fn from(t: String) -> Self { - Self { uri: t, client: None } + fn from(uri: String) -> Self { + Transport::Uri(uri) + } +} + +impl From> for Transport { + fn from(client: Arc) -> Self { + Transport::RemoteClient(client) } } @@ -161,8 +193,7 @@ impl OnlineConfig { /// Return rpc (ws) client. fn rpc_client(&self) -> &WsClient { self.transport - .client - .as_ref() + .as_client() .expect("ws client must have been initialized by now; qed.") } } @@ -170,7 +201,7 @@ impl OnlineConfig { impl Default for OnlineConfig { fn default() -> Self { Self { - transport: Transport { uri: DEFAULT_TARGET.to_owned(), client: None }, + transport: Transport::Uri(DEFAULT_TARGET.to_owned()), at: None, state_snapshot: None, pallets: vec![], @@ -629,19 +660,8 @@ impl Builder { } pub(crate) async fn init_remote_client(&mut self) -> Result<(), &'static str> { - let mut online = self.as_online_mut(); - log::debug!(target: LOG_TARGET, "initializing remote client to {:?}", online.transport.uri); - // First, initialize the ws client. - let ws_client = WsClientBuilder::default() - .max_request_body_size(u32::MAX) - .build(&online.transport.uri) - .await - .map_err(|e| { - log::error!(target: LOG_TARGET, "error: {:?}", e); - "failed to build ws client" - })?; - online.transport.client = Some(ws_client); + self.as_online_mut().transport.map_uri().await?; // Then, if `at` is not set, set it. if self.as_online().at.is_none() { diff --git a/utils/frame/remote-externalities/src/rpc_api.rs b/utils/frame/remote-externalities/src/rpc_api.rs index 13254741c1acb..37555de480d4c 100644 --- a/utils/frame/remote-externalities/src/rpc_api.rs +++ b/utils/frame/remote-externalities/src/rpc_api.rs @@ -19,8 +19,8 @@ // TODO: Consolidate one off RPC calls https://github.com/paritytech/substrate/issues/8988 use jsonrpsee::{ + core::client::ClientT, rpc_params, - types::traits::Client, ws_client::{WsClient, WsClientBuilder}, }; use sp_runtime::{ @@ -73,7 +73,7 @@ where Ok(signed_block.block) } -/// Build a website client that connects to `from`. +/// Build a websocket client that connects to `from`. async fn build_client>(from: S) -> Result { WsClientBuilder::default() .max_request_body_size(u32::MAX) diff --git a/utils/frame/rpc/support/Cargo.toml b/utils/frame/rpc/support/Cargo.toml index 6ecaabd720595..fcb5a4367386d 100644 --- a/utils/frame/rpc/support/Cargo.toml +++ b/utils/frame/rpc/support/Cargo.toml @@ -20,7 +20,7 @@ jsonrpc-client-transports = { version = "18.0.0", features = ["http"] } codec = { package = "parity-scale-codec", version = "2.0.0" } serde = "1" frame-support = { version = "4.0.0-dev", path = "../../../../frame/support" } -sp-storage = { version = "4.0.0", path = "../../../../primitives/storage" } +sp-storage = { version = "5.0.0", path = "../../../../primitives/storage" } sc-rpc-api = { version = "0.10.0-dev", path = "../../../../client/rpc-api" } [dev-dependencies] diff --git a/utils/frame/rpc/system/Cargo.toml b/utils/frame/rpc/system/Cargo.toml index cb801c6cbf275..8ce72416dac2a 100644 --- a/utils/frame/rpc/system/Cargo.toml +++ b/utils/frame/rpc/system/Cargo.toml @@ -20,10 +20,10 @@ jsonrpc-core = "18.0.0" jsonrpc-core-client = "18.0.0" jsonrpc-derive = "18.0.0" log = "0.4.8" -sp-runtime = { version = "4.1.0-dev", path = "../../../../primitives/runtime" } +sp-runtime = { version = "5.0.0", path = "../../../../primitives/runtime" } sp-api = { version = "4.0.0-dev", path = "../../../../primitives/api" } frame-system-rpc-runtime-api = { version = "4.0.0-dev", path = "../../../../frame/system/rpc/runtime-api" } -sp-core = { version = "4.1.0-dev", path = "../../../../primitives/core" } +sp-core = { version = "5.0.0", path = "../../../../primitives/core" } sp-blockchain = { version = "4.0.0-dev", path = "../../../../primitives/blockchain" } sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../../../client/transaction-pool/api" } sp-block-builder = { version = "4.0.0-dev", path = "../../../../primitives/block-builder" } diff --git a/utils/frame/rpc/system/src/lib.rs b/utils/frame/rpc/system/src/lib.rs index df24e208b51a4..eb1b258c97ec6 100644 --- a/utils/frame/rpc/system/src/lib.rs +++ b/utils/frame/rpc/system/src/lib.rs @@ -106,7 +106,7 @@ where let nonce = api.account_nonce(&at, account.clone()).map_err(|e| RpcError { code: ErrorCode::ServerError(Error::RuntimeError.into()), message: "Unable to query nonce.".into(), - data: Some(format!("{:?}", e).into()), + data: Some(e.to_string().into()), })?; Ok(adjust_nonce(&*self.pool, account, nonce)) @@ -141,7 +141,7 @@ where let result = api.apply_extrinsic(&at, uxt).map_err(|e| RpcError { code: ErrorCode::ServerError(Error::RuntimeError.into()), message: "Unable to dry run extrinsic.".into(), - data: Some(format!("{:?}", e).into()), + data: Some(e.to_string().into()), })?; Ok(Encode::encode(&result).into()) diff --git a/utils/frame/try-runtime/cli/Cargo.toml b/utils/frame/try-runtime/cli/Cargo.toml index 2e214ec2307b7..12380e2d3272f 100644 --- a/utils/frame/try-runtime/cli/Cargo.toml +++ b/utils/frame/try-runtime/cli/Cargo.toml @@ -13,24 +13,23 @@ readme = "README.md" targets = ["x86_64-unknown-linux-gnu"] [dependencies] +clap = { version = "3.0", features = ["derive"] } log = "0.4.8" parity-scale-codec = { version = "2.3.1" } -serde = "1.0.132" -structopt = "0.3.25" +serde = "1.0.136" +zstd = "0.9.0" sc-service = { version = "0.10.0-dev", default-features = false, path = "../../../../client/service" } sc-cli = { version = "0.10.0-dev", path = "../../../../client/cli" } sc-executor = { version = "0.10.0-dev", path = "../../../../client/executor" } sc-chain-spec = { version = "4.0.0-dev", path = "../../../../client/chain-spec" } -sp-state-machine = { version = "0.10.0", path = "../../../../primitives/state-machine" } -sp-runtime = { version = "4.1.0-dev", path = "../../../../primitives/runtime" } -sp-core = { version = "4.1.0-dev", path = "../../../../primitives/core" } -sp-io = { version = "4.0.0-dev", path = "../../../../primitives/io" } -sp-keystore = { version = "0.10.0", path = "../../../../primitives/keystore" } -sp-externalities = { version = "0.10.0", path = "../../../../primitives/externalities" } +sp-state-machine = { version = "0.11.0", path = "../../../../primitives/state-machine" } +sp-runtime = { version = "5.0.0", path = "../../../../primitives/runtime" } +sp-core = { version = "5.0.0", path = "../../../../primitives/core" } +sp-io = { version = "5.0.0", path = "../../../../primitives/io" } +sp-keystore = { version = "0.11.0", path = "../../../../primitives/keystore" } +sp-externalities = { version = "0.11.0", path = "../../../../primitives/externalities" } sp-version = { version = "4.0.0-dev", path = "../../../../primitives/version" } remote-externalities = { version = "0.10.0-dev", path = "../../remote-externalities" } -jsonrpsee = { version = "0.4.1", default-features = false, features = ["ws-client"]} - -zstd = "0.9.0" +jsonrpsee = { version = "0.4.1", default-features = false, features = ["ws-client"] } diff --git a/utils/frame/try-runtime/cli/src/commands/execute_block.rs b/utils/frame/try-runtime/cli/src/commands/execute_block.rs index 68c33b17b99de..b1a56f7e8f8eb 100644 --- a/utils/frame/try-runtime/cli/src/commands/execute_block.rs +++ b/utils/frame/try-runtime/cli/src/commands/execute_block.rs @@ -26,25 +26,25 @@ use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor}; use std::{fmt::Debug, str::FromStr}; /// Configurations of the [`Command::ExecuteBlock`]. -#[derive(Debug, Clone, structopt::StructOpt)] +#[derive(Debug, Clone, clap::Parser)] pub struct ExecuteBlockCmd { /// Overwrite the wasm code in state or not. - #[structopt(long)] + #[clap(long)] overwrite_wasm_code: bool, /// If set, then the state root check is disabled by the virtue of calling into /// `TryRuntime_execute_block_no_check` instead of /// `Core_execute_block`. - #[structopt(long)] + #[clap(long)] no_check: bool, /// The block hash at which to fetch the block. /// /// If the `live` state type is being used, then this can be omitted, and is equal to whatever /// the `state::at` is. Only use this (with care) when combined with a snapshot. - #[structopt( + #[clap( long, - multiple = false, + multiple_values = false, parse(try_from_str = crate::parse::hash) )] block_at: Option, @@ -53,9 +53,9 @@ pub struct ExecuteBlockCmd { /// /// If the `live` state type is being used, then this can be omitted, and is equal to whatever /// the `state::uri` is. Only use this (with care) when combined with a snapshot. - #[structopt( + #[clap( long, - multiple = false, + multiple_values = false, parse(try_from_str = crate::parse::url) )] block_ws_uri: Option, @@ -65,7 +65,7 @@ pub struct ExecuteBlockCmd { /// For this command only, if the `live` is used, then state of the parent block is fetched. /// /// If `block_at` is provided, then the [`State::Live::at`] is being ignored. - #[structopt(subcommand)] + #[clap(subcommand)] state: State, } diff --git a/utils/frame/try-runtime/cli/src/commands/follow_chain.rs b/utils/frame/try-runtime/cli/src/commands/follow_chain.rs index 445756f9eed99..82bc04880106e 100644 --- a/utils/frame/try-runtime/cli/src/commands/follow_chain.rs +++ b/utils/frame/try-runtime/cli/src/commands/follow_chain.rs @@ -35,14 +35,10 @@ const SUB: &'static str = "chain_subscribeFinalizedHeads"; const UN_SUB: &'static str = "chain_unsubscribeFinalizedHeads"; /// Configurations of the [`Command::FollowChain`]. -#[derive(Debug, Clone, structopt::StructOpt)] +#[derive(Debug, Clone, clap::Parser)] pub struct FollowChainCmd { /// The url to connect to. - #[structopt( - short, - long, - parse(try_from_str = parse::url), - )] + #[clap(short, long, parse(try_from_str = parse::url))] uri: String, } diff --git a/utils/frame/try-runtime/cli/src/commands/offchain_worker.rs b/utils/frame/try-runtime/cli/src/commands/offchain_worker.rs index 47af85560398e..72136e9236de5 100644 --- a/utils/frame/try-runtime/cli/src/commands/offchain_worker.rs +++ b/utils/frame/try-runtime/cli/src/commands/offchain_worker.rs @@ -28,19 +28,19 @@ use sp_runtime::traits::{Block as BlockT, Header, NumberFor}; use std::{fmt::Debug, str::FromStr}; /// Configurations of the [`Command::OffchainWorker`]. -#[derive(Debug, Clone, structopt::StructOpt)] +#[derive(Debug, Clone, clap::Parser)] pub struct OffchainWorkerCmd { /// Overwrite the wasm code in state or not. - #[structopt(long)] + #[clap(long)] overwrite_wasm_code: bool, /// The block hash at which to fetch the header. /// /// If the `live` state type is being used, then this can be omitted, and is equal to whatever /// the `state::at` is. Only use this (with care) when combined with a snapshot. - #[structopt( + #[clap( long, - multiple = false, + multiple_values = false, parse(try_from_str = parse::hash) )] header_at: Option, @@ -49,15 +49,15 @@ pub struct OffchainWorkerCmd { /// /// If the `live` state type is being used, then this can be omitted, and is equal to whatever /// the `state::uri` is. Only use this (with care) when combined with a snapshot. - #[structopt( + #[clap( long, - multiple = false, + multiple_values = false, parse(try_from_str = parse::url) )] header_ws_uri: Option, /// The state type to use. - #[structopt(subcommand)] + #[clap(subcommand)] pub state: State, } diff --git a/utils/frame/try-runtime/cli/src/commands/on_runtime_upgrade.rs b/utils/frame/try-runtime/cli/src/commands/on_runtime_upgrade.rs index 30e638217448f..616498da02497 100644 --- a/utils/frame/try-runtime/cli/src/commands/on_runtime_upgrade.rs +++ b/utils/frame/try-runtime/cli/src/commands/on_runtime_upgrade.rs @@ -28,10 +28,10 @@ use crate::{ }; /// Configurations of the [`Command::OnRuntimeUpgrade`]. -#[derive(Debug, Clone, structopt::StructOpt)] +#[derive(Debug, Clone, clap::Parser)] pub struct OnRuntimeUpgradeCmd { /// The state type to use. - #[structopt(subcommand)] + #[clap(subcommand)] pub state: State, } diff --git a/utils/frame/try-runtime/cli/src/lib.rs b/utils/frame/try-runtime/cli/src/lib.rs index 32c814b0443d0..ae7a1c3ae87ca 100644 --- a/utils/frame/try-runtime/cli/src/lib.rs +++ b/utils/frame/try-runtime/cli/src/lib.rs @@ -113,6 +113,8 @@ //! well with try-runtime's expensive RPC queries: //! //! - set `--rpc-max-payload 1000` to ensure large RPC queries can work. +//! - set `--ws-max-out-buffer-capacity 1000` to ensure the websocket connection can handle large +//! RPC queries. //! - set `--rpc-cors all` to ensure ws connections can come through. //! //! Note that *none* of the try-runtime operations need unsafe RPCs. @@ -141,7 +143,9 @@ //! //! These hooks allow you to execute some code, only within the `on-runtime-upgrade` command, before //! and after the migration. If any data needs to be temporarily stored between the pre/post -//! migration hooks, `OnRuntimeUpgradeHelpersExt` can help with that. +//! migration hooks, `OnRuntimeUpgradeHelpersExt` can help with that. Note that you should be +//! mindful with any mutable storage ops in the pre/post migration checks, as you almost certainly +//! will not want to mutate any of the storage that is to be migrated. //! //! #### Logging //! @@ -293,7 +297,7 @@ pub(crate) mod parse; pub(crate) const LOG_TARGET: &'static str = "try-runtime::cli"; /// Possible commands of `try-runtime`. -#[derive(Debug, Clone, structopt::StructOpt)] +#[derive(Debug, Clone, clap::Subcommand)] pub enum Command { /// Execute the migrations of the "local runtime". /// @@ -373,70 +377,64 @@ pub enum Command { } /// Shared parameters of the `try-runtime` commands -#[derive(Debug, Clone, structopt::StructOpt)] +#[derive(Debug, Clone, clap::Parser)] pub struct SharedParams { /// Shared parameters of substrate cli. #[allow(missing_docs)] - #[structopt(flatten)] + #[clap(flatten)] pub shared_params: sc_cli::SharedParams, /// The execution strategy that should be used. - #[structopt( - long = "execution", - value_name = "STRATEGY", - possible_values = &ExecutionStrategy::variants(), - case_insensitive = true, - default_value = "Wasm", - )] + #[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true, default_value = "Wasm")] pub execution: ExecutionStrategy, /// Type of wasm execution used. - #[structopt( + #[clap( long = "wasm-execution", value_name = "METHOD", - possible_values = &WasmExecutionMethod::variants(), - case_insensitive = true, + possible_values = WasmExecutionMethod::variants(), + ignore_case = true, default_value = "Compiled" )] pub wasm_method: WasmExecutionMethod, /// The number of 64KB pages to allocate for Wasm execution. Defaults to /// [`sc_service::Configuration.default_heap_pages`]. - #[structopt(long)] + #[clap(long)] pub heap_pages: Option, /// When enabled, the spec name check will not panic, and instead only show a warning. - #[structopt(long)] + #[clap(long)] pub no_spec_name_check: bool, } /// Our `try-runtime` command. /// /// See [`Command`] for more info. -#[derive(Debug, Clone, structopt::StructOpt)] +#[derive(Debug, Clone, clap::Parser)] pub struct TryRuntimeCmd { - #[structopt(flatten)] + #[clap(flatten)] pub shared: SharedParams, - #[structopt(subcommand)] + #[clap(subcommand)] pub command: Command, } /// The source of runtime *state* to use. -#[derive(Debug, Clone, structopt::StructOpt)] +#[derive(Debug, Clone, clap::Subcommand)] pub enum State { /// Use a state snapshot as the source of runtime state. /// /// This can be crated by passing a value to [`State::Live::snapshot_path`]. Snap { - #[structopt(short, long)] + #[clap(short, long)] snapshot_path: PathBuf, }, /// Use a live chain as the source of runtime state. Live { /// The url to connect to. - #[structopt( + #[clap( short, long, parse(try_from_str = parse::url), @@ -447,20 +445,20 @@ pub enum State { /// /// If non provided, then the latest finalized head is used. This is particularly useful /// for [`Command::OnRuntimeUpgrade`]. - #[structopt( + #[clap( short, long, - multiple = false, + multiple_values = false, parse(try_from_str = parse::hash), )] at: Option, /// An optional state snapshot file to WRITE to. Not written if set to `None`. - #[structopt(short, long)] + #[clap(short, long)] snapshot_path: Option, /// The pallets to scrape. If empty, entire chain state will be scraped. - #[structopt(short, long, require_delimiter = true)] + #[clap(short, long, require_delimiter = true)] pallets: Option>, /// Fetch the child-keys as well. @@ -468,7 +466,7 @@ pub enum State { /// Default is `false`, if specific `pallets` are specified, true otherwise. In other /// words, if you scrape the whole state the child tree data is included out of the box. /// Otherwise, it must be enabled explicitly using this flag. - #[structopt(long, require_delimiter = true)] + #[clap(long, require_delimiter = true)] child_tree: bool, }, } @@ -709,7 +707,7 @@ pub(crate) fn state_machine_call(Into::into)?; Ok((changes, encoded_results)) @@ -750,7 +748,7 @@ pub(crate) fn state_machine_call_with_proof(Into::into)?; let proof = proving_backend.extract_proof(); diff --git a/utils/prometheus/Cargo.toml b/utils/prometheus/Cargo.toml index 4ae38f6455327..27b5f94305fdd 100644 --- a/utils/prometheus/Cargo.toml +++ b/utils/prometheus/Cargo.toml @@ -16,7 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"] log = "0.4.8" prometheus = { version = "0.13.0", default-features = false } futures-util = { version = "0.3.19", default-features = false, features = ["io"] } -derive_more = "0.99" +thiserror = "1.0" async-std = { version = "1.10.0", features = ["unstable"] } tokio = "1.15" hyper = { version = "0.14.16", default-features = false, features = ["http1", "server", "tcp"] } diff --git a/utils/prometheus/src/lib.rs b/utils/prometheus/src/lib.rs index f1d87ac9f729c..3d28d9cd6f1c8 100644 --- a/utils/prometheus/src/lib.rs +++ b/utils/prometheus/src/lib.rs @@ -47,27 +47,22 @@ pub fn register( Ok(metric) } -#[derive(Debug, derive_more::Display, derive_more::From)] +#[derive(Debug, thiserror::Error)] pub enum Error { /// Hyper internal error. - Hyper(hyper::Error), + #[error(transparent)] + Hyper(#[from] hyper::Error), + /// Http request error. - Http(hyper::http::Error), + #[error(transparent)] + Http(#[from] hyper::http::Error), + /// i/o error. - Io(std::io::Error), - #[display(fmt = "Prometheus port {} already in use.", _0)] - PortInUse(SocketAddr), -} + #[error(transparent)] + Io(#[from] std::io::Error), -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Error::Hyper(error) => Some(error), - Error::Http(error) => Some(error), - Error::Io(error) => Some(error), - Error::PortInUse(_) => None, - } - } + #[error("Prometheus port {0} already in use.")] + PortInUse(SocketAddr), } async fn request_metrics(req: Request, registry: Registry) -> Result, Error> { diff --git a/utils/wasm-builder/Cargo.toml b/utils/wasm-builder/Cargo.toml index a2a56a5bf22cf..ce9687f9ae0ef 100644 --- a/utils/wasm-builder/Cargo.toml +++ b/utils/wasm-builder/Cargo.toml @@ -21,3 +21,4 @@ walkdir = "2.3.2" wasm-gc-api = "0.1.11" ansi_term = "0.12.1" sp-maybe-compressed-blob = { version = "4.1.0-dev", path = "../../primitives/maybe-compressed-blob" } +strum = { version = "0.23.0", features = ["derive"] } diff --git a/utils/wasm-builder/src/lib.rs b/utils/wasm-builder/src/lib.rs index 899903d96d169..6a7f0d7ca3cd5 100644 --- a/utils/wasm-builder/src/lib.rs +++ b/utils/wasm-builder/src/lib.rs @@ -83,6 +83,10 @@ //! needs to be absolute. //! - `WASM_BUILD_TOOLCHAIN` - The toolchain that should be used to build the Wasm binaries. The //! format needs to be the same as used by cargo, e.g. `nightly-2020-02-20`. +//! - `WASM_BUILD_WORKSPACE_HINT` - Hint the workspace that is being built. This is normally not +//! required as we walk up from the target directory until we find a `Cargo.toml`. If the target +//! directory is changed for the build, this environment variable can be used to point to the +//! actual workspace. //! //! Each project can be skipped individually by using the environment variable //! `SKIP_PROJECT_NAME_WASM_BUILD`. Where `PROJECT_NAME` needs to be replaced by the name of the @@ -116,9 +120,11 @@ pub use builder::{WasmBuilder, WasmBuilderSelectProject}; const SKIP_BUILD_ENV: &str = "SKIP_WASM_BUILD"; /// Environment variable to force a certain build type when building the wasm binary. -/// Expects "debug" or "release" as value. +/// Expects "debug", "release" or "production" as value. /// -/// By default the WASM binary uses the same build type as the main cargo build. +/// When unset the WASM binary uses the same build type as the main cargo build with +/// the exception of a debug build: In this case the wasm build defaults to `release` in +/// order to avoid a slowdown when not explicitly requested. const WASM_BUILD_TYPE_ENV: &str = "WASM_BUILD_TYPE"; /// Environment variable to extend the `RUSTFLAGS` variable given to the wasm build. @@ -138,6 +144,9 @@ const WASM_BUILD_TOOLCHAIN: &str = "WASM_BUILD_TOOLCHAIN"; /// Environment variable that makes sure the WASM build is triggered. const FORCE_WASM_BUILD_ENV: &str = "FORCE_WASM_BUILD"; +/// Environment variable that hints the workspace we are building. +const WASM_BUILD_WORKSPACE_HINT: &str = "WASM_BUILD_WORKSPACE_HINT"; + /// Write to the given `file` if the `content` is different. fn write_file_if_changed(file: impl AsRef, content: impl AsRef) { if fs::read_to_string(file.as_ref()).ok().as_deref() != Some(content.as_ref()) { diff --git a/utils/wasm-builder/src/wasm_project.rs b/utils/wasm-builder/src/wasm_project.rs index cf437ee7f0e6c..20e176444c621 100644 --- a/utils/wasm-builder/src/wasm_project.rs +++ b/utils/wasm-builder/src/wasm_project.rs @@ -17,6 +17,8 @@ use crate::{write_file_if_changed, CargoCommandVersioned}; +use build_helper::rerun_if_changed; +use cargo_metadata::{CargoOpt, Metadata, MetadataCommand}; use std::{ borrow::ToOwned, collections::HashSet, @@ -26,13 +28,8 @@ use std::{ path::{Path, PathBuf}, process, }; - +use strum::{EnumIter, IntoEnumIterator}; use toml::value::Table; - -use build_helper::rerun_if_changed; - -use cargo_metadata::{Metadata, MetadataCommand}; - use walkdir::WalkDir; /// Colorize an info message. @@ -77,8 +74,18 @@ fn crate_metadata(cargo_manifest: &Path) -> Metadata { let cargo_lock_existed = cargo_lock.exists(); + // If we can find a `Cargo.lock`, we assume that this is the workspace root and there exists a + // `Cargo.toml` that we can use for getting the metadata. + let cargo_manifest = if let Some(mut cargo_lock) = find_cargo_lock(cargo_manifest) { + cargo_lock.set_file_name("Cargo.toml"); + cargo_lock + } else { + cargo_manifest.to_path_buf() + }; + let crate_metadata = MetadataCommand::new() .manifest_path(cargo_manifest) + .features(CargoOpt::AllFeatures) .exec() .expect("`cargo metadata` can not fail on project `Cargo.toml`; qed"); @@ -118,9 +125,9 @@ pub(crate) fn create_and_compile( features_to_enable, ); - build_project(&project, default_rustflags, cargo_cmd); + let profile = build_project(&project, default_rustflags, cargo_cmd); let (wasm_binary, wasm_binary_compressed, bloaty) = - compact_wasm_file(&project, project_cargo_toml, wasm_binary_name); + compact_wasm_file(&project, profile, project_cargo_toml, wasm_binary_name); wasm_binary .as_ref() @@ -151,18 +158,29 @@ fn find_cargo_lock(cargo_manifest: &Path) -> Option { } } - if let Some(path) = find_impl(build_helper::out_dir()) { - return Some(path) + if let Ok(workspace) = env::var(crate::WASM_BUILD_WORKSPACE_HINT) { + let path = PathBuf::from(workspace); + + if path.join("Cargo.lock").exists() { + return Some(path.join("Cargo.lock")) + } else { + build_helper::warning!( + "`{}` env variable doesn't point to a directory that contains a `Cargo.lock`.", + crate::WASM_BUILD_WORKSPACE_HINT, + ); + } } - if let Some(path) = find_impl(cargo_manifest.to_path_buf()) { + if let Some(path) = find_impl(build_helper::out_dir()) { return Some(path) } build_helper::warning!( - "Could not find `Cargo.lock` for `{}`, while searching from `{}`.", + "Could not find `Cargo.lock` for `{}`, while searching from `{}`. \ + To fix this, point the `{}` env variable to the directory of the workspace being compiled.", cargo_manifest.display(), - build_helper::out_dir().display() + build_helper::out_dir().display(), + crate::WASM_BUILD_WORKSPACE_HINT, ); None @@ -225,16 +243,22 @@ fn create_project_cargo_toml( let mut wasm_workspace_toml = Table::new(); - // Add `profile` with release and dev + // Add different profiles which are selected by setting `WASM_BUILD_TYPE`. let mut release_profile = Table::new(); release_profile.insert("panic".into(), "abort".into()); - release_profile.insert("lto".into(), true.into()); + release_profile.insert("lto".into(), "thin".into()); + + let mut production_profile = Table::new(); + production_profile.insert("inherits".into(), "release".into()); + production_profile.insert("lto".into(), "fat".into()); + production_profile.insert("codegen-units".into(), 1.into()); let mut dev_profile = Table::new(); dev_profile.insert("panic".into(), "abort".into()); let mut profile = Table::new(); profile.insert("release".into(), release_profile.into()); + profile.insert("production".into(), production_profile.into()); profile.insert("dev".into(), dev_profile.into()); wasm_workspace_toml.insert("profile".into(), profile.into()); @@ -399,25 +423,119 @@ fn create_project( wasm_project_folder } -/// Returns if the project should be built as a release. -fn is_release_build() -> bool { - if let Ok(var) = env::var(crate::WASM_BUILD_TYPE_ENV) { - match var.as_str() { - "release" => true, - "debug" => false, - var => panic!( - "Unexpected value for `{}` env variable: {}\nOne of the following are expected: `debug` or `release`.", - crate::WASM_BUILD_TYPE_ENV, - var, - ), +/// The cargo profile that is used to build the wasm project. +#[derive(Debug, EnumIter)] +enum Profile { + /// The `--profile dev` profile. + Debug, + /// The `--profile release` profile. + Release, + /// The `--profile production` profile. + Production, +} + +impl Profile { + /// Create a profile by detecting which profile is used for the main build. + /// + /// We cannot easily determine the profile that is used by the main cargo invocation + /// because the `PROFILE` environment variable won't contain any custom profiles like + /// "production". It would only contain the builtin profile where the custom profile + /// inherits from. This is why we inspect the build path to learn which profile is used. + /// + /// # Note + /// + /// Can be overriden by setting [`crate::WASM_BUILD_TYPE_ENV`]. + fn detect(wasm_project: &Path) -> Profile { + let (name, overriden) = if let Ok(name) = env::var(crate::WASM_BUILD_TYPE_ENV) { + (name, true) + } else { + // First go backwards to the beginning of the target directory. + // Then go forwards to find the "wbuild" directory. + // We need to go backwards first because when starting from the root there + // might be a chance that someone has a "wbuild" directory somewhere in the path. + let name = wasm_project + .components() + .rev() + .take_while(|c| c.as_os_str() != "target") + .collect::>() + .iter() + .rev() + .take_while(|c| c.as_os_str() != "wbuild") + .last() + .expect("We put the wasm project within a `target/.../wbuild` path; qed") + .as_os_str() + .to_str() + .expect("All our profile directory names are ascii; qed") + .to_string(); + (name, false) + }; + match (Profile::iter().find(|p| p.directory() == name), overriden) { + // When not overriden by a env variable we default to using the `Release` profile + // for the wasm build even when the main build uses the debug build. This + // is because the `Debug` profile is too slow for normal development activities. + (Some(Profile::Debug), false) => Profile::Release, + // For any other profile or when overriden we take it at face value. + (Some(profile), _) => profile, + // For non overriden unknown profiles we fall back to `Release`. + // This allows us to continue building when a custom profile is used for the + // main builds cargo. When explicitly passing a profile via env variable we are + // not doing a fallback. + (None, false) => { + let profile = Profile::Release; + build_helper::warning!( + "Unknown cargo profile `{}`. Defaulted to `{:?}` for the runtime build.", + name, + profile, + ); + profile + }, + // Invalid profile specified. + (None, true) => { + // We use println! + exit instead of a panic in order to have a cleaner output. + println!( + "Unexpected profile name: `{}`. One of the following is expected: {:?}", + name, + Profile::iter().map(|p| p.directory()).collect::>(), + ); + process::exit(1); + }, + } + } + + /// The name of the profile as supplied to the cargo `--profile` cli option. + fn name(&self) -> &'static str { + match self { + Self::Debug => "dev", + Self::Release => "release", + Self::Production => "production", + } + } + + /// The sub directory within `target` where cargo places the build output. + /// + /// # Note + /// + /// Usually this is the same as [`Self::name`] with the exception of the debug + /// profile which is called `dev`. + fn directory(&self) -> &'static str { + match self { + Self::Debug => "debug", + _ => self.name(), } - } else { - true + } + + /// Whether the resulting binary should be compacted and compressed. + fn wants_compact(&self) -> bool { + !matches!(self, Self::Debug) } } /// Build the project to create the WASM binary. -fn build_project(project: &Path, default_rustflags: &str, cargo_cmd: CargoCommandVersioned) { +fn build_project( + project: &Path, + default_rustflags: &str, + cargo_cmd: CargoCommandVersioned, +) -> Profile { let manifest_path = project.join("Cargo.toml"); let mut build_cmd = cargo_cmd.command(); @@ -446,16 +564,16 @@ fn build_project(project: &Path, default_rustflags: &str, cargo_cmd: CargoComman build_cmd.arg("--color=always"); } - if is_release_build() { - build_cmd.arg("--release"); - }; + let profile = Profile::detect(project); + build_cmd.arg("--profile"); + build_cmd.arg(profile.name()); println!("{}", colorize_info_message("Information that should be included in a bug report.")); println!("{} {:?}", colorize_info_message("Executing build command:"), build_cmd); println!("{} {}", colorize_info_message("Using rustc version:"), cargo_cmd.rustc_version()); match build_cmd.status().map(|s| s.success()) { - Ok(true) => {}, + Ok(true) => profile, // Use `process.exit(1)` to have a clean error output. _ => process::exit(1), } @@ -464,18 +582,17 @@ fn build_project(project: &Path, default_rustflags: &str, cargo_cmd: CargoComman /// Compact the WASM binary using `wasm-gc` and compress it using zstd. fn compact_wasm_file( project: &Path, + profile: Profile, cargo_manifest: &Path, wasm_binary_name: Option, ) -> (Option, Option, WasmBinaryBloaty) { - let is_release_build = is_release_build(); - let target = if is_release_build { "release" } else { "debug" }; let default_wasm_binary_name = get_wasm_binary_name(cargo_manifest); let wasm_file = project .join("target/wasm32-unknown-unknown") - .join(target) + .join(profile.directory()) .join(format!("{}.wasm", default_wasm_binary_name)); - let wasm_compact_file = if is_release_build { + let wasm_compact_file = if profile.wants_compact() { let wasm_compact_file = project.join(format!( "{}.compact.wasm", wasm_binary_name.clone().unwrap_or_else(|| default_wasm_binary_name.clone()), @@ -523,8 +640,8 @@ fn compress_wasm(wasm_binary_path: &Path, compressed_binary_out_path: &Path) -> true } else { - println!( - "cargo:warning=Writing uncompressed wasm. Exceeded maximum size {}", + build_helper::warning!( + "Writing uncompressed wasm. Exceeded maximum size {}", CODE_BLOB_BOMB_LIMIT, ); @@ -666,11 +783,13 @@ fn copy_wasm_to_target_directory(cargo_manifest: &Path, wasm_binary: &WasmBinary }; if !target_dir.is_absolute() { - panic!( + // We use println! + exit instead of a panic in order to have a cleaner output. + println!( "Environment variable `{}` with `{}` is not an absolute path!", crate::WASM_TARGET_DIRECTORY, target_dir.display(), ); + process::exit(1); } fs::create_dir_all(&target_dir).expect("Creates `WASM_TARGET_DIRECTORY`.");