### Rust Configuration Check Example Source: https://github.com/paritytech/substrate/blob/master/bin/node-template/docs/rust-setup.md Demonstrates how to check the currently active Rust toolchain and installed targets using `rustup show`. Includes an example output. ```bash rustup show ``` ```text Default host: x86_64-unknown-linux-gnu rustup home: /home/user/.rustup inscribed toolchains --------------------- stable-x86_64-unknown-linux-gnu (default) nightly-2020-10-06-x86_64-unknown-linux-gnu nightly-x86_64-unknown-linux-gnu inscribed 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) ``` -------------------------------- ### Install Substrate (Mac/Ubuntu) Source: https://github.com/paritytech/substrate/blob/master/docs/README.adoc Installs Substrate and its dependencies using a curl script. This is the quickest way to get started on Unix-based systems. ```shell curl https://getsubstrate.io -sSf | bash ``` -------------------------------- ### Install Build Dependencies on OpenSUSE Source: https://github.com/paritytech/substrate/blob/master/bin/node-template/docs/rust-setup.md Installs essential packages including clang, curl, git, openssl-devel, llvm-devel, and libudev-devel for Substrate development on OpenSUSE. ```bash sudo zypper install clang curl git openssl-devel llvm-devel libudev-devel ``` -------------------------------- ### Install and Configure Rust Toolchain Source: https://github.com/paritytech/substrate/blob/master/bin/node-template/docs/rust-setup.md Installs Rust using rustup, configures the default toolchain to stable, updates toolchains, and adds the wasm32-unknown-unknown target for nightly Rust. ```bash # Install curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Configure source ~/.cargo/env rustup default stable rustup update rustup update nightly rustup target add wasm32-unknown-unknown --toolchain nightly ``` -------------------------------- ### Install Build Dependencies on Ubuntu/Debian Source: https://github.com/paritytech/substrate/blob/master/bin/node-template/docs/rust-setup.md Installs essential build tools like git, clang, curl, openssl, llvm, and libudev for Substrate development on Ubuntu/Debian systems. ```bash sudo apt update # May prompt for location information sudo apt install -y git clang curl libssl-dev llvm libudev-dev ``` -------------------------------- ### Install Specific Rust Nightly Toolchain Source: https://github.com/paritytech/substrate/blob/master/bin/node-template/docs/rust-setup.md Installs a specific version of the Rust nightly toolchain, identified by a date, for consistent builds. ```bash rustup install nightly- ``` -------------------------------- ### Build Substrate Runtime with Specific Nightly Source: https://github.com/paritytech/substrate/blob/master/bin/node-template/docs/rust-setup.md Builds the Substrate project's runtime using a specified Rust nightly toolchain via an environment variable. ```bash WASM_BUILD_TOOLCHAIN=nightly- cargo build --release ``` -------------------------------- ### Install Build Dependencies on Arch Linux Source: https://github.com/paritytech/substrate/blob/master/bin/node-template/docs/rust-setup.md Installs necessary packages including curl, git, and clang for Substrate development on Arch Linux. ```bash pacman -Syu --needed --noconfirm curl git clang ``` -------------------------------- ### Install Build Dependencies on Fedora Source: https://github.com/paritytech/substrate/blob/master/bin/node-template/docs/rust-setup.md Installs required packages such as clang, curl, git, and openssl-devel for Substrate development on Fedora. ```bash sudo dnf update sudo dnf install clang curl git openssl-devel ``` -------------------------------- ### OpenSSL Installation using vcpkg Source: https://github.com/paritytech/substrate/blob/master/docs/README.adoc Steps to clone vcpkg, bootstrap it, and install OpenSSL for Windows static linking. ```shell mkdir \Tools cd \Tools git clone https://github.com/Microsoft/vcpkg.git cd vcpkg .\bootstrap-vcpkg.bat .\vcpkg.exe install openssl:x64-windows-static ``` -------------------------------- ### Example Grafana Dashboard Setup Source: https://github.com/paritytech/substrate/blob/master/scripts/ci/monitoring/grafana-dashboards/README_dashboard.md This snippet shows an example of a Grafana dashboard configuration file for Substrate networking, typically in JSON format. ```json { "__inputs": [ { "name": "DS_PROMETHEUS", "label": "Prometheus", "type": "datasource", "pluginId": "prometheus", "pluginLabel": "Prometheus" } ], "__requires": [ { "type": "grafana", "id": "grafana", "name": "Grafana", "version": "8.0.0" }, { "type": "datasource", "id": "prometheus", "name": "Prometheus", "version": "1.0.0" } ], "annotations": { "list": [ { "builtIn": 1, "datasource": { "type": "grafana", "uid": "__annotation" }, "enable": true, "hide": true, "iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts", "type": "dashboard" } ] }, "editable": true, "gnetId": null, "graphTooltip": 0, "id": null, "links": [], "panels": [ { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "gridPos": { "h": 8, "w": 12, "x": 0, "y": 0 }, "id": 2, "interval": "", "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true }, "options": { "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true }, "tooltip": { "mode": "single", "sort": "none" } }, "targets": [ { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "editorMode": "builder", "expr": "up{job='substrate'}", "legendFormat": "{{ instance }} - {{ job }}", "range": true, "refId": "A" } ], "title": "Substrate Node Status", "type": "timeseries" } ], "schemaVersion": 37, "style": "dark", "tags": [], "templating": { "list": [ { "current": { "selected": false, "text": "Prometheus", "value": "Prometheus" }, "hide": 0, "includeAll": false, "label": "Datasource", "multi": false, "name": "DS_PROMETHEUS", "options": [], "query": "prometheus", "refresh": 1, "regex": "", "skipUrlSync": false, "type": "datasource" } ] }, "time": { "from": "now-1h", "to": "now" }, "timepicker": {}, "timezone": "", "title": "Substrate Networking Dashboard", "uid": "substrate-networking", "version": 1 } ``` -------------------------------- ### Substrate Pallet Documentation Header Example Source: https://github.com/paritytech/substrate/blob/master/docs/DOCUMENTATION_GUIDELINES.md Example of a documentation header for a Substrate pallet, demonstrating how to link to external projects like Substrate and Polkadot, and include badges. ```rust "//! > Made with *Substrate*, for *Polkadot*.\n//!\n//! [![github]](https://github.com/paritytech/substrate/frame/fast-unstake) -\n//! [![polkadot]](https://polkadot.network)\n//!\n//! [polkadot]: https://img.shields.io/badge/polkadot-E6007A?style=for-the-badge&logo=polkadot&logoColor=white\n//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github" ``` -------------------------------- ### Install Rust on Windows Source: https://github.com/paritytech/substrate/blob/master/docs/README.adoc Provides instructions for installing Rust on Windows, including prerequisites like Visual Studio Build Tools. ```shell # Download and run vs_buildtools.exe from https://aka.ms/buildtools # Ensure Windows 10 SDK is included. # Restart your computer. # Download and run rustup-init.exe from https://www.rust-lang.org/tools/install # Choose 'Default Installation'. ``` -------------------------------- ### Starting Alice's Development Node Source: https://github.com/paritytech/substrate/blob/master/docs/README.adoc Starts the first validator node for Alice, configuring its base path, chain, node key, and telemetry. ```shell cargo run --release \ --base-path /tmp/alice \ --chain=local \ --alice \ --node-key 0000000000000000000000000000000000000000000000000000000000000001 \ --telemetry-url 'ws://telemetry.polkadot.io:1024 0' \ --validator ``` -------------------------------- ### Default Config Example Pallet Documentation Source: https://github.com/paritytech/substrate/blob/master/frame/examples/default-config/README.md Provides instructions on how to view the generated documentation for the Default Config Example Pallet. ```bash cargo doc --package pallet-default-config-example --open ``` -------------------------------- ### Starting Bob's Development Node Source: https://github.com/paritytech/substrate/blob/master/docs/README.adoc Starts the second validator node for Bob, connecting to Alice's node and configuring its port and base path. ```shell cargo run --release \ --base-path /tmp/bob \ --bootnodes /ip4/127.0.0.1/tcp/30333/p2p/QmRpheLN4JWdAnY7HGJfWFNbfkQCb6tFf4vvA6hgjMZKrR \ --chain=local \ --bob \ --port 30334 \ --telemetry-url 'ws://telemetry.polkadot.io:1024 0' \ --validator ``` -------------------------------- ### Subkey Generate Command Output Example Source: https://github.com/paritytech/substrate/blob/master/bin/utils/subkey/README.md Example of the detailed text output when generating a new account with the `subkey generate` command. ```text Secret phrase `hotel forest jar hover kite book view eight stuff angle legend defense` is account: Secret seed: 0xa05c75731970cc7868a2fb7cb577353cd5b31f62dccced92c441acd8fee0c92d Public key (hex): 0xfec70cfbf1977c6965b5af10a4534a6a35d548eb14580594d0bc543286892515 Account ID: 0xfec70cfbf1977c6965b5af10a4534a6a35d548eb14580594d0bc543286892515 SS58 Address: 5Hpm9fq3W3dQgwWpAwDS2ZHKAdnk86QRCu7iX4GnmDxycrte ``` -------------------------------- ### Install Rust and Substrate Dependencies (Linux/Mac) Source: https://github.com/paritytech/substrate/blob/master/docs/README.adoc Installs Rust, updates the nightly toolchain, adds the Wasm target, and installs necessary system packages for building Substrate on Linux and macOS. ```shell curl https://sh.rustup.rs -sSf | sh rustup update nightly rustup target add wasm32-unknown-unknown --toolchain nightly rustup update stable ``` ```shell # Linux: sudo apt install cmake pkg-config libssl-dev git clang libclang-dev llvm # Mac: brew install cmake pkg-config openssl git llvm ``` -------------------------------- ### Generated Weight File Example Source: https://github.com/paritytech/substrate/blob/master/utils/frame/benchmarking-cli/src/storage/README.md An example of the generated Rust code in a weight file, showing calculated storage read and write times based on benchmark statistics. ```rust /// Time to read one storage item. /// Calculated by multiplying the *Average* of all values with `1.1` and adding `0`. /// /// Stats [NS]: /// Min, Max: 4_611, 1_217_259 /// Average: 14_262 /// Median: 14_190 /// Std-Dev: 3035.79 /// /// Percentiles [NS]: /// 99th: 18_270 /// 95th: 16_190 /// 75th: 14_819 read: 14_262 * constants::WEIGHT_REF_TIME_PER_NANOS, /// Time to write one storage item. /// Calculated by multiplying the *Average* of all values with `1.1` and adding `0`. /// /// Stats [NS]: /// Min, Max: 12_969, 13_282_577 /// Average: 71_347This works under the assumption that the *average* read a /// Median: 69_499 /// Std-Dev: 25145.27 /// /// Percentiles [NS]: /// 99th: 135_839 /// 95th: 106_129 /// 75th: 79_239 write: 71_347 * constants::WEIGHT_REF_TIME_PER_NANOS, ``` -------------------------------- ### Starting a Development Chain Source: https://github.com/paritytech/substrate/blob/master/docs/README.adoc Launches a local Substrate development chain with detailed logging enabled. ```shell cargo run --release -- --dev # With detailed logs: RUST_LOG=debug RUST_BACKTRACE=1 cargo run --release \-- --dev ``` -------------------------------- ### Substrate Benchmark CLI Help Menu Source: https://github.com/paritytech/substrate/blob/master/utils/frame/benchmarking-cli/README.md Displays the main help menu for the Substrate benchmarking CLI, outlining available sub-commands and options. ```sh $ cargo run --profile=production -- benchmark Sub-commands concerned with benchmarking. USAGE: substrate benchmark OPTIONS: -h, --help Print help information -V, --version Print version information SUBCOMMANDS: block Benchmark the execution time of historic blocks machine Command to benchmark the hardware. overhead Benchmark the execution overhead per-block and per-extrinsic pallet Benchmark the extrinsic weight of FRAME Pallets storage Benchmark the storage speed of a chain snapshot ``` -------------------------------- ### Install Homebrew and OpenSSL on macOS Source: https://github.com/paritytech/substrate/blob/master/bin/node-template/docs/rust-setup.md Installs Homebrew package manager and OpenSSL, a dependency for Substrate development on macOS. Includes a note for Apple M1 ARM systems regarding Rosetta 2. ```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 ``` -------------------------------- ### Downgrade Rust Nightly and Set Wasm Target Source: https://github.com/paritytech/substrate/blob/master/bin/node-template/docs/rust-setup.md Uninstalls the current nightly toolchain, installs a specific version, and configures the Wasm target for it. ```bash rustup uninstall nightly rustup install nightly- rustup target add wasm32-unknown-unknown --toolchain nightly- ``` -------------------------------- ### Start Local Substrate Development Chain Source: https://github.com/paritytech/substrate/blob/master/docs/README.adoc Launches a local Substrate development chain with default settings. ```shell substrate --dev ``` -------------------------------- ### Get Current Timestamp in Custom Module Source: https://github.com/paritytech/substrate/blob/master/frame/timestamp/README.md Example of how to use the Timestamp module within a custom module to retrieve the current on-chain time. It demonstrates importing the module, configuring the pallet, and calling the `get` function. ```rust use pallet_timestamp::{self as timestamp}; #[frame_support::pallet] pub mod pallet { use super::*; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); #[pallet::config] pub trait Config: frame_system::Config + timestamp::Config {} #[pallet::call] impl Pallet { #[pallet::weight(0)] pub fn get_time(origin: OriginFor) -> DispatchResult { let _sender = ensure_signed(origin)?; let _now = >::get(); Ok(()) } } } ``` -------------------------------- ### System Module Example: Get Extrinsic Count and Parent Hash Source: https://github.com/paritytech/substrate/blob/master/frame/system/README.md Demonstrates how to retrieve the extrinsic count and parent hash for the current block using the System module's public functions. This example requires the System module to be configured and imported. ```rust #[frame_support::pallet] pub mod pallet { use super::*; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::config] pub trait Config: frame_system::Config {} #[pallet::pallet] pub struct Pallet(_); #[pallet::call] impl Pallet { #[pallet::weight(0)] pub fn system_module_example(origin: OriginFor) -> DispatchResult { let _sender = ensure_signed(origin)?; let _extrinsic_count = >::extrinsic_count(); let _parent_hash = >::parent_hash(); Ok(()) } } } ``` -------------------------------- ### Configure Wasm Target with Specific Nightly Source: https://github.com/paritytech/substrate/blob/master/bin/node-template/docs/rust-setup.md Adds the Wasm compilation target for a specific Rust nightly toolchain version. ```bash rustup target add wasm32-unknown-unknown --toolchain nightly- ``` -------------------------------- ### Nix Environment Setup for Substrate Source: https://github.com/paritytech/substrate/blob/master/bin/node-template/README.md Provides instructions for setting up the Substrate development environment using Nix and nix-direnv. This ensures all necessary dependencies are correctly managed for a seamless development experience. ```bash # Install nix and nix-direnv if not already installed. # Navigate to the project directory. direnv allow ``` -------------------------------- ### Update Rust and Add Wasm Target Source: https://github.com/paritytech/substrate/blob/master/bin/node-template/docs/rust-setup.md Ensures your Rust compiler is up-to-date with the latest stable and nightly versions and adds the Wasm compilation target. ```bash rustup update rustup update nightly rustup target add wasm32-unknown-unknown --toolchain nightly ``` -------------------------------- ### Run a Substrate Node in Docker Source: https://github.com/paritytech/substrate/blob/master/scripts/ci/docker/substrate.Dockerfile.README.md Example command to run a Substrate node using the built Docker image. This starts a development node. ```bash docker run -p 9933:9933 -p 9944:9944 substrate-node:latest --dev ``` -------------------------------- ### Running Pallet Balance Benchmarks Source: https://github.com/paritytech/substrate/blob/master/frame/benchmarking/README.md Provides a command-line example for testing the benchmarks of the Balances pallet using Cargo. It highlights the need for the `runtime-benchmarks` feature flag and navigating to the correct directory. ```bash cargo test -p pallet-balances --features runtime-benchmarks ``` -------------------------------- ### Get Random Seed Example (Rust) Source: https://github.com/paritytech/substrate/blob/master/frame/insecure-randomness-collective-flip/README.md Demonstrates how to obtain a random seed for the current block using the Randomness Collective Flip pallet. This function relies on the `Randomness` trait and the `pallet_insecure_randomness_collective_flip` pallet. ```rust use frame_support::traits::Randomness; #[frame_support::pallet] pub mod pallet { use super::*; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); #[pallet::config] pub trait Config: frame_system::Config + pallet_insecure_randomness_collective_flip::Config {} #[pallet::call] impl Pallet { #[pallet::weight(0)] pub fn random_module_example(origin: OriginFor) -> DispatchResult { let _random_value = >::random(&b"my context"[..]); Ok(()) } } } ``` -------------------------------- ### Substrate Benchmark Help Command Source: https://github.com/paritytech/substrate/blob/master/frame/benchmarking/README.md Command to display all available options and flags for the Substrate benchmarking CLI, providing a comprehensive overview of its capabilities. ```bash ./target/production/substrate benchmark --help ``` -------------------------------- ### Rust Function Documentation Example Source: https://github.com/paritytech/substrate/blob/master/docs/DOCUMENTATION_GUIDELINES.md Demonstrates effective Rust documentation practices, including explaining functionality, panics, complexity, and adhering to line-width conventions. This format is preferred for clarity and maintainability. ```rust /// Multiplies an input of type [`u32`] by two. /// /// # Panics /// /// Panics if the input overflows. /// /// # Complexity /// /// Is implemented using some algorithm that yields complexity of O(1). // More efficiency can be achieved if we improve this via such and such. fn multiply_by_2(x: u32) -> u32 { .. } ``` -------------------------------- ### Start Substrate Node Source: https://github.com/paritytech/substrate/blob/master/utils/prometheus/README.md Starts the Substrate node in release mode. This is the first step to enable the Prometheus exporter. ```bash cargo run --release ``` -------------------------------- ### Substrate Custom Pallet Documentation Template Source: https://github.com/paritytech/substrate/blob/master/frame/examples/basic/README.md This snippet provides a Markdown template for documenting a custom Substrate pallet. It includes sections for the pallet's name, description, links to relevant Rustdocs (Config, Call, Module), overview, terminology, goals, scenarios, interface details (supported origins, types, dispatchable functions, public functions), and specific getter/setter function documentation. ```markdown // Add heading with custom pallet name # Pallet // Add simple description // Include the following links that shows what trait needs to be implemented to use the pallet // and the supported dispatchables that are documented in the Call enum. - [`::Config`](https://docs.rs/pallet-example-basic/latest/pallet_example_basic/trait.Config.html) - [`Call`](https://docs.rs/pallet-example-basic/latest/pallet_example_basic/enum.Call.html) - [`Module`](https://docs.rs/pallet-example-basic/latest/pallet_example_basic/struct.Module.html) ## Overview // Short description of pallet's purpose. // Links to Traits that should be implemented. // What this pallet is for. // What functionality the pallet provides. // When to use the pallet (use case examples). // How it is used. // Inputs it uses and the source of each input. // Outputs it produces. ## Terminology // Add terminology used in the custom pallet. Include concepts, storage items, or actions that you think // deserve to be noted to give context to the rest of the documentation or pallet usage. The author needs to // use some judgment about what is included. We don't want a list of every storage item nor types - the user // can go to the code for that. For example, "transfer fee" is obvious and should not be included, but // "free balance" and "reserved balance" should be noted to give context to the pallet. // Please do not link to outside resources. The reference docs should be the ultimate source of truth. ## Goals // Add goals that the custom pallet is designed to achieve. ### Scenarios #### // Describe requirements prior to interacting with the custom pallet. // Describe the process of interacting with the custom pallet for this scenario and public API functions used. ## Interface ### Supported Origins // What origins are used and supported in this pallet (root, signed, none) // i.e. root when `ensure_root` used // i.e. none when `ensure_none` used // i.e. signed when `ensure_signed` used `inherent` ### Types // Type aliases. Include any associated types and where the user would typically define them. `ExampleType` // Reference documentation of aspects such as `storageItems` and `dispatchable` functions should only be // included in the https://docs.rs Rustdocs for Substrate and not repeated in the README file. ### Dispatchable Functions // A brief description of dispatchable functions and a link to the rustdoc with their actual documentation. // MUST have link to Call enum // MUST have origin information included in function doc // CAN have more info up to the user ### Public Functions // A link to the rustdoc and any notes about usage in the pallet, not for specific functions. // For example, in the Balances Pallet: "Note that when using the publicly exposed functions, // you (the runtime developer) are responsible for implementing any necessary checks // (e.g. that the sender is the signer) before calling a function that will affect storage." // It is up to the writer of the respective pallet (with respect to how much information to provide). #### Public Inspection functions - Immutable (getters) // Insert a subheading for each getter function signature ##### `example_getter_name()` // What it returns // Why, when, and how often to call it // When it could panic or error // When safety issues to consider #### Public Mutable functions (changing state) // Insert a subheading for each setter function signature ``` -------------------------------- ### Bash Shell Completion Installation Source: https://github.com/paritytech/substrate/blob/master/bin/node/cli/doc/shell-completion.adoc Installs the Substrate CLI bash completion script and configures the system to load it automatically. ```shell source target/release/completion-scripts/substrate.bash ``` ```shell COMPL_DIR=$HOME/.completion mkdir -p $COMPL_DIR cp -f target/release/completion-scripts/substrate.bash $COMPL_DIR/ echo "source $COMPL_DIR/substrate.bash" >> $HOME/.bash_profile source $HOME/.bash_profile ```