├── .chopsticks ├── README.md ├── devnet.yml ├── paseo.yml └── testnet.yml ├── .dockerignore ├── .githooks ├── README.md └── pre-push ├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ └── release_tracking.md ├── actions │ └── init │ │ └── action.yml └── workflows │ ├── ci.yml │ ├── lint-pr.yml │ └── release.yml ├── .gitignore ├── .rustfmt.toml ├── .taplo.toml ├── Cargo.lock ├── Cargo.toml ├── Dockerfile ├── LICENSE ├── README.md ├── codecov.yml ├── docs └── release.md ├── extension ├── Cargo.toml ├── contract │ ├── Cargo.lock │ ├── Cargo.toml │ └── lib.rs └── src │ ├── decoding.rs │ ├── environment.rs │ ├── functions.rs │ ├── lib.rs │ ├── matching.rs │ ├── mock.rs │ └── tests.rs ├── integration-tests ├── Cargo.toml ├── README.md └── src │ ├── chains │ ├── asset_hub │ │ ├── genesis.rs │ │ └── mod.rs │ ├── mod.rs │ ├── pop_network │ │ ├── genesis.rs │ │ └── mod.rs │ └── relay │ │ ├── genesis.rs │ │ └── mod.rs │ └── lib.rs ├── networks ├── README.md ├── devnet.toml ├── mainnet.toml └── testnet.toml ├── node ├── Cargo.toml ├── build.rs ├── chain_specs │ ├── mainnet │ │ ├── pop-genesis-hash │ │ ├── pop-genesis-state │ │ ├── pop-polkadot.plain.json │ │ ├── pop-polkadot.raw.json │ │ └── pop-wasm │ └── testnet │ │ ├── paseo.raw.json │ │ ├── pop-paseo.plain.json │ │ └── pop-paseo.raw.json └── src │ ├── chain_spec.rs │ ├── cli.rs │ ├── command.rs │ ├── main.rs │ ├── rpc.rs │ └── service.rs ├── pallets ├── api │ ├── Cargo.toml │ └── src │ │ ├── extension.rs │ │ ├── fungibles │ │ ├── benchmarking.rs │ │ ├── mod.rs │ │ ├── tests.rs │ │ └── weights.rs │ │ ├── lib.rs │ │ ├── messaging │ │ ├── mod.rs │ │ └── transports │ │ │ ├── ismp.rs │ │ │ ├── mod.rs │ │ │ └── xcm.rs │ │ ├── mock.rs │ │ └── nonfungibles │ │ ├── benchmarking.rs │ │ ├── mod.rs │ │ ├── tests.rs │ │ └── weights.rs ├── motion │ ├── Cargo.toml │ ├── README.md │ └── src │ │ ├── benchmarking.rs │ │ ├── lib.rs │ │ ├── mock.rs │ │ ├── tests.rs │ │ └── weights.rs └── nfts │ ├── Cargo.toml │ ├── README.md │ ├── runtime-api │ ├── Cargo.toml │ ├── README.md │ └── src │ │ └── lib.rs │ └── src │ ├── benchmarking.rs │ ├── common_functions.rs │ ├── features │ ├── approvals.rs │ ├── atomic_swap.rs │ ├── attributes.rs │ ├── buy_sell.rs │ ├── create_delete_collection.rs │ ├── create_delete_item.rs │ ├── lock.rs │ ├── metadata.rs │ ├── mod.rs │ ├── roles.rs │ ├── settings.rs │ └── transfer.rs │ ├── impl_nonfungibles.rs │ ├── lib.rs │ ├── macros.rs │ ├── migration.rs │ ├── mock.rs │ ├── tests.rs │ ├── types.rs │ └── weights.rs ├── pop-api ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── README.md ├── examples │ ├── .gitignore │ ├── README.md │ ├── fungibles │ │ ├── Cargo.toml │ │ ├── README.md │ │ ├── lib.rs │ │ └── tests.rs │ ├── messaging │ │ ├── Cargo.toml │ │ └── lib.rs │ └── nonfungibles │ │ ├── Cargo.toml │ │ ├── README.md │ │ └── lib.rs ├── integration-tests │ ├── Cargo.lock │ ├── Cargo.toml │ ├── build.rs │ ├── contracts │ │ ├── create_token_in_constructor │ │ │ ├── Cargo.lock │ │ │ ├── Cargo.toml │ │ │ └── lib.rs │ │ ├── fungibles │ │ │ ├── Cargo.lock │ │ │ ├── Cargo.toml │ │ │ └── lib.rs │ │ ├── messaging │ │ │ ├── Cargo.lock │ │ │ ├── Cargo.toml │ │ │ └── lib.rs │ │ └── nonfungibles │ │ │ ├── Cargo.lock │ │ │ ├── Cargo.toml │ │ │ └── lib.rs │ └── src │ │ ├── fungibles │ │ ├── mod.rs │ │ └── utils.rs │ │ ├── lib.rs │ │ ├── messaging.rs │ │ ├── nonfungibles │ │ ├── mod.rs │ │ └── utils.rs │ │ └── utils.rs └── src │ ├── lib.rs │ ├── macros.rs │ ├── primitives.rs │ └── v0 │ ├── fungibles │ ├── README.md │ ├── errors.rs │ ├── events.rs │ ├── mod.rs │ └── traits.rs │ ├── messaging │ ├── ismp.rs │ ├── mod.rs │ └── xcm.rs │ ├── mod.rs │ └── nonfungibles │ ├── README.md │ ├── errors.rs │ ├── events.rs │ ├── mod.rs │ ├── traits.rs │ └── types.rs ├── primitives ├── Cargo.toml ├── README.md └── src │ └── lib.rs ├── runtime ├── common │ ├── Cargo.toml │ └── src │ │ ├── genesis.rs │ │ ├── lib.rs │ │ └── weights │ │ ├── block_weights.rs │ │ ├── cumulus_pallet_parachain_system.rs │ │ ├── cumulus_pallet_weight_reclaim.rs │ │ ├── cumulus_pallet_xcmp_queue.rs │ │ ├── extrinsic_weights.rs │ │ ├── frame_system.rs │ │ ├── frame_system_extensions.rs │ │ ├── mod.rs │ │ ├── pallet_assets.rs │ │ ├── pallet_balances.rs │ │ ├── pallet_collator_selection.rs │ │ ├── pallet_collective.rs │ │ ├── pallet_message_queue.rs │ │ ├── pallet_migrations.rs │ │ ├── pallet_motion.rs │ │ ├── pallet_multisig.rs │ │ ├── pallet_nfts.rs │ │ ├── pallet_preimage.rs │ │ ├── pallet_proxy.rs │ │ ├── pallet_revive.rs │ │ ├── pallet_scheduler.rs │ │ ├── pallet_session.rs │ │ ├── pallet_sudo.rs │ │ ├── pallet_timestamp.rs │ │ ├── pallet_transaction_payment.rs │ │ ├── pallet_treasury.rs │ │ ├── pallet_utility.rs │ │ ├── pallet_xcm.rs │ │ ├── paritydb_weights.rs │ │ ├── rocksdb_weights.rs │ │ └── xcm │ │ ├── mod.rs │ │ ├── pallet_xcm_benchmarks_fungible.rs │ │ └── pallet_xcm_benchmarks_generic.rs ├── devnet │ ├── Cargo.toml │ ├── build.rs │ └── src │ │ ├── config │ │ ├── api │ │ │ ├── mod.rs │ │ │ └── versioning.rs │ │ ├── assets.rs │ │ ├── contracts.rs │ │ ├── ismp.rs │ │ ├── mod.rs │ │ ├── proxy.rs │ │ └── xcm.rs │ │ ├── genesis.rs │ │ ├── lib.rs │ │ └── weights │ │ ├── block_weights.rs │ │ ├── extrinsic_weights.rs │ │ ├── mod.rs │ │ ├── paritydb_weights.rs │ │ └── rocksdb_weights.rs ├── mainnet │ ├── Cargo.toml │ ├── build.rs │ └── src │ │ ├── apis.rs │ │ ├── benchmarks.rs │ │ ├── config │ │ ├── assets.rs │ │ ├── collation.rs │ │ ├── governance.rs │ │ ├── mod.rs │ │ ├── monetary.rs │ │ ├── proxy.rs │ │ ├── revive.rs │ │ ├── system.rs │ │ ├── utility.rs │ │ ├── xcm.rs │ │ └── xcm_weights.rs │ │ ├── genesis.rs │ │ └── lib.rs └── testnet │ ├── Cargo.toml │ ├── build.rs │ └── src │ ├── config │ ├── api │ │ ├── mod.rs │ │ └── versioning.rs │ ├── assets.rs │ ├── collation.rs │ ├── contracts.rs │ ├── governance.rs │ ├── ismp.rs │ ├── mod.rs │ ├── monetary.rs │ ├── proxy.rs │ ├── system.rs │ ├── utility.rs │ └── xcm.rs │ ├── genesis.rs │ ├── lib.rs │ └── weights │ ├── block_weights.rs │ ├── extrinsic_weights.rs │ ├── mod.rs │ ├── paritydb_weights.rs │ └── rocksdb_weights.rs ├── rust-toolchain.toml ├── scripts ├── benchmarks-ci.sh ├── runtime-weight-template.hbs └── templates │ ├── pallet-weight-template.hbs │ ├── runtime-weight-template.hbs │ └── xcm-bench-template.hbs └── tests └── contracts └── filtered-call ├── .gitignore ├── Cargo.toml └── lib.rs /.chopsticks/README.md: -------------------------------------------------------------------------------- 1 | # Chopsticks 2 | 3 | A brief guide on testing a runtime upgrade with [Chopsticks](https://github.com/AcalaNetwork/chopsticks/). 4 | 5 | ## Runtime Upgrade 6 | 7 | 1. Launch local network with forks of Pop and Paseo state: 8 | ```shell 9 | npx @acala-network/chopsticks@latest xcm -r ./.chopsticks/paseo.yml -p ./.chopsticks/testnet.yml 10 | ``` 11 | 2. Authorise and apply the authorised runtime upgrade on the local Pop fork. 12 | 3. Build a block on the local relay chain to build a block (using [websocat](https://github.com/vi/websocat)). 13 | ```shell 14 | websocat ws://localhost:8001 15 | {"jsonrpc":"2.0","id":2,"method":"dev_newBlock","params":[{"count":1}]} 16 | ``` 17 | 4. Build blocks on Pop to complete the upgrade: 18 | ```shell 19 | websocat ws://localhost:8000 20 | {"jsonrpc":"2.0","id":2,"method":"dev_newBlock","params":[{"count":10}]} 21 | ``` 22 | 5. Verify that the runtime upgrade completed successfully. -------------------------------------------------------------------------------- /.chopsticks/devnet.yml: -------------------------------------------------------------------------------- 1 | endpoint: wss://rpc2.paseo.popnetwork.xyz 2 | mock-signature-host: true 3 | db: ./db.sqlite 4 | wasm-override: ../pop-node/target/release/wbuild/pop-runtime-devnet/pop_runtime_devnet.wasm 5 | 6 | import-storage: 7 | System: 8 | Account: 9 | - - - 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY 10 | - providers: 1 11 | data: 12 | free: 1000000000000000 13 | Sudo: 14 | Key: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY # Alice -------------------------------------------------------------------------------- /.chopsticks/paseo.yml: -------------------------------------------------------------------------------- 1 | endpoint: wss://rpc.ibp.network/paseo 2 | mock-signature-host: true 3 | db: ./db.sqlite 4 | 5 | import-storage: 6 | System: 7 | Account: 8 | - - - 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY 9 | - providers: 1 10 | data: 11 | free: 1000000000000000 12 | Sudo: 13 | Key: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY # Alice -------------------------------------------------------------------------------- /.chopsticks/testnet.yml: -------------------------------------------------------------------------------- 1 | endpoint: wss://rpc2.paseo.popnetwork.xyz 2 | mock-signature-host: true 3 | db: ./db.sqlite 4 | 5 | import-storage: 6 | System: 7 | Account: 8 | - - - 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY 9 | - providers: 1 10 | data: 11 | free: 1000000000000000 12 | Sudo: 13 | Key: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY # Alice -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | .git 2 | **/target/ 3 | **/*.txt 4 | **/*.md 5 | /docker/ 6 | 7 | # dotfiles in the repo root 8 | /.* 9 | -------------------------------------------------------------------------------- /.githooks/README.md: -------------------------------------------------------------------------------- 1 | # Git Hooks 2 | 3 | A pre-push hook which checks formatting of Rust files. Additional checks may be added in the future. 4 | 5 | # Prerequisites 6 | 7 | The following prerequisites are required: 8 | 9 | ## Rust Nightly 10 | 11 | The nightly version of Rust provides additional formatting benefits over the stable version. 12 | 13 | ```shell 14 | rustup toolchain install nightly --profile minimal --component rustfmt 15 | ``` 16 | 17 | ## Taplo 18 | 19 | Formatting of TOML documents is done via `taplo`. 20 | Find more about taplo [here](https://taplo.tamasfe.dev/). 21 | 22 | ``` 23 | cargo install taplo-cli --locked 24 | ``` 25 | 26 | ## Zepter 27 | 28 | Analyze, fix and format features in your Rust workspace. 29 | Find more about zepter [here](https://github.com/ggwpez/zepter). 30 | 31 | ``` 32 | cargo install zepter -f --locked 33 | ``` 34 | 35 | # Installation 36 | 37 | Use the following command in the root directory of the local repository to configure Git to use the hooks: 38 | 39 | ```shell 40 | git config core.hooksPath .githooks 41 | ``` 42 | -------------------------------------------------------------------------------- /.githooks/pre-push: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -eu 4 | 5 | # Are deps installed 6 | if ! command -v cargo > /dev/null 2>&1 7 | then 8 | echo "cargo couldn't be found, please confirm your set up is properly configured." 9 | exit 1 10 | else 11 | # Check Rust formatting 12 | if ! cargo +nightly fmt --all -- --check 13 | then 14 | echo "There are some code style issues." 15 | # shellcheck disable=SC2006 16 | echo "Run 'cargo +nightly fmt --all' first." 17 | exit 1 18 | fi 19 | fi 20 | 21 | if ! command -v taplo > /dev/null 2>&1 22 | then 23 | echo "taplo couldn't be found. Please, refer to .githooks/README.md." 24 | exit 1 25 | else 26 | # Check TOML formatting 27 | if ! taplo format --check 28 | then 29 | echo "There are some code style issues." 30 | echo "Run 'taplo fmt' first." 31 | exit 1 32 | fi 33 | fi 34 | 35 | if ! command -v zepter > /dev/null 2>&1 36 | then 37 | echo "zepter couldn't be found. Please, refer to .githooks/README.md." 38 | exit 1 39 | else 40 | # Check for feature formatting 41 | if ! zepter format features 42 | then 43 | echo "There are some code style issues." 44 | echo "Run 'zepter format features --fix' first." 45 | exit 1 46 | fi 47 | fi 48 | 49 | exit 0 50 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | @al3mart 2 | @Daanvdplas 3 | @evilrobot-01 4 | @peterwht -------------------------------------------------------------------------------- /.github/actions/init/action.yml: -------------------------------------------------------------------------------- 1 | name: Initialize 2 | description: This action initializes a runner for use in other actions. 3 | inputs: 4 | cache-key: 5 | description: "The key to be used for the cache" 6 | 7 | runs: 8 | using: "composite" 9 | steps: 10 | - name: Setup Ubuntu dependencies 11 | shell: bash 12 | run: sudo apt update && sudo apt install -y protobuf-compiler 13 | 14 | - name: Free up space on runner 15 | shell: bash 16 | run: | 17 | sudo rm -rf /opt/ghc 18 | sudo rm -rf /opt/hostedtoolcache/CodeQL 19 | sudo rm -rf /usr/local/.ghcup 20 | sudo rm -rf /usr/local/lib/android 21 | sudo rm -rf /usr/local/share/boost 22 | sudo rm -rf /usr/local/share/powershell 23 | sudo rm -rf /usr/share/dotnet 24 | sudo rm -rf /usr/share/swift 25 | sudo rm -rf "$AGENT_TOOLSDIRECTORY" 26 | 27 | - name: Rust Cache 28 | uses: Swatinem/rust-cache@v2.7.8 29 | with: 30 | cache-on-failure: true 31 | cache-all-crates: true 32 | key: ${{ inputs.cache-key }} -------------------------------------------------------------------------------- /.github/workflows/lint-pr.yml: -------------------------------------------------------------------------------- 1 | name: "Lint PR" 2 | 3 | on: 4 | pull_request_target: 5 | types: 6 | - opened 7 | - edited 8 | - synchronize 9 | 10 | permissions: 11 | pull-requests: read 12 | 13 | jobs: 14 | lint: 15 | name: Validate PR title for conventional commit compliance 16 | runs-on: ubuntu-latest 17 | steps: 18 | - uses: amannn/action-semantic-pull-request@v5 19 | env: 20 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Rust directories 2 | **/target 3 | 4 | # MacOS 5 | **/.DS_Store 6 | 7 | # Node 8 | **/node_modules 9 | 10 | # Code Editors / IDEs 11 | .vscode 12 | .idea 13 | 14 | # Binaries 15 | **/bin/ 16 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | # Non-default formatting configuration options: use with `cargo +nightly fmt --all` 2 | binop_separator = "Back" 3 | chain_width = 80 4 | combine_control_expr = false 5 | comment_width = 100 6 | condense_wildcard_suffixes = true 7 | edition = "2021" 8 | format_code_in_doc_comments = true 9 | format_strings = true 10 | group_imports = "StdExternalCrate" 11 | hard_tabs = true 12 | imports_granularity = "Crate" 13 | match_arm_blocks = false 14 | match_block_trailing_comma = true 15 | newline_style = "Unix" 16 | normalize_comments = true 17 | reorder_impl_items = true 18 | trailing_semicolon = false 19 | unstable_features = true 20 | use_field_init_shorthand = true 21 | # Uses max_width or its default value (100) if not specified. 22 | use_small_heuristics = "Max" 23 | use_try_shorthand = true 24 | wrap_comments = true 25 | -------------------------------------------------------------------------------- /.taplo.toml: -------------------------------------------------------------------------------- 1 | # all options https://taplo.tamasfe.dev/configuration/formatter-options.html 2 | 3 | exclude = [ "networks/**", "target/**" ] 4 | 5 | # global rules 6 | [formatting] 7 | array_auto_collapse = false 8 | array_auto_expand = true 9 | compact_arrays = false # zepter compatibility 10 | indent_string = " " # tab 11 | inline_table_expand = false 12 | reorder_arrays = true 13 | reorder_keys = true 14 | 15 | [[rule]] 16 | include = [ "Cargo.toml" ] 17 | keys = [ "workspace.dependencies" ] 18 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # This file is sourced from https://github.com/paritytech/polkadot-sdk/blob/master/docker/dockerfiles/polkadot/polkadot_builder.Dockerfile 2 | FROM docker.io/paritytech/ci-linux:production as builder 3 | # Require the current commit hash to be provided as an argument 4 | ARG SUBSTRATE_CLI_GIT_COMMIT_HASH 5 | RUN test -n "$SUBSTRATE_CLI_GIT_COMMIT_HASH" || (echo "SUBSTRATE_CLI_GIT_COMMIT_HASH not set, provide via --build-arg SUBSTRATE_CLI_GIT_COMMIT_HASH=(git rev-parse --short=11 HEAD)" && false) 6 | ENV SUBSTRATE_CLI_GIT_COMMIT_HASH=$SUBSTRATE_CLI_GIT_COMMIT_HASH 7 | WORKDIR /pop 8 | COPY . /pop 9 | RUN cargo build --release 10 | 11 | # Build image 12 | FROM debian:bullseye-slim as collator 13 | COPY --from=builder /pop/target/release/pop-node /usr/bin/pop-node 14 | CMD ["/usr/bin/pop-node"] 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![pop-net-banner](https://github.com/r0gue-io/pop-node/assets/60948618/e13ec7e6-1aaf-44bc-8ab3-c7b1b876ea3f) 2 | 3 | 4 |
5 | 6 | [![Twitter URL](https://img.shields.io/twitter/follow/Pop?style=social)](https://x.com/onpopio/) 7 | [![Twitter URL](https://img.shields.io/twitter/follow/R0GUE?style=social)](https://twitter.com/gor0gue) 8 | [![Telegram](https://img.shields.io/badge/Telegram-gray?logo=telegram)](https://t.me/onpopio) 9 | [![Build, test and lint](https://github.com/r0gue-io/pop-node/actions/workflows/build.yml/badge.svg)](https://github.com/r0gue-io/pop-node/actions/workflows/build.yml) 10 | 11 |
12 | 13 | Pop Network makes it easy for smart contract developers to use the Power of Polkadot. Through curated runtime 14 | primitives, smart contract developers can spend less time learning the complexities of Polkadot, and more time buidling 15 | awesome things. 16 | 17 | Pop supports Polkadot native contracts (`pallet-contracts`), enabling developers to build with more performant and 18 | secure smart contract languages (such as [ink!](https://use.ink/)). 19 | 20 | Get started by using [Pop API](./pop-api) in your contracts! 21 | 22 | # Launching Local Network 23 | 24 | ## Installation 25 | 26 | You can install the [Pop CLI](https://github.com/r0gue-io/pop-cli) as follows: 27 | 28 | ```shell 29 | cargo install pop-cli 30 | ``` 31 | 32 | ## Spawn Network 33 | 34 | You can spawn a local network as follows: 35 | 36 | ```shell 37 | pop up parachain -f ./networks/testnet.toml 38 | ``` 39 | 40 | Note: `pop` will automatically source the necessary `polkadot` binaries. Currently, these will have to be built if on a 41 | non-linux system. 42 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | # https://docs.codecov.com/docs/common-recipe-list 2 | coverage: 3 | status: 4 | project: 5 | default: 6 | target: auto 7 | threshold: 0% 8 | comment: 9 | layout: " diff, flags, files" 10 | behavior: default 11 | require_changes: false 12 | require_base: false 13 | require_head: true 14 | hide_project_coverage: false -------------------------------------------------------------------------------- /docs/release.md: -------------------------------------------------------------------------------- 1 | # Release Tag and Title Structure 2 | 3 | This table outlines the naming conventions for Node and Runtimes releases, including both the tag format and suggested title format. 4 | 5 | | **Release Type** | **Tag Format** | **Example Tag** | **Title Format** | **Example Title** | 6 | |-----------------------------|---------------------|---------------------|----------------------------|----------------------------| 7 | | Node | `node-x.y.z` | `node-0.1.0` | `Node v` | Node v0.1.0 | 8 | | Devnet - Runtime | `devnet-x.y.z` | `devnet-0.1.0` | `Devnet Runtime v` | **Devnet Runtime v0.1.0** | 9 | | Testnet - Runtime | `testnet-x.y.z` | `testnet-0.2.0` | `Testnet Runtime v` | **Testnet Runtime v0.2.0** | 10 | | Mainnet - Runtime | `mainnet-x.y.z` | `mainnet-1.0.0` | `Mainnet Runtime v` | **Mainnet Runtime v1.0.0** | 11 | -------------------------------------------------------------------------------- /extension/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors.workspace = true 3 | description.workspace = true 4 | edition.workspace = true 5 | homepage.workspace = true 6 | license.workspace = true 7 | name = "pop-chain-extension" 8 | publish = false 9 | repository.workspace = true 10 | version = "0.1.0" 11 | 12 | [package.metadata.docs.rs] 13 | targets = [ "x86_64-unknown-linux-gnu" ] 14 | 15 | [dependencies] 16 | codec.workspace = true 17 | impl-trait-for-tuples.workspace = true 18 | log.workspace = true 19 | 20 | # Substrate 21 | frame-support.workspace = true 22 | frame-system.workspace = true 23 | pallet-contracts.workspace = true 24 | sp-core.workspace = true 25 | sp-runtime.workspace = true 26 | 27 | [dev-dependencies] 28 | contract-build.workspace = true 29 | env_logger.workspace = true 30 | pallet-balances.workspace = true 31 | pallet-contracts.workspace = true 32 | pallet-timestamp.workspace = true 33 | rand.workspace = true 34 | scale-info.workspace = true 35 | sp-io.workspace = true 36 | 37 | [features] 38 | default = [ "std" ] 39 | runtime-benchmarks = [ 40 | "frame-support/runtime-benchmarks", 41 | "frame-system/runtime-benchmarks", 42 | "pallet-balances/runtime-benchmarks", 43 | "pallet-contracts/runtime-benchmarks", 44 | "pallet-timestamp/runtime-benchmarks", 45 | "sp-runtime/runtime-benchmarks", 46 | ] 47 | std = [ 48 | "codec/std", 49 | "frame-support/std", 50 | "frame-system/std", 51 | "log/std", 52 | "pallet-balances/std", 53 | "pallet-contracts/std", 54 | "pallet-timestamp/std", 55 | "scale-info/std", 56 | "sp-core/std", 57 | "sp-io/std", 58 | "sp-runtime/std", 59 | ] 60 | -------------------------------------------------------------------------------- /extension/contract/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = [ "R0GUE " ] 3 | description = "Simple contract for proxying a call to a chain extension." 4 | edition = "2021" 5 | name = "proxy" 6 | version = "0.1.0" 7 | 8 | [dependencies] 9 | ink = { version = "5.1.0", default-features = false } 10 | 11 | [lib] 12 | path = "lib.rs" 13 | 14 | [features] 15 | default = [ "std" ] 16 | std = [ "ink/std" ] 17 | -------------------------------------------------------------------------------- /extension/contract/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(feature = "std"), no_std, no_main)] 2 | 3 | use ink::{ 4 | env::chain_extension::{ChainExtensionMethod, FromStatusCode}, 5 | prelude::vec::Vec, 6 | }; 7 | 8 | #[ink::contract] 9 | mod contract { 10 | use super::*; 11 | 12 | // Simple contract for proxying a call to a chain extension. 13 | #[ink(storage)] 14 | #[derive(Default)] 15 | pub struct Proxy; 16 | 17 | impl Proxy { 18 | #[ink(constructor)] 19 | pub fn new() -> Self { 20 | ink::env::debug_println!("Proxy::new()"); 21 | Default::default() 22 | } 23 | 24 | #[ink(message)] 25 | pub fn call(&self, func_id: u32, input: Vec) -> Result, StatusCode> { 26 | ink::env::debug_println!("Proxy::call() func_id={func_id}, input={input:?}"); 27 | ChainExtensionMethod::build(func_id) 28 | .input::>() 29 | .output::, StatusCode>, true>() 30 | .handle_error_code::() 31 | .call(&input) 32 | } 33 | } 34 | } 35 | 36 | #[ink::scale_derive(Encode, Decode, TypeInfo)] 37 | pub struct StatusCode(u32); 38 | impl FromStatusCode for StatusCode { 39 | fn from_status_code(status_code: u32) -> Result<(), Self> { 40 | match status_code { 41 | 0 => Ok(()), 42 | _ => Err(StatusCode(status_code)), 43 | } 44 | } 45 | } 46 | 47 | impl From for StatusCode { 48 | fn from(_: ink::scale::Error) -> Self { 49 | StatusCode(u32::MAX) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /extension/src/matching.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | /// Trait for matching a function. 4 | pub trait Matches { 5 | /// Determines whether a function is a match. 6 | /// 7 | /// # Parameters 8 | /// - `env` - The current execution environment. 9 | fn matches(env: &impl Environment) -> bool; 10 | } 11 | 12 | /// Matches an extension and function identifier. 13 | pub struct Equals(PhantomData<(E, F)>); 14 | impl, FuncId: Get> Matches for Equals { 15 | fn matches(env: &impl Environment) -> bool { 16 | env.ext_id() == ExtId::get() && env.func_id() == FuncId::get() 17 | } 18 | } 19 | 20 | /// Matches a function identifier only. 21 | pub struct FunctionId(PhantomData); 22 | impl> Matches for FunctionId { 23 | fn matches(env: &impl Environment) -> bool { 24 | env.func_id() == T::get() 25 | } 26 | } 27 | 28 | /// Matches a `u32` function identifier. 29 | pub struct WithFuncId(PhantomData); 30 | impl> Matches for WithFuncId { 31 | fn matches(env: &impl Environment) -> bool { 32 | let ext_id: [u8; 2] = env.ext_id().to_le_bytes(); 33 | let func_id: [u8; 2] = env.func_id().to_le_bytes(); 34 | u32::from_le_bytes([func_id[0], func_id[1], ext_id[0], ext_id[1]]) == T::get() 35 | } 36 | } 37 | 38 | #[cfg(test)] 39 | mod tests { 40 | use sp_core::{ConstU16, ConstU32}; 41 | 42 | use super::*; 43 | use crate::mock::MockEnvironment; 44 | 45 | #[test] 46 | fn equals_matches() { 47 | let env = MockEnvironment::new(u32::from_be_bytes([0u8, 1, 0, 2]), vec![]); 48 | assert!(Equals::, ConstU16<2>>::matches(&env)); 49 | } 50 | 51 | #[test] 52 | fn equals_does_not_match() { 53 | // Fails due to the invalid function id. 54 | let env = MockEnvironment::new(u32::from_be_bytes([0u8, 1, 0, 3]), vec![]); 55 | assert!(!Equals::, ConstU16<2>>::matches(&env)); 56 | 57 | // Fails due to the invalid extension id. 58 | let env = MockEnvironment::new(u32::from_be_bytes([0u8, 2, 0, 2]), vec![]); 59 | assert!(!Equals::, ConstU16<2>>::matches(&env)); 60 | } 61 | 62 | #[test] 63 | fn function_id_matches() { 64 | let env = MockEnvironment::new(u32::from_be_bytes([0u8, 1, 0, 2]), vec![]); 65 | assert!(FunctionId::>::matches(&env)); 66 | } 67 | 68 | #[test] 69 | fn function_id_does_not_match() { 70 | let env = MockEnvironment::new(u32::from_be_bytes([0u8, 1, 0, 3]), vec![]); 71 | assert!(!FunctionId::>::matches(&env)); 72 | } 73 | 74 | #[test] 75 | fn with_func_id_matches() { 76 | let env = MockEnvironment::default(); 77 | assert!(WithFuncId::>::matches(&env)); 78 | 79 | let env = MockEnvironment::new(1, vec![]); 80 | assert!(WithFuncId::>::matches(&env)); 81 | 82 | let env = MockEnvironment::new(100, vec![]); 83 | assert!(WithFuncId::>::matches(&env)); 84 | } 85 | 86 | #[test] 87 | fn with_func_id_does_not_match() { 88 | let env = MockEnvironment::new(1, vec![]); 89 | assert!(!WithFuncId::>::matches(&env)); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /integration-tests/README.md: -------------------------------------------------------------------------------- 1 | In order to run the integration tests you have to specify what Relay and Pop runtime to use. The first also determines the Asset Hub runtime. 2 | ```shell 3 | cargo test --features=, 4 | ``` 5 | For example: 6 | ```shell 7 | cargo test --features=paseo,testnet 8 | ``` -------------------------------------------------------------------------------- /integration-tests/src/chains/asset_hub/genesis.rs: -------------------------------------------------------------------------------- 1 | use cumulus_primitives_core::relay_chain::Balance; 2 | use emulated_integration_tests_common::{ 3 | accounts, build_genesis_storage, collators::invulnerables, SAFE_XCM_VERSION, 4 | }; 5 | use sp_core::storage::Storage; 6 | 7 | use crate::chains::asset_hub::{ 8 | constants::currency::EXISTENTIAL_DEPOSIT, 9 | runtime::{ 10 | BalancesConfig, CollatorSelectionConfig, ParachainInfoConfig, PolkadotXcmConfig, 11 | RuntimeGenesisConfig, SessionConfig, SessionKeys, SystemConfig, WASM_BINARY, 12 | }, 13 | }; 14 | 15 | pub(crate) const ED: Balance = EXISTENTIAL_DEPOSIT; 16 | pub(crate) const PARA_ID: u32 = 1000; 17 | 18 | pub(crate) fn genesis() -> Storage { 19 | let genesis_config = RuntimeGenesisConfig { 20 | system: SystemConfig::default(), 21 | balances: BalancesConfig { 22 | balances: accounts::init_balances() 23 | .iter() 24 | .cloned() 25 | .map(|k| (k, ED * 4096 * 4096)) 26 | .collect(), 27 | ..Default::default() 28 | }, 29 | parachain_info: ParachainInfoConfig { parachain_id: PARA_ID.into(), ..Default::default() }, 30 | collator_selection: CollatorSelectionConfig { 31 | invulnerables: invulnerables().iter().cloned().map(|(acc, _)| acc).collect(), 32 | candidacy_bond: ED * 16, 33 | ..Default::default() 34 | }, 35 | session: SessionConfig { 36 | keys: invulnerables() 37 | .into_iter() 38 | .map(|(acc, aura)| { 39 | ( 40 | acc.clone(), // account id 41 | acc, // validator id 42 | SessionKeys { aura }, // session keys 43 | ) 44 | }) 45 | .collect(), 46 | ..Default::default() 47 | }, 48 | polkadot_xcm: PolkadotXcmConfig { 49 | safe_xcm_version: Some(SAFE_XCM_VERSION), 50 | ..Default::default() 51 | }, 52 | ..Default::default() 53 | }; 54 | 55 | build_genesis_storage( 56 | &genesis_config, 57 | WASM_BINARY.expect("WASM binary was not built, please build it!"), 58 | ) 59 | } 60 | -------------------------------------------------------------------------------- /integration-tests/src/chains/asset_hub/mod.rs: -------------------------------------------------------------------------------- 1 | use emulated_integration_tests_common::{ 2 | impl_accounts_helpers_for_parachain, impl_assert_events_helpers_for_parachain, 3 | impl_assets_helpers_for_parachain, impl_foreign_assets_helpers_for_parachain, 4 | impl_xcm_helpers_for_parachain, impls::Parachain, xcm_emulator::decl_test_parachains, 5 | }; 6 | use frame_support::traits::OnInitialize; 7 | #[cfg(feature = "paseo")] 8 | pub(crate) use {asset_hub_paseo_runtime as runtime, paseo_runtime_constants as constants}; 9 | #[cfg(feature = "westend")] 10 | pub(crate) use {asset_hub_westend_runtime as runtime, westend_runtime_constants as constants}; 11 | 12 | pub(crate) mod genesis; 13 | 14 | // AssetHub Parachain declaration. 15 | decl_test_parachains! { 16 | pub struct AssetHub { 17 | genesis = genesis::genesis(), 18 | on_init = { 19 | runtime::AuraExt::on_initialize(1); 20 | }, 21 | runtime = runtime, 22 | core = { 23 | XcmpMessageHandler: runtime::XcmpQueue, 24 | LocationToAccountId: runtime::xcm_config::LocationToAccountId, 25 | ParachainInfo: runtime::ParachainInfo, 26 | MessageOrigin: cumulus_primitives_core::AggregateMessageOrigin, 27 | }, 28 | pallets = { 29 | PolkadotXcm: runtime::PolkadotXcm, 30 | Assets: runtime::Assets, 31 | ForeignAssets: runtime::ForeignAssets, 32 | Balances: runtime::Balances, 33 | } 34 | }, 35 | } 36 | 37 | // AssetHub implementation. 38 | impl_accounts_helpers_for_parachain!(AssetHub); 39 | impl_assert_events_helpers_for_parachain!(AssetHub); 40 | impl_assets_helpers_for_parachain!(AssetHub); 41 | impl_foreign_assets_helpers_for_parachain!(AssetHub, xcm::v5::Location); 42 | impl_xcm_helpers_for_parachain!(AssetHub); 43 | -------------------------------------------------------------------------------- /integration-tests/src/chains/mod.rs: -------------------------------------------------------------------------------- 1 | pub(crate) mod asset_hub; 2 | pub(crate) mod pop_network; 3 | pub(crate) mod relay; 4 | -------------------------------------------------------------------------------- /integration-tests/src/chains/pop_network/genesis.rs: -------------------------------------------------------------------------------- 1 | use emulated_integration_tests_common::{build_genesis_storage, collators}; 2 | use pop_runtime_common::Balance; 3 | use sp_core::storage::Storage; 4 | 5 | use super::runtime; 6 | 7 | #[cfg(not(feature = "mainnet"))] 8 | pub(crate) const ED: Balance = runtime::EXISTENTIAL_DEPOSIT; 9 | #[cfg(feature = "mainnet")] 10 | pub(crate) const ED: Balance = runtime::EXISTENTIAL_DEPOSIT * 100; 11 | const PARA_ID: u32 = 9090; 12 | const SAFE_XCM_VERSION: u32 = xcm::prelude::XCM_VERSION; 13 | 14 | pub(crate) fn genesis() -> Storage { 15 | let genesis_config = runtime::RuntimeGenesisConfig { 16 | system: runtime::SystemConfig::default(), 17 | balances: runtime::BalancesConfig { ..Default::default() }, 18 | parachain_info: runtime::ParachainInfoConfig { 19 | parachain_id: PARA_ID.into(), 20 | ..Default::default() 21 | }, 22 | collator_selection: runtime::CollatorSelectionConfig { 23 | invulnerables: collators::invulnerables().iter().cloned().map(|(acc, _)| acc).collect(), 24 | candidacy_bond: ED * 16, 25 | ..Default::default() 26 | }, 27 | session: runtime::SessionConfig { 28 | keys: collators::invulnerables() 29 | .into_iter() 30 | .map(|(acc, aura)| { 31 | ( 32 | acc.clone(), // account id 33 | acc, // validator id 34 | runtime::SessionKeys { aura }, // session keys 35 | ) 36 | }) 37 | .collect(), 38 | ..Default::default() 39 | }, 40 | polkadot_xcm: runtime::PolkadotXcmConfig { 41 | safe_xcm_version: Some(SAFE_XCM_VERSION), 42 | ..Default::default() 43 | }, 44 | ..Default::default() 45 | }; 46 | 47 | build_genesis_storage( 48 | &genesis_config, 49 | runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"), 50 | ) 51 | } 52 | -------------------------------------------------------------------------------- /integration-tests/src/chains/pop_network/mod.rs: -------------------------------------------------------------------------------- 1 | pub(crate) mod genesis; 2 | 3 | use emulated_integration_tests_common::{ 4 | impl_accounts_helpers_for_parachain, impl_assert_events_helpers_for_parachain, 5 | impl_xcm_helpers_for_parachain, impls::Parachain, xcm_emulator::decl_test_parachains, 6 | }; 7 | use frame_support::traits::OnInitialize; 8 | #[cfg(feature = "devnet")] 9 | pub(crate) use pop_runtime_devnet as runtime; 10 | #[cfg(feature = "mainnet")] 11 | pub(crate) use pop_runtime_mainnet as runtime; 12 | #[cfg(feature = "testnet")] 13 | pub(crate) use pop_runtime_testnet as runtime; 14 | 15 | // PopNetwork Parachain declaration 16 | decl_test_parachains! { 17 | pub struct PopNetwork { 18 | genesis = genesis::genesis(), 19 | on_init = { 20 | runtime::AuraExt::on_initialize(1); 21 | }, 22 | runtime = runtime, 23 | core = { 24 | XcmpMessageHandler: runtime::XcmpQueue, 25 | LocationToAccountId: runtime::config::xcm::LocationToAccountId, 26 | ParachainInfo: runtime::ParachainInfo, 27 | MessageOrigin: cumulus_primitives_core::AggregateMessageOrigin, 28 | }, 29 | pallets = { 30 | PolkadotXcm: runtime::PolkadotXcm, 31 | Balances: runtime::Balances, 32 | } 33 | }, 34 | } 35 | 36 | // PopNetwork implementation 37 | impl_accounts_helpers_for_parachain!(PopNetwork); 38 | impl_assert_events_helpers_for_parachain!(PopNetwork); 39 | impl_xcm_helpers_for_parachain!(PopNetwork); 40 | -------------------------------------------------------------------------------- /integration-tests/src/chains/relay/genesis.rs: -------------------------------------------------------------------------------- 1 | use emulated_integration_tests_common::{ 2 | accounts, build_genesis_storage, get_host_config, validators, 3 | }; 4 | use polkadot_primitives::{AssignmentId, Balance, ValidatorId, LOWEST_PUBLIC_ID}; 5 | use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; 6 | use sp_consensus_babe::AuthorityId as BabeId; 7 | use sp_consensus_beefy::{ecdsa_crypto::AuthorityId as BeefyId, test_utils::Keyring}; 8 | use sp_consensus_grandpa::AuthorityId as GrandpaId; 9 | use sp_core::storage::Storage; 10 | 11 | use crate::chains::relay::{ 12 | constants::currency::{EXISTENTIAL_DEPOSIT, UNITS}, 13 | runtime::{ 14 | BabeConfig, BalancesConfig, ConfigurationConfig, RegistrarConfig, RuntimeGenesisConfig, 15 | SessionConfig, SessionKeys, SystemConfig, BABE_GENESIS_EPOCH_CONFIG, WASM_BINARY, 16 | }, 17 | }; 18 | 19 | pub(crate) const ED: Balance = EXISTENTIAL_DEPOSIT; 20 | const ENDOWMENT: u128 = 1_000_000 * UNITS; 21 | 22 | pub(crate) fn genesis() -> Storage { 23 | let genesis_config = RuntimeGenesisConfig { 24 | system: SystemConfig::default(), 25 | balances: BalancesConfig { 26 | balances: accounts::init_balances().iter().map(|k| (k.clone(), ENDOWMENT)).collect(), 27 | ..Default::default() 28 | }, 29 | session: SessionConfig { 30 | keys: validators::initial_authorities() 31 | .iter() 32 | .map(|x| { 33 | ( 34 | x.0.clone(), 35 | x.0.clone(), 36 | session_keys( 37 | x.2.clone(), 38 | x.3.clone(), 39 | x.4.clone(), 40 | x.5.clone(), 41 | x.6.clone(), 42 | Keyring::Alice.into(), 43 | ), 44 | ) 45 | }) 46 | .collect::>(), 47 | ..Default::default() 48 | }, 49 | babe: BabeConfig { 50 | authorities: Default::default(), 51 | epoch_config: BABE_GENESIS_EPOCH_CONFIG, 52 | ..Default::default() 53 | }, 54 | configuration: ConfigurationConfig { config: get_host_config() }, 55 | registrar: RegistrarConfig { next_free_para_id: LOWEST_PUBLIC_ID, ..Default::default() }, 56 | ..Default::default() 57 | }; 58 | 59 | build_genesis_storage(&genesis_config, WASM_BINARY.unwrap()) 60 | } 61 | 62 | fn session_keys( 63 | babe: BabeId, 64 | grandpa: GrandpaId, 65 | para_validator: ValidatorId, 66 | para_assignment: AssignmentId, 67 | authority_discovery: AuthorityDiscoveryId, 68 | beefy: BeefyId, 69 | ) -> SessionKeys { 70 | SessionKeys { babe, grandpa, para_validator, para_assignment, authority_discovery, beefy } 71 | } 72 | 73 | // In case we want to add Polkadot in the future, the following change in `invulnerables` is 74 | // required. 75 | // 76 | // #[cfg(feature = "polkadot")] 77 | // use emulated_integration_tests_common::{get_account_id_from_seed, get_from_seed}; 78 | // use sp_core::sr25519; 79 | // use polkadot_primitives::{AccountId, Balance}; 80 | // 81 | // type AuraId = sp_consensus_aura::ed25519::AuthorityId; 82 | // pub fn invulnerables() -> Vec<(AccountId, AuraId)> { 83 | // vec![ 84 | // (get_account_id_from_seed::("Alice"), get_from_seed::("Alice")), 85 | // (get_account_id_from_seed::("Bob"), get_from_seed::("Bob")), 86 | // ] 87 | // } 88 | -------------------------------------------------------------------------------- /integration-tests/src/chains/relay/mod.rs: -------------------------------------------------------------------------------- 1 | use emulated_integration_tests_common::{ 2 | impl_accounts_helpers_for_relay_chain, impl_assert_events_helpers_for_relay_chain, 3 | impl_hrmp_channels_helpers_for_relay_chain, impl_send_transact_helpers_for_relay_chain, 4 | xcm_emulator::decl_test_relay_chains, 5 | }; 6 | use polkadot_primitives::runtime_api::runtime_decl_for_parachain_host::ParachainHostV13; 7 | #[cfg(feature = "paseo")] 8 | pub(crate) use { 9 | paseo_runtime::{self as runtime, xcm_config::SovereignAccountOf}, 10 | paseo_runtime_constants as constants, 11 | }; 12 | #[cfg(feature = "westend")] 13 | pub(crate) use { 14 | westend_runtime::{self as runtime, xcm_config::LocationConverter as SovereignAccountOf}, 15 | westend_runtime_constants as constants, 16 | }; 17 | 18 | pub(crate) mod genesis; 19 | 20 | // Relay declaration. 21 | decl_test_relay_chains! { 22 | #[api_version(11)] 23 | pub struct Relay { 24 | genesis = genesis::genesis(), 25 | on_init = (), 26 | runtime = runtime, 27 | core = { 28 | SovereignAccountOf: SovereignAccountOf, 29 | }, 30 | pallets = { 31 | XcmPallet: runtime::XcmPallet, 32 | Balances: runtime::Balances, 33 | Hrmp: runtime::Hrmp, 34 | } 35 | }, 36 | } 37 | 38 | // Relay implementation. 39 | impl_accounts_helpers_for_relay_chain!(Relay); 40 | impl_assert_events_helpers_for_relay_chain!(Relay); 41 | impl_hrmp_channels_helpers_for_relay_chain!(Relay); 42 | impl_send_transact_helpers_for_relay_chain!(Relay); 43 | -------------------------------------------------------------------------------- /networks/README.md: -------------------------------------------------------------------------------- 1 | # Zombienet 2 | 3 | ## Installation 4 | 5 | You can install the Pop CLI as follows: 6 | 7 | ```shell 8 | cargo install --git https://github.com/r0gue-io/pop-cli 9 | ``` 10 | 11 | ## Spawn Network 12 | 13 | You can spawn a local network as follows: 14 | 15 | ```shell 16 | pop up parachain -f ./networks/testnet.toml 17 | ``` -------------------------------------------------------------------------------- /networks/devnet.toml: -------------------------------------------------------------------------------- 1 | # pop up parachain -f ./tests/networks/pop.toml 2 | 3 | [relaychain] 4 | chain = "paseo-local" 5 | 6 | [relaychain.runtime_genesis_patch.balances] 7 | balances = [ 8 | # Pop sovereign account 9 | ["5Ec4AhPKXY9B4ayGshkz2wFMh7N8gP7XKfAvtt1cigpG9FkJ", 60000000000000000], 10 | ] 11 | 12 | [[relaychain.nodes]] 13 | name = "alice" 14 | rpc_port = 8833 15 | validator = true 16 | 17 | [[relaychain.nodes]] 18 | name = "bob" 19 | validator = true 20 | 21 | [[parachains]] 22 | id = 4001 23 | chain = "pop-devnet-dev" # pop devnet runtime with development config. 24 | default_command = "./target/release/pop-node" 25 | 26 | [parachains.genesis_overrides.balances] 27 | balances = [ 28 | # Dev accounts 29 | ["5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", 10000000000000000], 30 | ["5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", 10000000000000000], 31 | ["5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y", 10000000000000000], 32 | ["5DAAnrj7VHTznn2AWBemMuyBwZWs6FNFjdyVXUeYum3PTXFy", 10000000000000000], 33 | ["5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", 10000000000000000], 34 | ["5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL", 10000000000000000], 35 | ] 36 | 37 | [[parachains.collators]] 38 | name = "pop" 39 | rpc_port = 9944 40 | args = [ 41 | "-lpop-api::extension=debug", 42 | "-lruntime::contracts=trace", 43 | "-lxcm=trace", 44 | "--enable-offchain-indexing=true" 45 | ] 46 | 47 | [[parachains]] 48 | id = 1000 49 | chain = "asset-hub-paseo-local" 50 | 51 | [[parachains.collators]] 52 | name = "asset-hub" 53 | args = ["-lxcm=trace"] 54 | rpc_port = 9977 55 | -------------------------------------------------------------------------------- /networks/mainnet.toml: -------------------------------------------------------------------------------- 1 | # pop up parachain -f ./networks/mainnet.toml 2 | 3 | [relaychain] 4 | chain = "paseo-local" 5 | 6 | [relaychain.runtime_genesis_patch.balances] 7 | balances = [ 8 | # Pop sovereign account 9 | ["5Ec4AhPKXY9B4ayGshkz2wFMh7N8gP7XKfAvtt1cigpG9FkJ", 60000000000000000], 10 | ] 11 | 12 | [[relaychain.nodes]] 13 | name = "alice" 14 | rpc_port = 8833 15 | validator = true 16 | 17 | [[relaychain.nodes]] 18 | name = "bob" 19 | validator = true 20 | 21 | [[parachains]] 22 | id = 4001 23 | chain = "pop-dev" # mainnet runtime with development config. 24 | default_command = "./target/release/pop-node" 25 | 26 | [parachains.genesis_overrides.balances] 27 | balances = [ 28 | # Dev accounts 29 | ["5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", 10000000000000000], 30 | ["5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", 10000000000000000], 31 | ["5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y", 10000000000000000], 32 | ["5DAAnrj7VHTznn2AWBemMuyBwZWs6FNFjdyVXUeYum3PTXFy", 10000000000000000], 33 | ["5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", 10000000000000000], 34 | ["5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL", 10000000000000000], 35 | ] 36 | 37 | [[parachains.collators]] 38 | name = "pop" 39 | rpc_port = 9944 40 | args = [ 41 | "-lruntime::revive=trace", 42 | "-lruntime::revive::strace=trace", 43 | "-lxcm=trace", 44 | ] 45 | -------------------------------------------------------------------------------- /networks/testnet.toml: -------------------------------------------------------------------------------- 1 | # pop up parachain -f ./tests/networks/pop.toml 2 | 3 | [relaychain] 4 | chain = "paseo-local" 5 | 6 | [relaychain.runtime_genesis_patch.balances] 7 | balances = [ 8 | # Pop sovereign account 9 | ["5Ec4AhPKXY9B4ayGshkz2wFMh7N8gP7XKfAvtt1cigpG9FkJ", 60000000000000000], 10 | ] 11 | 12 | [[relaychain.nodes]] 13 | name = "alice" 14 | rpc_port = 8833 15 | validator = true 16 | 17 | [[relaychain.nodes]] 18 | name = "bob" 19 | validator = true 20 | 21 | [[parachains]] 22 | id = 4001 23 | chain = "pop-testnet-dev" # pop testnet runtime with development config. 24 | default_command = "./target/release/pop-node" 25 | 26 | [parachains.genesis_overrides.balances] 27 | balances = [ 28 | # Dev accounts 29 | ["5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", 10000000000000000], 30 | ["5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", 10000000000000000], 31 | ["5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y", 10000000000000000], 32 | ["5DAAnrj7VHTznn2AWBemMuyBwZWs6FNFjdyVXUeYum3PTXFy", 10000000000000000], 33 | ["5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", 10000000000000000], 34 | ["5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL", 10000000000000000], 35 | ] 36 | 37 | [[parachains.collators]] 38 | name = "pop" 39 | rpc_port = 9944 40 | args = [ 41 | "-lpop-api::extension=debug", 42 | "-lruntime::contracts=debug", 43 | "-lruntime::revive=trace", 44 | "-lruntime::revive::strace=trace", 45 | "-lxcm=trace", 46 | "--enable-offchain-indexing=true" 47 | ] 48 | 49 | # Asset Hub 50 | [[parachains]] 51 | id = 1000 52 | chain = "asset-hub-paseo-local" 53 | 54 | [parachains.genesis_overrides.balances] 55 | balances = [ 56 | # Pop sovereign account 57 | ["5Eg2fnt8cGL5CBhRRhi59abAwb3SPoAdPJpN9qY7bQqpzpf6", 60000000000000000], 58 | ] 59 | 60 | [[parachains.collators]] 61 | name = "asset-hub" 62 | args = ["-lxcm=trace"] 63 | rpc_port = 9977 64 | 65 | # Channels 66 | [[hrmp_channels]] 67 | sender = 1000 68 | recipient = 4001 69 | max_capacity = 1000 70 | max_message_size = 1024 71 | 72 | [[hrmp_channels]] 73 | sender = 4001 74 | recipient = 1000 75 | max_capacity = 1000 76 | max_message_size = 1024 -------------------------------------------------------------------------------- /node/build.rs: -------------------------------------------------------------------------------- 1 | use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; 2 | 3 | fn main() { 4 | generate_cargo_keys(); 5 | 6 | rerun_if_git_head_changed(); 7 | } 8 | -------------------------------------------------------------------------------- /node/chain_specs/mainnet/pop-genesis-hash: -------------------------------------------------------------------------------- 1 | 0x6e53695daa61933e947c9298c67162ffedf881f2d8a4cf06f8e1d9394958a0f5 2 | -------------------------------------------------------------------------------- /node/chain_specs/mainnet/pop-genesis-state: -------------------------------------------------------------------------------- 1 | 0x000000000000000000000000000000000000000000000000000000000000000000a4d7b9b2f1aa005dc255c6aa9bd9b4d9dd70b9e376cac147474df7b0371da0aa03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c11131400 -------------------------------------------------------------------------------- /node/src/cli.rs: -------------------------------------------------------------------------------- 1 | use std::path::PathBuf; 2 | 3 | /// Sub-commands supported by the collator. 4 | #[derive(Debug, clap::Subcommand)] 5 | pub enum Subcommand { 6 | /// Build a chain specification. 7 | BuildSpec(sc_cli::BuildSpecCmd), 8 | 9 | /// Validate blocks. 10 | CheckBlock(sc_cli::CheckBlockCmd), 11 | 12 | /// Export blocks. 13 | ExportBlocks(sc_cli::ExportBlocksCmd), 14 | 15 | /// Export the state of a given block into a chain spec. 16 | ExportState(sc_cli::ExportStateCmd), 17 | 18 | /// Import blocks. 19 | ImportBlocks(sc_cli::ImportBlocksCmd), 20 | 21 | /// Revert the chain to a previous state. 22 | Revert(sc_cli::RevertCmd), 23 | 24 | /// Remove the whole chain. 25 | PurgeChain(cumulus_client_cli::PurgeChainCmd), 26 | 27 | /// Export the genesis head data of the parachain. 28 | /// 29 | /// Head data is the encoded block header. 30 | #[command(alias = "export-genesis-state")] 31 | ExportGenesisHead(cumulus_client_cli::ExportGenesisHeadCommand), 32 | 33 | /// Export the genesis wasm of the parachain. 34 | ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand), 35 | 36 | /// Sub-commands concerned with benchmarking. 37 | /// The pallet benchmarking moved to the `pallet` sub-command. 38 | #[command(subcommand)] 39 | Benchmark(frame_benchmarking_cli::BenchmarkCmd), 40 | 41 | /// Key management CLI utilities 42 | #[command(subcommand)] 43 | Key(sc_cli::KeySubcommand), 44 | } 45 | 46 | const AFTER_HELP_EXAMPLE: &str = color_print::cstr!( 47 | r#"Examples: 48 | pop-node build-spec --disable-default-bootnode > plain-parachain-chainspec.json 49 | Export a chainspec for a local testnet in json format. 50 | pop-node --chain plain-parachain-chainspec.json --tmp -- --chain rococo-local 51 | Launch a full node with chain specification loaded from plain-parachain-chainspec.json. 52 | pop-node 53 | Launch a full node with default parachain local-testnet and relay chain rococo-local. 54 | pop-node --collator 55 | Launch a collator with default parachain local-testnet and relay chain rococo-local. 56 | "# 57 | ); 58 | #[derive(Debug, clap::Parser)] 59 | #[command( 60 | propagate_version = true, 61 | args_conflicts_with_subcommands = true, 62 | subcommand_negates_reqs = true 63 | )] 64 | #[clap(after_help = AFTER_HELP_EXAMPLE)] 65 | pub struct Cli { 66 | #[command(subcommand)] 67 | pub subcommand: Option, 68 | 69 | #[command(flatten)] 70 | pub run: cumulus_client_cli::RunCmd, 71 | 72 | /// Disable automatic hardware benchmarks. 73 | /// 74 | /// By default these benchmarks are automatically ran at startup and measure 75 | /// the CPU speed, the memory bandwidth and the disk speed. 76 | /// 77 | /// The results are then printed out in the logs, and also sent as part of 78 | /// telemetry, if telemetry is enabled. 79 | #[arg(long)] 80 | pub no_hardware_benchmarks: bool, 81 | 82 | /// Relay chain arguments 83 | #[arg(raw = true)] 84 | pub relay_chain_args: Vec, 85 | } 86 | 87 | #[derive(Debug)] 88 | pub struct RelayChainCli { 89 | /// The actual relay chain cli object. 90 | pub base: polkadot_cli::RunCmd, 91 | 92 | /// Optional chain id that should be passed to the relay chain. 93 | pub chain_id: Option, 94 | 95 | /// The base path that should be used by the relay chain. 96 | pub base_path: Option, 97 | } 98 | 99 | impl RelayChainCli { 100 | /// Parse the relay chain CLI parameters using the para chain `Configuration`. 101 | pub fn new<'a>( 102 | para_config: &sc_service::Configuration, 103 | relay_chain_args: impl Iterator, 104 | ) -> Self { 105 | let extension = crate::chain_spec::Extensions::try_get(&*para_config.chain_spec); 106 | let chain_id = extension.map(|e| e.relay_chain.clone()); 107 | let base_path = para_config.base_path.path().join("polkadot"); 108 | Self { 109 | base_path: Some(base_path), 110 | chain_id, 111 | base: clap::Parser::parse_from(relay_chain_args), 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /node/src/main.rs: -------------------------------------------------------------------------------- 1 | //! Pop Parachain Node 2 | 3 | #![warn(missing_docs)] 4 | 5 | mod chain_spec; 6 | mod cli; 7 | mod command; 8 | mod rpc; 9 | mod service; 10 | 11 | fn main() -> sc_cli::Result<()> { 12 | command::run() 13 | } 14 | -------------------------------------------------------------------------------- /node/src/rpc.rs: -------------------------------------------------------------------------------- 1 | //! A collection of node-specific RPC methods. 2 | //! Substrate provides the `sc-rpc` crate, which defines the core RPC layer 3 | //! used by Substrate nodes. This file extends those RPC definitions with 4 | //! capabilities that are specific to this project's runtime configuration. 5 | 6 | #![warn(missing_docs)] 7 | 8 | use std::sync::Arc; 9 | 10 | use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; 11 | use pop_runtime_common::{AccountId, Balance, Block, Nonce}; 12 | use sc_client_api::{AuxStore, BlockBackend, ProofProvider}; 13 | use sc_transaction_pool_api::TransactionPool; 14 | use sp_api::ProvideRuntimeApi; 15 | use sp_block_builder::BlockBuilder; 16 | use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; 17 | #[cfg(feature = "ismp")] 18 | use sp_core::H256; 19 | use substrate_frame_rpc_system::{System, SystemApiServer}; 20 | 21 | /// A type representing all RPC extensions. 22 | pub type RpcExtension = jsonrpsee::RpcModule<()>; 23 | 24 | /// Full client dependencies 25 | pub struct FullDeps { 26 | /// The client instance to use. 27 | pub client: Arc, 28 | /// Transaction pool instance. 29 | pub pool: Arc

, 30 | /// Backend used by the node. 31 | pub backend: Arc, 32 | } 33 | 34 | /// Instantiate all RPC extensions. 35 | #[cfg(not(feature = "ismp"))] 36 | pub fn create_full( 37 | deps: FullDeps, 38 | ) -> Result> 39 | where 40 | C: ProvideRuntimeApi 41 | + HeaderBackend 42 | + AuxStore 43 | + BlockBackend 44 | + ProofProvider 45 | + HeaderMetadata 46 | + Send 47 | + Sync 48 | + 'static, 49 | C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, 50 | C::Api: substrate_frame_rpc_system::AccountNonceApi, 51 | C::Api: BlockBuilder, 52 | P: TransactionPool + Sync + Send + 'static, 53 | B: sc_client_api::Backend + Send + Sync + 'static, 54 | B::State: sc_client_api::StateBackend>, 55 | { 56 | let mut module = RpcExtension::new(()); 57 | let FullDeps { client, pool, backend: _ } = deps; 58 | 59 | module.merge(System::new(client.clone(), pool).into_rpc())?; 60 | module.merge(TransactionPayment::new(client.clone()).into_rpc())?; 61 | 62 | Ok(module) 63 | } 64 | 65 | /// Instantiate all RPC extensions. 66 | #[cfg(feature = "ismp")] 67 | pub fn create_full( 68 | deps: FullDeps, 69 | ) -> Result> 70 | where 71 | C: ProvideRuntimeApi 72 | + HeaderBackend 73 | + AuxStore 74 | + BlockBackend 75 | + ProofProvider 76 | + HeaderMetadata 77 | + Send 78 | + Sync 79 | + 'static, 80 | C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, 81 | C::Api: substrate_frame_rpc_system::AccountNonceApi, 82 | C::Api: BlockBuilder, 83 | C::Api: pallet_ismp_runtime_api::IsmpRuntimeApi, 84 | P: TransactionPool + Sync + Send + 'static, 85 | B: sc_client_api::Backend + Send + Sync + 'static, 86 | B::State: sc_client_api::StateBackend>, 87 | { 88 | let mut module = RpcExtension::new(()); 89 | let FullDeps { client, pool, backend } = deps; 90 | 91 | module.merge(System::new(client.clone(), pool).into_rpc())?; 92 | module.merge(TransactionPayment::new(client.clone()).into_rpc())?; 93 | 94 | use pallet_ismp_rpc::{IsmpApiServer, IsmpRpcHandler}; 95 | module.merge(IsmpRpcHandler::new(client, backend.clone())?.into_rpc())?; 96 | 97 | Ok(module) 98 | } 99 | -------------------------------------------------------------------------------- /pallets/api/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors.workspace = true 3 | description = "API pallet, enabling smart(er) contracts with the power of Polkadot" 4 | edition.workspace = true 5 | license.workspace = true 6 | name = "pallet-api" 7 | version = "0.1.0" 8 | 9 | [package.metadata.docs.rs] 10 | targets = [ "x86_64-unknown-linux-gnu" ] 11 | 12 | [dependencies] 13 | anyhow.workspace = true 14 | codec.workspace = true 15 | log.workspace = true 16 | scale-info.workspace = true 17 | 18 | # Local 19 | pop-chain-extension.workspace = true 20 | 21 | # Substrate 22 | frame-benchmarking.workspace = true 23 | frame-support.workspace = true 24 | frame-system.workspace = true 25 | pallet-assets.workspace = true 26 | pallet-nfts.workspace = true 27 | sp-core.workspace = true 28 | sp-runtime.workspace = true 29 | 30 | # Cross chain 31 | ismp.workspace = true 32 | pallet-ismp.workspace = true 33 | xcm.workspace = true 34 | 35 | [dev-dependencies] 36 | pallet-balances.workspace = true 37 | sp-io.workspace = true 38 | 39 | [features] 40 | default = [ "std" ] 41 | runtime-benchmarks = [ 42 | "frame-benchmarking/runtime-benchmarks", 43 | "frame-support/runtime-benchmarks", 44 | "frame-system/runtime-benchmarks", 45 | "pallet-assets/runtime-benchmarks", 46 | "pallet-nfts/runtime-benchmarks", 47 | "pop-chain-extension/runtime-benchmarks", 48 | "sp-runtime/runtime-benchmarks", 49 | ] 50 | std = [ 51 | "codec/std", 52 | "frame-benchmarking/std", 53 | "frame-support/std", 54 | "frame-system/std", 55 | "ismp/std", 56 | "pallet-assets/std", 57 | "pallet-balances/std", 58 | "pallet-ismp/std", 59 | "pallet-nfts/std", 60 | "pop-chain-extension/std", 61 | "scale-info/std", 62 | "sp-core/std", 63 | "sp-io/std", 64 | "sp-runtime/std", 65 | ] 66 | try-runtime = [ 67 | "frame-support/try-runtime", 68 | "frame-system/try-runtime", 69 | "pallet-nfts/try-runtime", 70 | "sp-runtime/try-runtime", 71 | ] 72 | -------------------------------------------------------------------------------- /pallets/api/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(feature = "std"), no_std)] 2 | 3 | extern crate alloc; 4 | pub use extension::Extension; 5 | use frame_support::pallet_prelude::Weight; 6 | 7 | pub mod extension; 8 | pub mod fungibles; 9 | pub mod messaging; 10 | #[cfg(test)] 11 | mod mock; 12 | pub mod nonfungibles; 13 | 14 | /// Trait for performing reads of runtime state. 15 | pub trait Read { 16 | /// The type of read requested. 17 | type Read; 18 | /// The type of result returned. 19 | type Result; 20 | 21 | /// Determines the weight of the requested read, used to charge the appropriate weight before 22 | /// the read is performed. 23 | /// 24 | /// # Parameters 25 | /// - `request` - The read request. 26 | fn weight(request: &Self::Read) -> Weight; 27 | 28 | /// Performs the requested read and returns the result. 29 | /// 30 | /// # Parameters 31 | /// - `request` - The read request. 32 | fn read(request: Self::Read) -> Self::Result; 33 | } 34 | -------------------------------------------------------------------------------- /pallets/api/src/messaging/transports/mod.rs: -------------------------------------------------------------------------------- 1 | /// Messaging using the Interoperable State Machine Protocol (ISMP). 2 | pub mod ismp; 3 | /// Messaging using Polkadot's Cross-Consensus Messaging (XCM). 4 | pub(crate) mod xcm; 5 | -------------------------------------------------------------------------------- /pallets/api/src/messaging/transports/xcm.rs: -------------------------------------------------------------------------------- 1 | pub(crate) use xcm::latest::{Location, QueryId, Response}; 2 | 3 | use crate::messaging::{pallet::Call, BlockNumberOf, Config}; 4 | 5 | pub trait NotifyQueryHandler { 6 | /// Attempt to create a new query ID and register it as a query that is yet to respond, and 7 | /// which will call a dispatchable when a response happens. 8 | fn new_notify_query( 9 | responder: impl Into, 10 | notify: Call, 11 | timeout: BlockNumberOf, 12 | match_querier: impl Into, 13 | ) -> u64; 14 | } 15 | -------------------------------------------------------------------------------- /pallets/api/src/nonfungibles/benchmarking.rs: -------------------------------------------------------------------------------- 1 | //! Benchmarking setup for pallet_api::nonfungibles 2 | 3 | use frame_benchmarking::{account, v2::*}; 4 | use frame_support::BoundedVec; 5 | use sp_runtime::traits::Zero; 6 | 7 | use super::{ 8 | AttributeNamespace, CollectionIdOf, Config, Inspect, ItemIdOf, NftsInstanceOf, Pallet, Read, 9 | }; 10 | use crate::Read as _; 11 | 12 | const SEED: u32 = 1; 13 | 14 | #[benchmarks( 15 | where 16 | > as Inspect<::AccountId>>::ItemId: Zero, 17 | > as Inspect<::AccountId>>::CollectionId: Zero, 18 | )] 19 | mod benchmarks { 20 | use super::*; 21 | 22 | #[benchmark] 23 | // Storage: `Collection` 24 | fn total_supply() { 25 | #[block] 26 | { 27 | Pallet::::read(Read::TotalSupply(CollectionIdOf::::zero())); 28 | } 29 | } 30 | 31 | #[benchmark] 32 | // Storage: `AccountBalance` 33 | fn balance_of() { 34 | #[block] 35 | { 36 | Pallet::::read(Read::BalanceOf { 37 | collection: CollectionIdOf::::zero(), 38 | owner: account("Alice", 0, SEED), 39 | }); 40 | } 41 | } 42 | 43 | #[benchmark] 44 | // Storage: `Allowances`, `Item` 45 | fn allowance() { 46 | #[block] 47 | { 48 | Pallet::::read(Read::Allowance { 49 | collection: CollectionIdOf::::zero(), 50 | owner: account("Alice", 0, SEED), 51 | operator: account("Bob", 0, SEED), 52 | item: Some(ItemIdOf::::zero()), 53 | }); 54 | } 55 | } 56 | 57 | #[benchmark] 58 | // Storage: `Item` 59 | fn owner_of() { 60 | #[block] 61 | { 62 | Pallet::::read(Read::OwnerOf { 63 | collection: CollectionIdOf::::zero(), 64 | item: ItemIdOf::::zero(), 65 | }); 66 | } 67 | } 68 | 69 | #[benchmark] 70 | // Storage: `Attribute` 71 | fn get_attribute() { 72 | #[block] 73 | { 74 | Pallet::::read(Read::GetAttribute { 75 | key: BoundedVec::default(), 76 | collection: CollectionIdOf::::zero(), 77 | item: Some(ItemIdOf::::zero()), 78 | namespace: AttributeNamespace::CollectionOwner, 79 | }); 80 | } 81 | } 82 | 83 | #[benchmark] 84 | // Storage: `NextCollectionId` 85 | fn next_collection_id() { 86 | #[block] 87 | { 88 | Pallet::::read(Read::NextCollectionId); 89 | } 90 | } 91 | 92 | #[benchmark] 93 | // Storage: `ItemMetadata` 94 | fn item_metadata() { 95 | #[block] 96 | { 97 | Pallet::::read(Read::ItemMetadata { 98 | collection: CollectionIdOf::::zero(), 99 | item: ItemIdOf::::zero(), 100 | }); 101 | } 102 | } 103 | 104 | impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test); 105 | } 106 | -------------------------------------------------------------------------------- /pallets/motion/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = [ "Parity Technologies ", "R0GUE " ] 3 | description = "FRAME pallet to wrap council calls providing root origin to the council." 4 | edition = { workspace = true } 5 | homepage = { workspace = true } 6 | license = { workspace = true } 7 | name = "pallet-motion" 8 | publish = false 9 | repository = { workspace = true } 10 | version = "4.0.0-dev" 11 | 12 | [package.metadata.docs.rs] 13 | targets = [ "x86_64-unknown-linux-gnu" ] 14 | 15 | [dependencies] 16 | codec = { workspace = true, default-features = false, features = [ 17 | "derive", 18 | ] } 19 | frame-benchmarking = { workspace = true, default-features = false, optional = true } 20 | frame-support = { workspace = true } 21 | frame-system = { workspace = true } 22 | log = { workspace = true, default-features = false } 23 | pallet-collective = { workspace = true, default-features = false } 24 | scale-info = { workspace = true, default-features = false, features = [ 25 | "derive", 26 | ] } 27 | sp-runtime = { workspace = true, default-features = false } 28 | 29 | [dev-dependencies] 30 | pallet-balances = { workspace = true, default-features = false } 31 | sp-core = { workspace = true, default-features = false } 32 | sp-io = { workspace = true, default-features = false } 33 | 34 | [features] 35 | default = [ "std" ] 36 | runtime-benchmarks = [ 37 | "frame-benchmarking/runtime-benchmarks", 38 | "pallet-collective/runtime-benchmarks", 39 | ] 40 | std = [ 41 | "codec/std", 42 | "frame-benchmarking?/std", 43 | "frame-support/std", 44 | "frame-system/std", 45 | "log/std", 46 | "pallet-balances/std", 47 | "pallet-collective/std", 48 | "scale-info/std", 49 | "sp-runtime/std", 50 | ] 51 | try-runtime = [ "frame-support/try-runtime" ] 52 | -------------------------------------------------------------------------------- /pallets/motion/README.md: -------------------------------------------------------------------------------- 1 | # Motion Pallet 2 | 3 | `pallet-motion` enables councils (`pallet-collective`) to make root-origin calls by providing three configurable origins: 4 | - `SimpleMajority` (1/2) 5 | - `SuperMajority` (2/3) 6 | - `Unanimous` (1/1) 7 | 8 | It is composed of three associated extrinsics, one for each origin: 9 | - `simple_majority` 10 | - Dispatches the call if and only if the number of votes is greater than `SimpleMajority`. 11 | - `super_majority` 12 | - Dispatches the call if and only if the number of votes is greater than or equal to `SuperMajority`. 13 | - `unanimous` 14 | - Dispatches the call if and only if all collective members have voted yes. 15 | 16 | 17 | ## Configuration 18 | 19 | You can configure `pallet-motion` in combination with `pallet-collective` the following way: 20 | 21 | ```rust 22 | type CouncilCollective = pallet_collective::Instance1; 23 | impl pallet_motion::Config for Runtime { 24 | // --- 25 | type SimpleMajorityOrigin = 26 | pallet_collective::EnsureProportionMoreThan; 27 | type SuperMajorityOrigin = 28 | pallet_collective::EnsureProportionAtLeast; 29 | type UnanimousOrigin = 30 | pallet_collective::EnsureProportionAtLeast; 31 | } 32 | ``` 33 | 34 | --- 35 | 36 | ### Credit: 37 | 38 | Original source at: https://github.com/Watr-Protocol/watr/tree/main/pallets/motion 39 | -------------------------------------------------------------------------------- /pallets/motion/src/benchmarking.rs: -------------------------------------------------------------------------------- 1 | //! Benchmarking setup for pallet-motion 2 | 3 | use frame_benchmarking::v2::*; 4 | use frame_support::traits::EnsureOrigin; 5 | 6 | use super::*; 7 | #[allow(unused)] 8 | use crate::Pallet as Motion; 9 | 10 | fn assert_last_event(generic_event: ::RuntimeEvent) { 11 | frame_system::Pallet::::assert_last_event(generic_event.into()); 12 | } 13 | 14 | #[benchmarks( 15 | where 16 | ::RuntimeCall: From>, 17 | )] 18 | mod benchmarks { 19 | use super::*; 20 | 21 | #[benchmark] 22 | fn simple_majority() -> Result<(), BenchmarkError> { 23 | let call: ::RuntimeCall = frame_system::Call::remark { remark: vec![] }.into(); 24 | let origin = ::SimpleMajorityOrigin::try_successful_origin() 25 | .map_err(|_| BenchmarkError::Stop("Origin should be present"))?; 26 | 27 | #[extrinsic_call] 28 | _(origin as T::RuntimeOrigin, Box::new(call)); 29 | 30 | assert_last_event::(Event::DispatchSimpleMajority { motion_result: Ok(()) }.into()); 31 | Ok(()) 32 | } 33 | 34 | #[benchmark] 35 | fn super_majority() -> Result<(), BenchmarkError> { 36 | let call: ::RuntimeCall = frame_system::Call::remark { remark: vec![] }.into(); 37 | let origin = ::SuperMajorityOrigin::try_successful_origin() 38 | .map_err(|_| BenchmarkError::Stop("Origin should be present"))?; 39 | 40 | #[extrinsic_call] 41 | _(origin as T::RuntimeOrigin, Box::new(call)); 42 | 43 | assert_last_event::(Event::DispatchSuperMajority { motion_result: Ok(()) }.into()); 44 | Ok(()) 45 | } 46 | 47 | #[benchmark] 48 | fn unanimous() -> Result<(), BenchmarkError> { 49 | let call: ::RuntimeCall = frame_system::Call::remark { remark: vec![] }.into(); 50 | let origin = ::UnanimousOrigin::try_successful_origin() 51 | .map_err(|_| BenchmarkError::Stop("Origin should be present"))?; 52 | 53 | #[extrinsic_call] 54 | _(origin as T::RuntimeOrigin, Box::new(call)); 55 | 56 | assert_last_event::(Event::DispatchUnanimous { motion_result: Ok(()) }.into()); 57 | Ok(()) 58 | } 59 | 60 | impl_benchmark_test_suite!(Motion, crate::mock::new_test_ext(), crate::mock::Test); 61 | } 62 | -------------------------------------------------------------------------------- /pallets/motion/src/mock.rs: -------------------------------------------------------------------------------- 1 | use frame_support::{ 2 | derive_impl, parameter_types, 3 | traits::{ConstU128, ConstU16, ConstU64}, 4 | weights::Weight, 5 | }; 6 | use frame_system::{self as system, limits::BlockWeights}; 7 | use sp_runtime::{BuildStorage, Perbill}; 8 | 9 | use super::*; 10 | pub(crate) use crate as pallet_motion; 11 | 12 | type Block = frame_system::mocking::MockBlock; 13 | 14 | parameter_types! { 15 | pub RuntimeBlockWeights: BlockWeights = BlockWeights::default(); 16 | } 17 | 18 | // Configure a mock runtime to test the pallet. 19 | frame_support::construct_runtime!( 20 | pub struct Test { 21 | System: frame_system::{Pallet, Call, Event}, 22 | Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, 23 | Council: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config}, 24 | Motion: pallet_motion, 25 | } 26 | ); 27 | 28 | #[derive_impl(frame_system::config_preludes::TestDefaultConfig)] 29 | impl system::Config for Test { 30 | type AccountData = pallet_balances::AccountData; 31 | type Block = Block; 32 | type BlockHashCount = ConstU64<250>; 33 | type Nonce = u64; 34 | type PalletInfo = PalletInfo; 35 | type SS58Prefix = ConstU16<42>; 36 | } 37 | 38 | #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] 39 | impl pallet_balances::Config for Test { 40 | type AccountStore = System; 41 | type Balance = u128; 42 | type ExistentialDeposit = ConstU128<1>; 43 | type FreezeIdentifier = (); 44 | type MaxLocks = (); 45 | type MaxReserves = (); 46 | type ReserveIdentifier = [u8; 8]; 47 | type RuntimeFreezeReason = RuntimeFreezeReason; 48 | type RuntimeHoldReason = RuntimeHoldReason; 49 | } 50 | 51 | parameter_types! { 52 | pub CouncilMotionDuration: u64 = 7; 53 | pub const CouncilMaxProposals: u32 = 100; 54 | pub const CouncilMaxMembers: u32 = 100; 55 | pub MaxProposalWeight: Weight = Perbill::from_percent(50) * RuntimeBlockWeights::get().max_block; 56 | } 57 | 58 | pub type CouncilCollective = pallet_collective::Instance1; 59 | impl pallet_collective::Config for Test { 60 | type Consideration = (); 61 | type DefaultVote = pallet_collective::PrimeDefaultVote; 62 | type DisapproveOrigin = frame_system::EnsureRoot; 63 | type KillOrigin = frame_system::EnsureRoot; 64 | type MaxMembers = CouncilMaxMembers; 65 | type MaxProposalWeight = MaxProposalWeight; 66 | type MaxProposals = CouncilMaxProposals; 67 | type MotionDuration = CouncilMotionDuration; 68 | type Proposal = RuntimeCall; 69 | type RuntimeEvent = RuntimeEvent; 70 | type RuntimeOrigin = RuntimeOrigin; 71 | type SetMembersOrigin = frame_system::EnsureRoot; 72 | type WeightInfo = (); 73 | } 74 | 75 | impl pallet_motion::Config for Test { 76 | type RuntimeCall = RuntimeCall; 77 | type RuntimeEvent = RuntimeEvent; 78 | type SimpleMajorityOrigin = 79 | pallet_collective::EnsureProportionAtLeast; 80 | type SuperMajorityOrigin = 81 | pallet_collective::EnsureProportionAtLeast; 82 | type UnanimousOrigin = pallet_collective::EnsureProportionAtLeast; 83 | type WeightInfo = (); 84 | } 85 | 86 | // Build genesis storage according to the mock runtime. 87 | pub fn new_test_ext() -> sp_io::TestExternalities { 88 | let mut ext: sp_io::TestExternalities = RuntimeGenesisConfig { 89 | balances: pallet_balances::GenesisConfig:: { 90 | balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50)], 91 | ..Default::default() 92 | }, 93 | council: pallet_collective::GenesisConfig { 94 | members: vec![1, 2, 3, 4], 95 | phantom: Default::default(), 96 | }, 97 | } 98 | .build_storage() 99 | .unwrap() 100 | .into(); 101 | ext.execute_with(|| System::set_block_number(1)); 102 | ext 103 | } 104 | -------------------------------------------------------------------------------- /pallets/motion/src/weights.rs: -------------------------------------------------------------------------------- 1 | 2 | //! Autogenerated weights for pallet_motion 3 | //! 4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev 5 | //! DATE: 2023-07-24, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` 6 | //! WORST CASE MAP SIZE: `1000000` 7 | //! HOSTNAME: `PAR03043`, CPU: `` 8 | //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 9 | 10 | // Executed Command: 11 | // target/release/parachain-template-node 12 | // benchmark 13 | // pallet 14 | // --chain=dev 15 | // --execution=wasm 16 | // --wasm-execution=compiled 17 | // --pallet=pallet_motion 18 | // --extrinsic=* 19 | // --steps=50 20 | // --repeat=20 21 | // --json 22 | // --template 23 | // scripts/frame-weight-template.hbs 24 | // --output=./pallets/motion/src/weights.rs 25 | 26 | #![cfg_attr(rustfmt, rustfmt_skip)] 27 | #![allow(unused_parens)] 28 | #![allow(unused_imports)] 29 | #![allow(missing_docs)] 30 | 31 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 32 | use core::marker::PhantomData; 33 | 34 | /// Weight functions needed for pallet_motion. 35 | pub trait WeightInfo { 36 | fn simple_majority() -> Weight; 37 | fn super_majority() -> Weight; 38 | fn unanimous() -> Weight; 39 | } 40 | 41 | /// Weights for pallet_motion using the Substrate node and recommended hardware. 42 | pub struct SubstrateWeight(PhantomData); 43 | impl WeightInfo for SubstrateWeight { 44 | fn simple_majority() -> Weight { 45 | // Proof Size summary in bytes: 46 | // Measured: `0` 47 | // Estimated: `0` 48 | // Minimum execution time: 7_000_000 picoseconds. 49 | Weight::from_parts(8_000_000, 0) 50 | } 51 | fn super_majority() -> Weight { 52 | // Proof Size summary in bytes: 53 | // Measured: `0` 54 | // Estimated: `0` 55 | // Minimum execution time: 7_000_000 picoseconds. 56 | Weight::from_parts(8_000_000, 0) 57 | } 58 | fn unanimous() -> Weight { 59 | // Proof Size summary in bytes: 60 | // Measured: `0` 61 | // Estimated: `0` 62 | // Minimum execution time: 7_000_000 picoseconds. 63 | Weight::from_parts(8_000_000, 0) 64 | } 65 | } 66 | 67 | // For backwards compatibility and tests 68 | impl WeightInfo for () { 69 | fn simple_majority() -> Weight { 70 | // Proof Size summary in bytes: 71 | // Measured: `0` 72 | // Estimated: `0` 73 | // Minimum execution time: 7_000_000 picoseconds. 74 | Weight::from_parts(8_000_000, 0) 75 | } 76 | fn super_majority() -> Weight { 77 | // Proof Size summary in bytes: 78 | // Measured: `0` 79 | // Estimated: `0` 80 | // Minimum execution time: 7_000_000 picoseconds. 81 | Weight::from_parts(8_000_000, 0) 82 | } 83 | fn unanimous() -> Weight { 84 | // Proof Size summary in bytes: 85 | // Measured: `0` 86 | // Estimated: `0` 87 | // Minimum execution time: 7_000_000 picoseconds. 88 | Weight::from_parts(8_000_000, 0) 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /pallets/nfts/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = [ "Parity Technologies ", "R0GUE " ] 3 | description = "Fork of FRAME NFTs pallet" 4 | edition.workspace = true 5 | homepage = "https://substrate.io" 6 | license.workspace = true 7 | name = "pallet-nfts" 8 | readme = "README.md" 9 | repository.workspace = true 10 | version = "34.1.0" 11 | 12 | [package.metadata.docs.rs] 13 | targets = [ "x86_64-unknown-linux-gnu" ] 14 | 15 | [dependencies] 16 | codec = { workspace = true } 17 | enumflags2 = { workspace = true } 18 | log = { workspace = true } 19 | scale-info = { features = [ "derive" ], workspace = true } 20 | 21 | # Substrate 22 | frame-benchmarking = { optional = true, workspace = true } 23 | frame-support.workspace = true 24 | frame-system.workspace = true 25 | sp-core.workspace = true 26 | sp-io.workspace = true 27 | sp-runtime.workspace = true 28 | 29 | [dev-dependencies] 30 | pallet-balances.workspace = true 31 | sp-keystore.workspace = true 32 | 33 | [features] 34 | default = [ "std" ] 35 | runtime-benchmarks = [ 36 | "frame-benchmarking/runtime-benchmarks", 37 | "frame-support/runtime-benchmarks", 38 | "frame-system/runtime-benchmarks", 39 | "sp-runtime/runtime-benchmarks", 40 | ] 41 | std = [ 42 | "codec/std", 43 | "enumflags2/std", 44 | "frame-benchmarking?/std", 45 | "frame-support/std", 46 | "frame-system/std", 47 | "log/std", 48 | "pallet-balances/std", 49 | "scale-info/std", 50 | "sp-core/std", 51 | "sp-io/std", 52 | "sp-keystore/std", 53 | "sp-runtime/std", 54 | ] 55 | try-runtime = [ 56 | "frame-support/try-runtime", 57 | "frame-system/try-runtime", 58 | "sp-runtime/try-runtime", 59 | ] 60 | -------------------------------------------------------------------------------- /pallets/nfts/runtime-api/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = [ "Parity Technologies ", "R0GUE " ] 3 | description = "Runtime API for the FRAME NFTs pallet." 4 | edition.workspace = true 5 | homepage = "https://substrate.io" 6 | license = "Apache-2.0" 7 | name = "pallet-nfts-runtime-api" 8 | readme = "README.md" 9 | repository.workspace = true 10 | version = "23.0.0" 11 | 12 | [package.metadata.docs.rs] 13 | targets = [ "x86_64-unknown-linux-gnu" ] 14 | 15 | [dependencies] 16 | codec = { features = [ "derive" ], workspace = true } 17 | sp-api.workspace = true 18 | 19 | [features] 20 | default = [ "std" ] 21 | std = [ "codec/std", "sp-api/std" ] 22 | -------------------------------------------------------------------------------- /pallets/nfts/runtime-api/README.md: -------------------------------------------------------------------------------- 1 | RPC runtime API for the FRAME NFTs pallet. 2 | 3 | License: Apache-2.0 4 | -------------------------------------------------------------------------------- /pallets/nfts/runtime-api/src/lib.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | //! Runtime API definition for the FRAME NFTs pallet. 19 | 20 | #![cfg_attr(not(feature = "std"), no_std)] 21 | 22 | extern crate alloc; 23 | 24 | use alloc::vec::Vec; 25 | 26 | use codec::{Decode, Encode}; 27 | 28 | sp_api::decl_runtime_apis! { 29 | pub trait NftsApi 30 | where 31 | AccountId: Encode + Decode, 32 | CollectionId: Encode, 33 | ItemId: Encode, 34 | { 35 | fn owner(collection: CollectionId, item: ItemId) -> Option; 36 | 37 | fn collection_owner(collection: CollectionId) -> Option; 38 | 39 | fn attribute( 40 | collection: CollectionId, 41 | item: ItemId, 42 | key: Vec, 43 | ) -> Option>; 44 | 45 | fn custom_attribute( 46 | account: AccountId, 47 | collection: CollectionId, 48 | item: ItemId, 49 | key: Vec, 50 | ) -> Option>; 51 | 52 | fn system_attribute( 53 | collection: CollectionId, 54 | item: Option, 55 | key: Vec, 56 | ) -> Option>; 57 | 58 | fn collection_attribute(collection: CollectionId, key: Vec) -> Option>; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /pallets/nfts/src/features/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | pub mod approvals; 19 | pub mod atomic_swap; 20 | pub mod attributes; 21 | pub mod buy_sell; 22 | pub mod create_delete_collection; 23 | pub mod create_delete_item; 24 | pub mod lock; 25 | pub mod metadata; 26 | pub mod roles; 27 | pub mod settings; 28 | pub mod transfer; 29 | -------------------------------------------------------------------------------- /pallets/nfts/src/macros.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | /// Implements encoding and decoding traits for a wrapper type that represents 19 | /// bitflags. The wrapper type should contain a field of type `$size`, where 20 | /// `$size` is an integer type (e.g., u8, u16, u32) that can represent the bitflags. 21 | /// The `$bitflag_enum` type is the enumeration type that defines the individual bitflags. 22 | /// 23 | /// This macro provides implementations for the following traits: 24 | /// - `MaxEncodedLen`: Calculates the maximum encoded length for the wrapper type. 25 | /// - `Encode`: Encodes the wrapper type using the provided encoding function. 26 | /// - `EncodeLike`: Trait indicating the type can be encoded as is. 27 | /// - `Decode`: Decodes the wrapper type from the input. 28 | /// - `TypeInfo`: Provides type information for the wrapper type. 29 | macro_rules! impl_codec_bitflags { 30 | ($wrapper:ty, $size:ty, $bitflag_enum:ty) => { 31 | impl MaxEncodedLen for $wrapper { 32 | fn max_encoded_len() -> usize { 33 | <$size>::max_encoded_len() 34 | } 35 | } 36 | impl Encode for $wrapper { 37 | fn using_encoded R>(&self, f: F) -> R { 38 | self.0.bits().using_encoded(f) 39 | } 40 | } 41 | impl EncodeLike for $wrapper {} 42 | impl Decode for $wrapper { 43 | fn decode( 44 | input: &mut I, 45 | ) -> ::core::result::Result { 46 | let field = <$size>::decode(input)?; 47 | Ok(Self(BitFlags::from_bits(field as $size).map_err(|_| "invalid value")?)) 48 | } 49 | } 50 | 51 | impl TypeInfo for $wrapper { 52 | type Identity = Self; 53 | 54 | fn type_info() -> Type { 55 | Type::builder() 56 | .path(Path::new("BitFlags", module_path!())) 57 | .type_params(vec![TypeParameter::new("T", Some(meta_type::<$bitflag_enum>()))]) 58 | .composite( 59 | Fields::unnamed() 60 | .field(|f| f.ty::<$size>().type_name(stringify!($bitflag_enum))), 61 | ) 62 | } 63 | } 64 | }; 65 | } 66 | pub(crate) use impl_codec_bitflags; 67 | -------------------------------------------------------------------------------- /pallets/nfts/src/mock.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | //! Test environment for Nfts pallet. 19 | 20 | use frame_support::{ 21 | construct_runtime, derive_impl, parameter_types, 22 | traits::{AsEnsureOriginWithArg, ConstU32, ConstU64}, 23 | }; 24 | use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; 25 | use sp_runtime::{ 26 | traits::{IdentifyAccount, IdentityLookup, Verify}, 27 | BuildStorage, MultiSignature, 28 | }; 29 | 30 | use super::*; 31 | use crate as pallet_nfts; 32 | 33 | type Block = frame_system::mocking::MockBlock; 34 | 35 | construct_runtime!( 36 | pub enum Test 37 | { 38 | System: frame_system, 39 | Balances: pallet_balances, 40 | Nfts: pallet_nfts, 41 | } 42 | ); 43 | 44 | pub type Signature = MultiSignature; 45 | pub type AccountPublic = ::Signer; 46 | pub type AccountId = ::AccountId; 47 | 48 | #[derive_impl(frame_system::config_preludes::TestDefaultConfig)] 49 | impl frame_system::Config for Test { 50 | type AccountData = pallet_balances::AccountData; 51 | type AccountId = AccountId; 52 | type Block = Block; 53 | type Lookup = IdentityLookup; 54 | } 55 | 56 | #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] 57 | impl pallet_balances::Config for Test { 58 | type AccountStore = System; 59 | } 60 | 61 | parameter_types! { 62 | pub storage Features: PalletFeatures = PalletFeatures::all_enabled(); 63 | } 64 | 65 | impl Config for Test { 66 | type ApprovalsLimit = ConstU32<10>; 67 | type AttributeDepositBase = ConstU64<1>; 68 | type BlockNumberProvider = frame_system::Pallet; 69 | type CollectionApprovalDeposit = ConstU64<1>; 70 | type CollectionBalanceDeposit = ConstU64<1>; 71 | type CollectionDeposit = ConstU64<2>; 72 | type CollectionId = u32; 73 | type CreateOrigin = AsEnsureOriginWithArg>; 74 | type Currency = Balances; 75 | type DepositPerByte = ConstU64<1>; 76 | type Features = Features; 77 | type ForceOrigin = frame_system::EnsureRoot; 78 | #[cfg(feature = "runtime-benchmarks")] 79 | type Helper = (); 80 | type ItemAttributesApprovalsLimit = ConstU32<2>; 81 | type ItemDeposit = ConstU64<1>; 82 | type ItemId = u32; 83 | type KeyLimit = ConstU32<50>; 84 | type Locker = (); 85 | type MaxAttributesPerCall = ConstU32<2>; 86 | type MaxDeadlineDuration = ConstU64<10000>; 87 | type MaxTips = ConstU32<10>; 88 | type MetadataDepositBase = ConstU64<1>; 89 | /// Using `AccountPublic` here makes it trivial to convert to `AccountId` via `into_account()`. 90 | type OffchainPublic = AccountPublic; 91 | /// Off-chain = signature On-chain - therefore no conversion needed. 92 | /// It needs to be From for benchmarking. 93 | type OffchainSignature = Signature; 94 | type RuntimeEvent = RuntimeEvent; 95 | type StringLimit = ConstU32<50>; 96 | type ValueLimit = ConstU32<50>; 97 | type WeightInfo = (); 98 | } 99 | 100 | pub(crate) fn new_test_ext() -> sp_io::TestExternalities { 101 | let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); 102 | 103 | let mut ext = sp_io::TestExternalities::new(t); 104 | ext.register_extension(KeystoreExt::new(MemoryKeystore::new())); 105 | ext.execute_with(|| System::set_block_number(1)); 106 | ext 107 | } 108 | -------------------------------------------------------------------------------- /pop-api/.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | # Generated by Cargo 3 | # will have compiled files and executables 4 | debug/ 5 | target/ 6 | 7 | # These are backup files generated by rustfmt 8 | **/*.rs.bk 9 | 10 | # MSVC Windows builds of rustc generate these, which store debugging information 11 | *.pdb 12 | -------------------------------------------------------------------------------- /pop-api/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | description = "Enabling smart(er) contracts with the power of Polkadot" 3 | edition = "2021" 4 | license = "GPL-3.0-only" 5 | name = "pop-api" 6 | version = "0.0.0" 7 | 8 | [dependencies] 9 | bitflags = { version = "2.8.0", optional = true } 10 | enumflags2 = { version = "0.7.9", optional = true } 11 | 12 | # Pop. 13 | pop-primitives = { path = "../primitives", default-features = false } 14 | 15 | # Substrate. 16 | sp-io = { version = "40.0.0", default-features = false, features = [ 17 | "disable_allocator", 18 | "disable_oom", 19 | "disable_panic_handler", 20 | ] } 21 | 22 | # ink! dependencies. 23 | ink = { version = "5.1.0", default-features = false } 24 | 25 | [dev-dependencies] 26 | pallet-nfts = { path = "../pallets/nfts" } 27 | scale = { package = "parity-scale-codec", version = "3" } 28 | 29 | [lib] 30 | crate-type = [ "rlib" ] 31 | name = "pop_api" 32 | path = "src/lib.rs" 33 | 34 | [features] 35 | default = [ "std" ] 36 | fungibles = [ ] 37 | messaging = [ ] 38 | nonfungibles = [ "dep:bitflags", "dep:enumflags2" ] 39 | std = [ 40 | "ink/std", 41 | "pop-primitives/std", 42 | "sp-io/std", 43 | ] 44 | -------------------------------------------------------------------------------- /pop-api/README.md: -------------------------------------------------------------------------------- 1 | ## Pop API 2 | 3 | The `pop-api` crate provides a high-level interface that allows smart contracts to seamlessly interact with Pop, a 4 | blockchain built to power innovative and impactful solutions on Polkadot. Designed for stability, simplicity, and 5 | efficiency, the API abstracts away the complexities of the runtime, enabling developers to focus on building powerful 6 | applications rather than managing intricate blockchain details. 7 | 8 | ### Design Goals 9 | 10 | - **Simple**: enhance the developer experience by abstracting away the complexities of runtime functionality, making it 11 | easy for developers to build advanced applications. 12 | - **Versioned**: offer a stable, versioned interface that ensures smart contracts stay compatible as the runtime 13 | evolves, enabling seamless integration of new features without disrupting existing contracts. 14 | - **Efficient**: optimise for minimal contract size, having the lowest possible deployment and execution costs. 15 | 16 | ### Key Features 17 | 18 | - **Versioned Interface**: Provides backward compatibility, ensuring that existing contract functionality remains stable 19 | as new features are added to the runtime. 20 | - **Error Handling**: Supports rich, versioned error types, enabling contracts to receive and interpret any runtime 21 | error, making troubleshooting and development easier. 22 | - **Use Cases**: 23 | - [Fungibles](./src/v0/fungibles/README.md): Interacting and managing fungible tokens. 24 | - In development: 25 | - Non Fungibles: Interacting and managing non fungible tokens. 26 | - Messaging: Cross chain rails for interaction with other chains using ISMP & XCM. 27 | - Sponsorship: Allowing smart contracts to sponsor transactions. 28 | - Incentives: Incentivise smart contracts by sharing chain revenue. 29 | 30 | ### Getting Started 31 | 32 | Using the API in your ink! smart contract is as easy as adding the `pop-api` crate in your `Cargo.toml`: 33 | 34 | ```toml 35 | pop-api = { git = "https://github.com/r0gue-io/pop-node", default-features = false } 36 | ``` 37 | 38 | and importing it within the contract source: 39 | 40 | ```rust 41 | use pop_api::*; 42 | ``` 43 | 44 | Check out the ink! smart contract [examples](./example) using the API. 45 | 46 | ### Learn more 47 | 48 | The true strength of the API lies in the Pop runtime, where a single, unified chain extension provides flexible and 49 | efficient access to all runtime features, while specialized API modules deliver stable, intuitive interfaces for 50 | developers. Together, these elements make the API a powerful tool for creating decentralized applications on Polkadot. 51 | 52 | Want to explore how it all works? Check out: 53 | 54 | - [Chain Extension Implementation](../extension) 55 | - [API Modules](../pallets/api) 56 | 57 | ### Support 58 | 59 | Be part of our passionate community of Web3 builders. [Join our Telegram](https://t.me/onpopio)! 60 | 61 | Feel free to raise issues if anything is unclear, if you have ideas or want to contribute to Pop! 62 | 63 | For any questions related to ink! you can also go to [Polkadot Stack Exchange](https://polkadot.stackexchange.com/) or 64 | ask the [ink! community](https://t.me/inkathon/). 65 | -------------------------------------------------------------------------------- /pop-api/examples/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore build artifacts from the local tests sub-crate. 2 | **/target/ 3 | 4 | # Ignore backup files creates by cargo fmt. 5 | **/*.rs.bk 6 | 7 | # Remove Cargo.lock when creating an executable, leave it for libraries 8 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 9 | **/Cargo.lock 10 | -------------------------------------------------------------------------------- /pop-api/examples/README.md: -------------------------------------------------------------------------------- 1 | ## Pop API Examples 2 | 3 | The example contracts demonstrate how to use the `pop_api` interface with [ink!](https://use.ink). 4 | 5 | ## Warning 6 | 7 | The available contracts are *examples* demonstrating usage of Pop's smart contract API. They are neither audited nor 8 | endorsed for production use. Do **not** rely on them to keep anything of value secure. 9 | 10 | ## Development 11 | 12 | ### Prerequisite 13 | 14 | [Pop CLI](https://github.com/r0gue-io/pop-cli) installed. 15 | 16 | ### Launching a local Pop Network 17 | 18 | The example contracts only work with Pop Network runtimes due to their usage of Pop's smart contract API. To run 19 | `pop-node` locally, you can use the following command: 20 | 21 | ```bash 22 | pop up network -f ./networks/devnet.toml 23 | ``` 24 | 25 | The output should provide a command for following the logs emitted from `pop-node`, which can be useful for debugging: 26 | 27 | ``` 28 | logs: tail -f /var/folders/mr/gvb9gkhx58x2mxbpc6dw77ph0000gn/T/zombie-d9983e5b-fc70-478d-b943-d920a659d308/pop/pop.log 29 | ``` 30 | 31 | > 📚 See the full guide to launching a chain 32 | > locally [here](https://learn.onpop.io/appchains/guides/launch-a-chain/running-your-parachain). 33 | 34 | ### Build a contract 35 | 36 | Run the below command to build the contract: 37 | 38 | ```bash 39 | pop build -r 40 | ``` 41 | 42 | This builds the contract in release mode. 43 | 44 | ### Upload and instantiate a contract 45 | 46 | Upload your contract to the local instance of Pop Network you launched above with the following command, replacing the 47 | url with that shown in the output of the `pop up network` command. 48 | 49 | ```bash 50 | pop up contract \ 51 | --url=ws://127.0.0.1:9944 \ 52 | # The value provided at instantiation (via `payable`). 53 | --value 100000000000 \ 54 | # Using Alice as the contract owner, you can provide `--use-wallet` to sign with your own wallet. 55 | --suri //Alice \ 56 | # Provide the constructor args 57 | --args ... 58 | ``` 59 | 60 | ## Support 61 | 62 | Be part of our passionate community of Web3 builders. [Join our Telegram](https://t.me/onpopio)! 63 | 64 | Feel free to raise issues if anything is unclear, you have ideas or want to contribute to Pop! Examples using the 65 | API are always welcome! 66 | 67 | For any questions related to ink! you can also go to [Polkadot Stack Exchange](https://polkadot.stackexchange.com/) or 68 | ask the [ink! community](https://t.me/inkathon/1). 69 | 70 | - [Learn more about ink! smart contract language](https://use.ink). 71 | - Learn more about [Pop API](https://github.com/r0gue-io/pop-node/tree/main/pop-api/). 72 | -------------------------------------------------------------------------------- /pop-api/examples/fungibles/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = [ "R0GUE " ] 3 | edition = "2021" 4 | name = "fungibles" 5 | version = "0.1.0" 6 | 7 | [dependencies] 8 | ink = { version = "5.1.0", default-features = false, features = [ "ink-debug" ] } 9 | pop-api = { path = "../../../pop-api", default-features = false, features = [ 10 | "fungibles", 11 | ] } 12 | 13 | [dev-dependencies] 14 | drink = { package = "pop-drink", git = "https://github.com/r0gue-io/pop-drink", tag = "stable-2503-4", features = [ "devnet" ] } 15 | env_logger = { version = "0.11.3" } 16 | serde_json = "1.0.114" 17 | 18 | [lib] 19 | path = "lib.rs" 20 | 21 | [features] 22 | default = [ "std" ] 23 | e2e-tests = [ ] 24 | ink-as-dependency = [ ] 25 | std = [ 26 | "ink/std", 27 | "pop-api/std", 28 | ] 29 | -------------------------------------------------------------------------------- /pop-api/examples/fungibles/README.md: -------------------------------------------------------------------------------- 1 | # PSP22 Fungible Token with Pop API 2 | 3 | This [ink!][ink] contract implements a [PSP22-compliant][psp22] fungible token by leveraging the [Pop API Fungibles][pop-api-fungibles]. Unlike typical token contracts, where the contract itself manages the token, tokens created by this contract are managed directly by Pop. This enables seamless integration and interoperability of the token across the Polkadot ecosystem and its applications. 4 | 5 | As the creator of the token, the contract has permissions to mint and burn tokens, but it can only transfer and approve tokens on its own behalf and requires explicit approval to transfer tokens for other accounts. Instead of users interacting with the contract to handle their token approvals, they interact primarily with Pop’s runtime. 6 | 7 | ## Key benefits of using the Pop API 8 | 9 | - The token operates live on the Pop Network, beyond just within the contract. 10 | - Simplify token management with high-level interfaces to significantly reduce contract size and complexity. 11 | 12 | [Learn more how Pop API works.](pop-api) 13 | 14 | ## Use Cases 15 | 16 | This contract can serve a variety of purposes where owner-controlled token management is essential. Example use cases include: 17 | - **DAO Token**: A DAO can use this contract to manage a governance token, with the DAO overseeing token issuance and removal based on governance decisions. 18 | - **Staking and Rewards**: This contract supports minting tokens specifically for reward distribution. 19 | - **Loyalty Programs**: Businesses or platforms can use this contract to issue loyalty points, with the owner managing token balances for users based on participation or purchases. 20 | 21 | ## Test with Pop Drink 22 | 23 | Since this contract interacts directly with Pop’s runtime through the Pop API, it requires [Pop Drink](https://github.com/r0gue-io/pop-drink) for testing. See how the contract is tested in [tests](./tests.rs). 24 | 25 | ## Potential Improvements 26 | 27 | - **Multiple owner management**: Instead of restricting ownership to a single `owner`, the contract could be designed to accommodate multiple owners. 28 | 29 | ## Support 30 | 31 | Be part of our passionate community of Web3 builders. [Join our Telegram](https://t.me/onpopio)! 32 | 33 | Feel free to raise issues if anything is unclear, you have ideas or want to contribute to Pop! Examples using the fungibles API are always welcome! 34 | 35 | For any questions related to ink! you can also go to [Polkadot Stack Exchange](https://polkadot.stackexchange.com/) or 36 | ask the [ink! community](https://t.me/inkathon/1). 37 | 38 | [ink]: https://use.ink 39 | [psp22]: https://github.com/inkdevhub/standards/blob/master/PSPs/psp-22.md 40 | [pop-api]: https://github.com/r0gue-io/pop-node/tree/main/pop-api/ 41 | [pop-api-fungibles]: https://github.com/r0gue-io/pop-node/tree/main/pop-api/src/v0/fungibles 42 | [pop-drink]: https://github.com/r0gue-io/pop-drink 43 | -------------------------------------------------------------------------------- /pop-api/examples/messaging/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = [ "R0GUE " ] 3 | edition = "2021" 4 | name = "messaging" 5 | version = "0.1.0" 6 | 7 | [dependencies] 8 | ink = { version = "5.1.0", default-features = false } 9 | pop-api = { path = "../../../pop-api", default-features = false, features = [ "messaging" ] } 10 | 11 | [lib] 12 | path = "lib.rs" 13 | 14 | [features] 15 | default = [ "std" ] 16 | e2e-tests = [ ] 17 | ink-as-dependency = [ ] 18 | std = [ 19 | "ink/std", 20 | "pop-api/std", 21 | ] 22 | -------------------------------------------------------------------------------- /pop-api/examples/nonfungibles/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = [ "R0GUE " ] 3 | edition = "2021" 4 | name = "nonfungibles" 5 | version = "0.1.0" 6 | 7 | [dependencies] 8 | ink = { version = "5.1.0", default-features = false } 9 | pop-api = { path = "../../../pop-api", default-features = false, features = [ 10 | "nonfungibles", 11 | ] } 12 | 13 | [lib] 14 | path = "lib.rs" 15 | 16 | [features] 17 | default = [ "std" ] 18 | e2e-tests = [ ] 19 | ink-as-dependency = [ ] 20 | std = [ 21 | "ink/std", 22 | "pop-api/std", 23 | ] 24 | -------------------------------------------------------------------------------- /pop-api/examples/nonfungibles/README.md: -------------------------------------------------------------------------------- 1 | # Non-Fungibles Contract Example 2 | 3 | This smart contract demonstrates how to manage NFTs using the [ 4 | `pop_api::nonfungibles`](../../src/v0/nonfungibles) interface with [ink!](https://use.ink). 5 | 6 | ### Upload and instantiate a contract 7 | 8 | See [examples](../README.md#development) for instructions on getting started and then upload your contract with the 9 | following command. 10 | 11 | ```bash 12 | pop up contract \ 13 | --url=ws://127.0.0.1:9944 \ 14 | # The value provided at instantiation (via `payable`) to reserve the deposit for the collection. 15 | --value 100000000000 \ 16 | # Using Alice as the contract owner, you can provide `--use-wallet` to sign with your own wallet. 17 | --suri //Alice \ 18 | # Provide the max supply 19 | --args 1000 20 | ``` 21 | 22 | ## Support 23 | 24 | Be part of our passionate community of Web3 builders. [Join our Telegram](https://t.me/onpopio)! 25 | 26 | Feel free to raise issues if anything is unclear, you have ideas or want to contribute to Pop! Examples using the 27 | non-fungibles API are always welcome! 28 | 29 | For any questions related to ink! you can also go to [Polkadot Stack Exchange](https://polkadot.stackexchange.com/) or 30 | ask the [ink! community](https://t.me/inkathon/1). 31 | 32 | [ink]: https://use.ink 33 | 34 | [psp34]: https://github.com/inkdevhub/standards/blob/master/PSPs/psp-34.md 35 | 36 | [pop-api]: https://github.com/r0gue-io/pop-node/tree/main/pop-api/ 37 | 38 | [pop-api-nonfungibles]: https://github.com/r0gue-io/pop-node/tree/main/pop-api/src/v0/nonfungibles 39 | 40 | [pop-drink]: https://github.com/r0gue-io/pop-drink -------------------------------------------------------------------------------- /pop-api/integration-tests/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | build = "build.rs" 3 | edition = "2021" 4 | name = "pop-api-integration-tests" 5 | version = "0.1.0" 6 | 7 | [build-dependencies] 8 | contract-build.workspace = true 9 | 10 | [dev-dependencies] 11 | codec.workspace = true 12 | env_logger.workspace = true 13 | frame-support = { workspace = true, default-features = false } 14 | frame-system = { workspace = true, default-features = false } 15 | ismp = { workspace = true, default-features = false } 16 | log.workspace = true 17 | pallet-api = { workspace = true, default-features = false } 18 | pallet-assets = { workspace = true, default-features = false } 19 | pallet-balances = { workspace = true, default-features = false } 20 | pallet-contracts = { workspace = true, default-features = false } 21 | pallet-ismp = { workspace = true, default-features = false } 22 | pallet-nfts = { workspace = true, default-features = false } 23 | pallet-xcm = { workspace = true, default-features = false } 24 | pop-api = { path = "../../pop-api", default-features = false, features = [ 25 | "fungibles", 26 | "messaging", 27 | "nonfungibles", 28 | ] } 29 | pop-primitives = { workspace = true, default-features = false } 30 | pop-runtime-devnet.workspace = true 31 | pop-runtime-testnet.workspace = true 32 | sp-io = { workspace = true, default-features = false } 33 | sp-runtime = { workspace = true, default-features = false } 34 | xcm.workspace = true 35 | xcm-executor.workspace = true 36 | 37 | [features] 38 | default = [ "std" ] 39 | devnet = [ "pop-runtime-devnet/default" ] 40 | std = [ 41 | "codec/std", 42 | "frame-support/std", 43 | "frame-system/std", 44 | "pallet-api/std", 45 | "pallet-assets/std", 46 | "pallet-balances/std", 47 | "pallet-contracts/std", 48 | "pallet-nfts/std", 49 | "pop-api/std", 50 | "pop-primitives/std", 51 | "pop-runtime-devnet/std", 52 | "pop-runtime-testnet/std", 53 | "sp-io/std", 54 | "sp-runtime/std", 55 | ] 56 | testnet = [ "pop-runtime-testnet/default" ] 57 | -------------------------------------------------------------------------------- /pop-api/integration-tests/build.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fs, 3 | path::{Path, PathBuf}, 4 | process, 5 | }; 6 | 7 | use contract_build::{ 8 | execute, BuildArtifacts, BuildMode, BuildResult, ExecuteArgs, ManifestPath, OutputType, 9 | Verbosity, 10 | }; 11 | 12 | fn main() { 13 | let contracts_dir = PathBuf::from("./contracts/"); 14 | let contract_dirs = match get_subcontract_directories(&contracts_dir) { 15 | Ok(dirs) => dirs, 16 | Err(e) => { 17 | eprintln!("Failed to read contracts directory: {}", e); 18 | process::exit(1); 19 | }, 20 | }; 21 | 22 | for contract in contract_dirs { 23 | if let Err(e) = build_contract(&contract) { 24 | eprintln!("Failed to build contract {}: {}", contract.display(), e); 25 | process::exit(1); 26 | } 27 | } 28 | } 29 | 30 | // Function to retrieve all subdirectories in a given directory. 31 | fn get_subcontract_directories(contracts_dir: &Path) -> Result, String> { 32 | fs::read_dir(contracts_dir) 33 | .map_err(|e| format!("Could not read directory '{}': {}", contracts_dir.display(), e))? 34 | .filter_map(|entry| match entry { 35 | Ok(entry) if entry.path().is_dir() => Some(Ok(entry.path())), 36 | Ok(_) => None, 37 | Err(e) => Some(Err(format!("Error reading directory entry: {}", e))), 38 | }) 39 | .collect() 40 | } 41 | 42 | // Function to build a contract given its directory. 43 | fn build_contract(contract_dir: &Path) -> Result { 44 | let manifest_path = ManifestPath::new(contract_dir.join("Cargo.toml")).map_err(|e| { 45 | format!("Could not retrieve manifest path for {}: {}", contract_dir.display(), e) 46 | })?; 47 | 48 | let args = ExecuteArgs { 49 | build_artifact: BuildArtifacts::CodeOnly, 50 | build_mode: BuildMode::Debug, 51 | manifest_path, 52 | output_type: OutputType::HumanReadable, 53 | verbosity: Verbosity::Default, 54 | ..Default::default() 55 | }; 56 | 57 | execute(args).map_err(|e| format!("Build failed for {}: {}", contract_dir.display(), e)) 58 | } 59 | -------------------------------------------------------------------------------- /pop-api/integration-tests/contracts/create_token_in_constructor/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = [ "R0GUE " ] 3 | edition = "2021" 4 | name = "create_token_in_constructor" 5 | version = "0.1.0" 6 | 7 | [workspace] 8 | 9 | [dependencies] 10 | ink = { version = "5.1.0", default-features = false } 11 | pop-api = { path = "../../..", default-features = false, features = [ "fungibles" ] } 12 | 13 | [lib] 14 | path = "lib.rs" 15 | 16 | [features] 17 | default = [ "std" ] 18 | e2e-tests = [ ] 19 | ink-as-dependency = [ ] 20 | std = [ 21 | "ink/std", 22 | "pop-api/std", 23 | ] 24 | -------------------------------------------------------------------------------- /pop-api/integration-tests/contracts/create_token_in_constructor/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(feature = "std"), no_std, no_main)] 2 | 3 | use pop_api::{ 4 | fungibles::{self as api, events::Created}, 5 | primitives::TokenId, 6 | StatusCode, 7 | }; 8 | 9 | pub type Result = core::result::Result; 10 | 11 | #[ink::contract] 12 | mod create_token_in_constructor { 13 | use super::*; 14 | 15 | #[ink(storage)] 16 | pub struct Fungible { 17 | token: TokenId, 18 | } 19 | 20 | impl Fungible { 21 | #[ink(constructor, payable)] 22 | pub fn new(id: TokenId, min_balance: Balance) -> Result { 23 | let contract = Self { token: id }; 24 | // AccountId of the contract which will be set to the owner of the fungible token. 25 | let owner = contract.env().account_id(); 26 | api::create(id, owner, min_balance)?; 27 | contract.env().emit_event(Created { id, creator: owner, admin: owner }); 28 | Ok(contract) 29 | } 30 | 31 | #[ink(message)] 32 | pub fn token_exists(&self) -> Result { 33 | api::token_exists(self.token) 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /pop-api/integration-tests/contracts/fungibles/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = [ "R0GUE " ] 3 | edition = "2021" 4 | name = "fungibles" 5 | version = "0.1.0" 6 | 7 | [workspace] 8 | 9 | [dependencies] 10 | ink = { version = "5.1.0", default-features = false } 11 | pop-api = { path = "../../../../pop-api", default-features = false, features = [ "fungibles" ] } 12 | 13 | [lib] 14 | path = "lib.rs" 15 | 16 | [features] 17 | default = [ "std" ] 18 | e2e-tests = [ ] 19 | ink-as-dependency = [ ] 20 | std = [ 21 | "ink/std", 22 | "pop-api/std", 23 | ] 24 | -------------------------------------------------------------------------------- /pop-api/integration-tests/contracts/messaging/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = [ "R0GUE " ] 3 | edition = "2021" 4 | name = "messaging" 5 | version = "0.1.0" 6 | 7 | [workspace] 8 | 9 | [dependencies] 10 | ink = { version = "5.1.0", default-features = false } 11 | pop-api = { path = "../../../../pop-api", default-features = false, features = [ "messaging" ] } 12 | 13 | [lib] 14 | path = "lib.rs" 15 | 16 | [features] 17 | default = [ "std" ] 18 | e2e-tests = [ ] 19 | ink-as-dependency = [ ] 20 | std = [ 21 | "ink/std", 22 | "pop-api/std", 23 | ] 24 | -------------------------------------------------------------------------------- /pop-api/integration-tests/contracts/nonfungibles/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = [ "R0GUE " ] 3 | edition = "2021" 4 | name = "nonfungibles" 5 | version = "0.1.0" 6 | 7 | [workspace] 8 | 9 | [dependencies] 10 | ink = { version = "5.1.0", default-features = false } 11 | pop-api = { path = "../../../../pop-api", default-features = false, features = [ "nonfungibles" ] } 12 | 13 | [lib] 14 | path = "lib.rs" 15 | 16 | [features] 17 | default = [ "std" ] 18 | std = [ 19 | "ink/std", 20 | "pop-api/std", 21 | ] 22 | -------------------------------------------------------------------------------- /pop-api/integration-tests/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg(test)] 2 | 3 | use frame_support::{ 4 | assert_ok, 5 | pallet_prelude::{Decode, Encode}, 6 | traits::fungibles::{ 7 | approvals::Inspect as _, metadata::Inspect as _, roles::Inspect as _, Inspect, 8 | }, 9 | weights::Weight, 10 | }; 11 | use pallet_contracts::{Code, CollectEvents, Determinism, ExecReturnValue}; 12 | #[cfg(feature = "devnet")] 13 | use pop_runtime_devnet::{Assets, Contracts, Nfts, Runtime, RuntimeOrigin, System, UNIT}; 14 | #[cfg(feature = "testnet")] 15 | use pop_runtime_testnet::{Assets, Contracts, Nfts, Runtime, RuntimeOrigin, System, UNIT}; 16 | use sp_runtime::{AccountId32, BuildStorage, DispatchError}; 17 | use utils::*; 18 | 19 | mod fungibles; 20 | #[cfg(feature = "testnet")] 21 | mod messaging; 22 | #[cfg(feature = "devnet")] 23 | mod nonfungibles; 24 | mod utils; 25 | 26 | type Balance = u128; 27 | 28 | const ALICE: AccountId32 = AccountId32::new([1_u8; 32]); 29 | const BOB: AccountId32 = AccountId32::new([2_u8; 32]); 30 | const DEBUG_OUTPUT: pallet_contracts::DebugInfo = pallet_contracts::DebugInfo::UnsafeDebug; 31 | const FERDIE: AccountId32 = AccountId32::new([3_u8; 32]); 32 | const GAS_LIMIT: Weight = Weight::from_parts(500_000_000_000, 3 * 1024 * 1024); 33 | const INIT_AMOUNT: Balance = 100_000_000 * UNIT; 34 | const INIT_VALUE: Balance = 100 * UNIT; 35 | 36 | fn new_test_ext() -> sp_io::TestExternalities { 37 | let _ = env_logger::try_init(); 38 | 39 | let mut t = frame_system::GenesisConfig::::default() 40 | .build_storage() 41 | .expect("Frame system builds valid default genesis config"); 42 | 43 | pallet_balances::GenesisConfig:: { 44 | // FERDIE has no initial balance. 45 | balances: vec![(ALICE, INIT_AMOUNT), (BOB, INIT_AMOUNT)], 46 | ..Default::default() 47 | } 48 | .assimilate_storage(&mut t) 49 | .expect("Pallet balances storage can be assimilated"); 50 | 51 | let mut ext = sp_io::TestExternalities::new(t); 52 | ext.execute_with(|| System::set_block_number(1)); 53 | ext 54 | } 55 | 56 | fn function_selector(name: &str) -> Vec { 57 | let hash = sp_io::hashing::blake2_256(name.as_bytes()); 58 | [hash[0..4].to_vec()].concat() 59 | } 60 | 61 | fn bare_call( 62 | addr: AccountId32, 63 | input: Vec, 64 | value: u128, 65 | ) -> Result { 66 | let result = Contracts::bare_call( 67 | ALICE, 68 | addr.into(), 69 | value.into(), 70 | GAS_LIMIT, 71 | None, 72 | input, 73 | DEBUG_OUTPUT, 74 | CollectEvents::Skip, 75 | Determinism::Enforced, 76 | ); 77 | log::info!("contract exec result={result:?}"); 78 | result.result 79 | } 80 | 81 | // Deploy, instantiate and return contract address. 82 | fn instantiate(contract: &str, init_value: u128, salt: Vec) -> AccountId32 { 83 | let wasm_binary = std::fs::read(contract).expect("could not read .wasm file"); 84 | 85 | let result = Contracts::bare_instantiate( 86 | ALICE, 87 | init_value, 88 | GAS_LIMIT, 89 | None, 90 | Code::Upload(wasm_binary), 91 | function_selector("new"), 92 | salt, 93 | DEBUG_OUTPUT, 94 | CollectEvents::Skip, 95 | ) 96 | .result 97 | .unwrap(); 98 | assert!(!result.result.did_revert(), "deploying contract reverted {:?}", result); 99 | result.account_id 100 | } 101 | -------------------------------------------------------------------------------- /pop-api/integration-tests/src/utils.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | // Get the last event from pallet contracts. 4 | pub(super) fn last_contract_event() -> Vec { 5 | let events = System::read_events_for_pallet::>(); 6 | let contract_events = events 7 | .iter() 8 | .filter_map(|event| match event { 9 | pallet_contracts::Event::::ContractEmitted { data, .. } => 10 | Some(data.as_slice()), 11 | _ => None, 12 | }) 13 | .collect::>(); 14 | contract_events.last().unwrap().to_vec() 15 | } 16 | 17 | // Decodes a byte slice into an `AccountId` as defined in `primitives`. 18 | // 19 | // This is used to resolve type mismatches between the `AccountId` in the integration tests and the 20 | // contract environment. 21 | pub(super) fn account_id_from_slice(s: &[u8; 32]) -> pop_api::primitives::AccountId { 22 | pop_api::primitives::AccountId::decode(&mut &s[..]).expect("Should be decoded to AccountId") 23 | } 24 | 25 | pub(super) fn do_bare_call(function: &str, addr: &AccountId32, params: Vec) -> ExecReturnValue { 26 | let function = function_selector(function); 27 | let params = [function, params].concat(); 28 | bare_call(addr.clone(), params, 0).expect("should work") 29 | } 30 | 31 | pub(super) fn decoded(result: ExecReturnValue) -> Result { 32 | ::decode(&mut &result.data[1..]).map_err(|_| result) 33 | } 34 | -------------------------------------------------------------------------------- /pop-api/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! The `pop-api` crate provides an API for smart contracts to interact with the Pop Network 2 | //! runtime. 3 | //! 4 | //! This crate abstracts away complexities to deliver a streamlined developer experience while 5 | //! supporting multiple API versions to ensure backward compatibility. It is designed with a focus 6 | //! on stability, future-proofing, and storage efficiency, allowing developers to easily integrate 7 | //! powerful runtime features into their contracts without unnecessary overhead. 8 | 9 | #![cfg_attr(not(feature = "std"), no_std, no_main)] 10 | 11 | use constants::DECODING_FAILED; 12 | use ink::env::chain_extension::{ChainExtensionMethod, FromStatusCode}; 13 | pub use v0::*; 14 | 15 | /// Module providing macros. 16 | pub mod macros; 17 | /// Module providing primitives types. 18 | pub mod primitives; 19 | /// The first version of the API. 20 | pub mod v0; 21 | 22 | type ChainExtensionMethodApi = ChainExtensionMethod<(), (), (), false>; 23 | /// The result type used by the API, with the `StatusCode` as the error type. 24 | pub type Result = core::result::Result; 25 | 26 | /// Represents a status code returned by the runtime. 27 | /// 28 | /// `StatusCode` encapsulates a `u32` value that indicates the success or failure of a runtime call 29 | /// via Pop API. 30 | /// 31 | /// A `StatusCode` of `0` indicates success, while any other value represents an 32 | /// error. 33 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] 34 | #[ink::scale_derive(Encode, Decode, TypeInfo)] 35 | pub struct StatusCode(pub u32); 36 | 37 | impl From for StatusCode { 38 | /// Converts a `u32` into a `StatusCode`. 39 | fn from(value: u32) -> Self { 40 | StatusCode(value) 41 | } 42 | } 43 | 44 | impl FromStatusCode for StatusCode { 45 | /// Converts a `u32` status code to a `Result`. 46 | /// 47 | /// `Ok(())` if the status code is `0` and `Err(StatusCode(status_code))` for any other status 48 | /// code. 49 | fn from_status_code(status_code: u32) -> Result<()> { 50 | match status_code { 51 | 0 => Ok(()), 52 | _ => Err(StatusCode(status_code)), 53 | } 54 | } 55 | } 56 | 57 | impl From for StatusCode { 58 | /// Converts a scale decoding error into a `StatusCode` indicating a decoding failure. 59 | fn from(_: ink::scale::Error) -> Self { 60 | StatusCode(DECODING_FAILED) 61 | } 62 | } 63 | 64 | mod constants { 65 | // Error. 66 | pub(crate) const DECODING_FAILED: u32 = 255; 67 | // Runtime Errors. 68 | pub(crate) const MODULE_ERROR: u8 = 3; 69 | 70 | // Function IDs. 71 | pub(crate) const DISPATCH: u8 = 0; 72 | pub(crate) const READ_STATE: u8 = 1; 73 | 74 | // Modules. 75 | pub(crate) const ASSETS: u8 = 52; 76 | pub(crate) const BALANCES: u8 = 10; 77 | pub(crate) const FUNGIBLES: u8 = 150; 78 | pub(crate) const NFTS: u8 = 50; 79 | pub(crate) const MESSAGING: u8 = 152; 80 | pub(crate) const NONFUNGIBLES: u8 = 151; 81 | } 82 | 83 | // Helper method to build a dispatch call or a call to read state. 84 | // 85 | // Parameters: 86 | // - 'function': The ID of the function. 87 | // - 'version': The version of the chain extension. 88 | // - 'module': The index of the runtime module. 89 | // - 'dispatchable': The index of the module dispatchable functions. 90 | fn build_extension_method( 91 | function: u8, 92 | version: u8, 93 | module: u8, 94 | dispatchable: u8, 95 | ) -> ChainExtensionMethodApi { 96 | ChainExtensionMethod::build(u32::from_le_bytes([function, version, module, dispatchable])) 97 | } 98 | -------------------------------------------------------------------------------- /pop-api/src/macros.rs: -------------------------------------------------------------------------------- 1 | // Copyright (C) Parity Technologies (UK) Ltd. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | /// Implements encoding and decoding traits for a wrapper type that represents 17 | /// bitflags. The wrapper type should contain a field of type `$size`, where 18 | /// `$size` is an integer type (e.g., u8, u16, u32) that can represent the bitflags. 19 | /// The `$bitflag_enum` type is the enumeration type that defines the individual bitflags. 20 | /// 21 | /// This macro provides implementations for the following traits: 22 | /// - `MaxEncodedLen`: Calculates the maximum encoded length for the wrapper type. 23 | /// - `Encode`: Encodes the wrapper type using the provided encoding function. 24 | /// - `Decode`: Decodes the wrapper type from the input. 25 | /// - `TypeInfo`: Provides type information for the wrapper type. 26 | macro_rules! impl_codec_bitflags { 27 | ($wrapper:ty, $size:ty, $bitflag_enum:ty) => { 28 | impl ink::scale::MaxEncodedLen for $wrapper { 29 | fn max_encoded_len() -> usize { 30 | <$size>::max_encoded_len() 31 | } 32 | } 33 | impl ink::scale::Encode for $wrapper { 34 | fn using_encoded R>(&self, f: F) -> R { 35 | self.0.bits().using_encoded(f) 36 | } 37 | } 38 | impl ink::scale::Decode for $wrapper { 39 | fn decode( 40 | input: &mut I, 41 | ) -> ::core::result::Result { 42 | let field = <$size>::decode(input)?; 43 | Ok(Self(BitFlags::from_bits(field as $size).map_err(|_| "invalid value")?)) 44 | } 45 | } 46 | 47 | #[cfg(feature = "std")] 48 | impl ink::scale_info::TypeInfo for $wrapper { 49 | type Identity = Self; 50 | 51 | fn type_info() -> ink::scale_info::Type { 52 | ink::scale_info::Type::builder() 53 | .path(ink::scale_info::Path::new("BitFlags", module_path!())) 54 | .type_params(vec![ink::scale_info::TypeParameter::new( 55 | "T", 56 | Some(ink::scale_info::meta_type::<$bitflag_enum>()), 57 | )]) 58 | .composite( 59 | ink::scale_info::build::Fields::unnamed() 60 | .field(|f| f.ty::<$size>().type_name(stringify!($bitflag_enum))), 61 | ) 62 | } 63 | } 64 | }; 65 | } 66 | pub(crate) use impl_codec_bitflags; 67 | -------------------------------------------------------------------------------- /pop-api/src/primitives.rs: -------------------------------------------------------------------------------- 1 | use ink::env::{DefaultEnvironment, Environment}; 2 | pub use pop_primitives::*; 3 | 4 | // Public due to integration tests crate. 5 | pub type AccountId = ::AccountId; 6 | pub type Balance = ::Balance; 7 | pub type BlockNumber = ::BlockNumber; 8 | pub type Hash = ::Hash; 9 | pub type Era = BlockNumber; 10 | pub type Timestamp = ::Timestamp; 11 | -------------------------------------------------------------------------------- /pop-api/src/v0/fungibles/README.md: -------------------------------------------------------------------------------- 1 | ## Fungibles API 2 | 3 | The `fungibles` module provides an api for interacting and managing fungible tokens. 4 | 5 | It includes the following interfaces: 6 | 7 | 1. PSP-22 8 | 2. PSP-22 Metadata 9 | 3. Management 10 | 4. PSP-22 Mintable & Burnable 11 | 12 | To use it in your contract add the `fungibles` feature to the `pop-api` dependency. 13 | 14 | ```toml 15 | # Cargo.toml 16 | pop-api = { git = "https://github.com/r0gue-io/pop-node", default-features = false, features = [ "fungibles" ] } 17 | ``` 18 | 19 | Check out the [examples](../../examples/fungibles/) to learn how you can use the fungibles api. -------------------------------------------------------------------------------- /pop-api/src/v0/fungibles/events.rs: -------------------------------------------------------------------------------- 1 | //! A set of events for use in smart contracts interacting with the fungibles API. 2 | //! 3 | //! The `Transfer` and `Approval` events conform to the PSP-22 standard. The other events 4 | //! (`Create`, `StartDestroy`, `SetMetadata`, `ClearMetadata`) are provided for convenience. 5 | //! 6 | //! These events are not emitted by the API itself but can be used in your contracts to 7 | //! track token operations. Be mindful of the costs associated with emitting events. 8 | //! 9 | //! For more details, refer to [ink! events](https://use.ink/basics/events). 10 | 11 | use super::*; 12 | 13 | /// Event emitted when allowance by `owner` to `spender` changes. 14 | // Differing style: event name abides by the PSP22 standard. 15 | #[ink::event] 16 | #[cfg_attr(feature = "std", derive(Debug))] 17 | pub struct Approval { 18 | /// The owner providing the allowance. 19 | #[ink(topic)] 20 | pub owner: AccountId, 21 | /// The beneficiary of the allowance. 22 | #[ink(topic)] 23 | pub spender: AccountId, 24 | /// The new allowance amount. 25 | pub value: u128, 26 | } 27 | 28 | /// Event emitted when transfer of tokens occurs. 29 | // Differing style: event name abides by the PSP22 standard. 30 | #[ink::event] 31 | #[cfg_attr(feature = "std", derive(Debug))] 32 | pub struct Transfer { 33 | /// The source of the transfer. `None` when minting. 34 | #[ink(topic)] 35 | pub from: Option, 36 | /// The recipient of the transfer. `None` when burning. 37 | #[ink(topic)] 38 | pub to: Option, 39 | /// The amount transferred (or minted/burned). 40 | pub value: u128, 41 | } 42 | 43 | /// Event emitted when a token is created. 44 | #[ink::event] 45 | #[cfg_attr(feature = "std", derive(Debug))] 46 | pub struct Created { 47 | /// The token identifier. 48 | #[ink(topic)] 49 | pub id: TokenId, 50 | /// The creator of the token. 51 | #[ink(topic)] 52 | pub creator: AccountId, 53 | /// The administrator of the token. 54 | #[ink(topic)] 55 | pub admin: AccountId, 56 | } 57 | 58 | /// Event emitted when a token is in the process of being destroyed. 59 | #[ink::event] 60 | #[cfg_attr(feature = "std", derive(Debug))] 61 | pub struct DestroyStarted { 62 | /// The token. 63 | #[ink(topic)] 64 | pub token: TokenId, 65 | } 66 | 67 | /// Event emitted when new metadata is set for a token. 68 | #[ink::event] 69 | #[cfg_attr(feature = "std", derive(Debug))] 70 | pub struct MetadataSet { 71 | /// The token. 72 | #[ink(topic)] 73 | pub token: TokenId, 74 | /// The name of the token. 75 | #[ink(topic)] 76 | pub name: Vec, 77 | /// The symbol of the token. 78 | #[ink(topic)] 79 | pub symbol: Vec, 80 | /// The decimals of the token. 81 | pub decimals: u8, 82 | } 83 | 84 | /// Event emitted when metadata is cleared for a token. 85 | #[ink::event] 86 | #[cfg_attr(feature = "std", derive(Debug))] 87 | pub struct MetadataCleared { 88 | /// The token. 89 | #[ink(topic)] 90 | pub token: TokenId, 91 | } 92 | -------------------------------------------------------------------------------- /pop-api/src/v0/messaging/ismp.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | 3 | #[ink::scale_derive(Encode, Decode, TypeInfo)] 4 | pub struct Get { 5 | pub dest: u32, 6 | pub height: u32, 7 | pub timeout: u64, 8 | // TODO: Option 9 | pub context: Vec, 10 | pub keys: Vec>, 11 | } 12 | 13 | impl Get { 14 | pub fn new(dest: u32, height: u32, timeout: u64, context: Vec, keys: Vec>) -> Self { 15 | // TODO: validate: dest para id, ensure at least one key 16 | Self { dest, height, timeout, context, keys } 17 | } 18 | } 19 | 20 | #[ink::scale_derive(Encode, Decode, TypeInfo)] 21 | pub struct Post { 22 | pub dest: u32, 23 | pub timeout: u64, 24 | pub data: Vec, 25 | } 26 | 27 | impl Post { 28 | pub fn new(dest: u32, timeout: u64, data: Vec) -> Self { 29 | // TODO: validate: dest para id, ensure data not empty 30 | Self { dest, timeout, data } 31 | } 32 | } 33 | 34 | /// A verified storage value. 35 | #[ink::scale_derive(Encode, Decode, TypeInfo)] 36 | #[derive(Debug)] 37 | pub struct StorageValue { 38 | /// The request storage key. 39 | pub key: Vec, 40 | /// The verified value. 41 | pub value: Option>, 42 | } 43 | 44 | #[inline] 45 | pub fn get(id: MessageId, request: Get, fee: Balance, callback: Option) -> Result<()> { 46 | build_dispatch(ISMP_GET) 47 | .input::<(MessageId, Get, Balance, Option)>() 48 | .output::, true>() 49 | .handle_error_code::() 50 | .call(&(id, request, fee, callback)) 51 | } 52 | 53 | #[inline] 54 | pub fn post(id: MessageId, request: Post, fee: Balance, callback: Option) -> Result<()> { 55 | build_dispatch(ISMP_POST) 56 | .input::<(MessageId, Post, Balance, Option)>() 57 | .output::, true>() 58 | .handle_error_code::() 59 | .call(&(id, request, fee, callback)) 60 | } 61 | 62 | #[ink::trait_definition] 63 | pub trait OnGetResponse { 64 | // pop-api::messaging::ismp::OnGetResponse::on_response 65 | #[ink(message, selector = 0x57ad942b)] 66 | fn on_response(&mut self, id: MessageId, values: Vec) -> Result<()>; 67 | } 68 | 69 | #[ink::trait_definition] 70 | pub trait OnPostResponse { 71 | // pop-api::messaging::ismp::OnPostResponse::on_response 72 | #[ink(message, selector = 0xcfb0a1d2)] 73 | fn on_response(&mut self, id: MessageId, response: Vec) -> Result<()>; 74 | } 75 | -------------------------------------------------------------------------------- /pop-api/src/v0/messaging/mod.rs: -------------------------------------------------------------------------------- 1 | use ink::prelude::vec::Vec; 2 | 3 | use crate::{ 4 | constants::MESSAGING, 5 | messaging::xcm::Weight, 6 | primitives::{AccountId, Balance, BlockNumber}, 7 | ChainExtensionMethodApi, Result, StatusCode, 8 | }; 9 | 10 | /// APIs for messaging using the Interoperable State Machine Protocol (ISMP). 11 | pub mod ismp; 12 | /// APIs for messaging using Polkadot's Cross-Consensus Messaging (XCM). 13 | pub mod xcm; 14 | 15 | // Dispatchables 16 | pub(super) const _REQUEST: u8 = 0; 17 | pub(super) const ISMP_GET: u8 = 1; 18 | pub(super) const ISMP_POST: u8 = 2; 19 | pub(super) const XCM_NEW_QUERY: u8 = 3; 20 | pub(super) const _XCM_RESPONSE: u8 = 4; 21 | pub(super) const REMOVE: u8 = 5; 22 | // Reads 23 | pub(super) const POLL: u8 = 0; 24 | pub(super) const GET: u8 = 1; 25 | pub(super) const QUERY_ID: u8 = 2; 26 | 27 | pub type MessageId = u64; 28 | 29 | fn build_dispatch(dispatchable: u8) -> ChainExtensionMethodApi { 30 | crate::v0::build_dispatch(MESSAGING, dispatchable) 31 | } 32 | 33 | fn build_read_state(state_query: u8) -> ChainExtensionMethodApi { 34 | crate::v0::build_read_state(MESSAGING, state_query) 35 | } 36 | 37 | #[inline] 38 | pub fn poll(id: (AccountId, MessageId)) -> Result> { 39 | build_read_state(POLL) 40 | .input::<(AccountId, MessageId)>() 41 | .output::>, true>() 42 | .handle_error_code::() 43 | .call(&id) 44 | } 45 | 46 | #[inline] 47 | pub fn get(id: (AccountId, MessageId)) -> Result>> { 48 | build_read_state(GET) 49 | .input::<(AccountId, MessageId)>() 50 | .output::>>, true>() 51 | .handle_error_code::() 52 | .call(&id) 53 | } 54 | 55 | #[inline] 56 | pub fn remove(requests: Vec) -> Result<()> { 57 | build_dispatch(REMOVE) 58 | .input::>() 59 | .output::, true>() 60 | .handle_error_code::() 61 | .call(&requests) 62 | } 63 | 64 | #[ink::scale_derive(Decode, Encode, TypeInfo)] 65 | pub struct Callback { 66 | selector: [u8; 4], 67 | weight: Weight, 68 | } 69 | 70 | impl Callback { 71 | pub fn to(selector: u32, weight: Weight) -> Self { 72 | Self { selector: selector.to_be_bytes(), weight } 73 | } 74 | } 75 | 76 | #[derive(PartialEq)] 77 | #[ink::scale_derive(Decode, Encode, TypeInfo)] 78 | #[cfg_attr(feature = "std", derive(Debug))] 79 | pub enum Status { 80 | Pending, 81 | TimedOut, 82 | Complete, 83 | } 84 | -------------------------------------------------------------------------------- /pop-api/src/v0/messaging/xcm.rs: -------------------------------------------------------------------------------- 1 | pub use ink::{ 2 | env::call::Selector, 3 | prelude::vec::Vec, 4 | xcm::prelude::{ 5 | Junction, Junctions, Location, MaybeErrorCode, NetworkId, QueryId, Response, 6 | VersionedLocation, VersionedResponse, VersionedXcm, Weight, XcmContext, XcmHash, 7 | }, 8 | }; 9 | use ink::{ 10 | env::{account_id, xcm_execute, xcm_send, DefaultEnvironment}, 11 | scale::Encode, 12 | }; 13 | 14 | use super::*; 15 | 16 | /// Note: usage of a callback requires implementation of the [OnResponse] trait. 17 | #[inline] 18 | pub fn new_query( 19 | id: MessageId, 20 | responder: Location, 21 | timeout: BlockNumber, 22 | callback: Option, 23 | ) -> Result> { 24 | build_dispatch(XCM_NEW_QUERY) 25 | .input::<(MessageId, Location, BlockNumber, Option)>() 26 | .output::, true>() 27 | .handle_error_code::() 28 | .call(&(id, responder, timeout, callback))?; 29 | 30 | build_read_state(QUERY_ID) 31 | .input::<(AccountId, MessageId)>() 32 | .output::>, true>() 33 | .handle_error_code::() 34 | .call(&(account_id::(), id)) 35 | } 36 | 37 | /// Execute an XCM message locally, using the contract's address as the origin. 38 | pub fn execute(msg: &VersionedXcm) -> ink::env::Result<()> { 39 | xcm_execute::(msg) 40 | } 41 | 42 | /// Send an XCM message, using the contract's address as the origin. 43 | pub fn send( 44 | dest: &VersionedLocation, 45 | msg: &VersionedXcm, 46 | ) -> ink::env::Result { 47 | xcm_send::(dest, msg) 48 | } 49 | 50 | #[ink::trait_definition] 51 | pub trait OnResponse { 52 | // pop-api::messaging::xcm::OnResponse::on_response 53 | #[ink(message, selector = 0x641b0b03)] 54 | fn on_response(&mut self, id: MessageId, response: Response) -> Result<()>; 55 | } 56 | -------------------------------------------------------------------------------- /pop-api/src/v0/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | build_extension_method, 3 | constants::{DISPATCH, READ_STATE}, 4 | primitives::Error, 5 | ChainExtensionMethodApi, StatusCode, 6 | }; 7 | 8 | /// APIs for fungible tokens. 9 | #[cfg(feature = "fungibles")] 10 | pub mod fungibles; 11 | /// APIs for messaging. 12 | #[cfg(feature = "messaging")] 13 | pub mod messaging; 14 | /// APIs for non-fungible tokens. 15 | #[cfg(feature = "nonfungibles")] 16 | pub mod nonfungibles; 17 | 18 | pub(crate) const V0: u8 = 0; 19 | 20 | impl From for Error { 21 | fn from(value: StatusCode) -> Self { 22 | value.0.into() 23 | } 24 | } 25 | 26 | // Helper method to build a dispatch call. 27 | // 28 | // Parameters: 29 | // - 'module': The index of the runtime module. 30 | // - 'dispatchable': The index of the module dispatchable functions. 31 | fn build_dispatch(module: u8, dispatchable: u8) -> ChainExtensionMethodApi { 32 | build_extension_method(DISPATCH, V0, module, dispatchable) 33 | } 34 | 35 | // Helper method to build a call to read state. 36 | // 37 | // Parameters: 38 | // - 'module': The index of the runtime module. 39 | // - 'state_query': The index of the runtime state query. 40 | fn build_read_state(module: u8, state_query: u8) -> ChainExtensionMethodApi { 41 | build_extension_method(READ_STATE, V0, module, state_query) 42 | } 43 | -------------------------------------------------------------------------------- /pop-api/src/v0/nonfungibles/README.md: -------------------------------------------------------------------------------- 1 | ## Non-Fungibles API 2 | 3 | The `nonfungibles` module provides an api for interacting and managing non-fungible tokens. 4 | 5 | It includes the following interfaces: 6 | 7 | 1. PSP-34 8 | 2. PSP-34 Metadata 9 | 3. Management 10 | 4. PSP-34 Mintable & Burnable 11 | 12 | To use it in your contract add the `nonfungibles` feature to the `pop-api` dependency. 13 | 14 | ```toml 15 | # Cargo.toml 16 | pop-api = { git = "https://github.com/r0gue-io/pop-node", default-features = false, features = [ "nonfungibles" ] } 17 | ``` 18 | 19 | Check out the [examples](../../examples/nonfungibles/) to learn how you can use the non-fungibles api. 20 | -------------------------------------------------------------------------------- /pop-api/src/v0/nonfungibles/errors.rs: -------------------------------------------------------------------------------- 1 | //! A set of errors for use in smart contracts that interact with the nonfungibles api. This 2 | //! includes errors compliant to standards. 3 | 4 | use ink::prelude::string::{String, ToString}; 5 | 6 | use super::*; 7 | 8 | /// The PSP34 error. 9 | #[derive(Debug, PartialEq, Eq)] 10 | #[ink::scale_derive(Encode, Decode, TypeInfo)] 11 | pub enum Psp34Error { 12 | /// Custom error type for cases if writer of traits added own restrictions. 13 | Custom(String), 14 | /// Returned if owner approves self. 15 | SelfApprove, 16 | /// Returned if the caller doesn't have allowance for transferring. 17 | NotApproved, 18 | /// Returned if the owner already own the token. 19 | TokenExists, 20 | /// Returned if the token doesn't exist. 21 | TokenNotExists, 22 | /// Returned if safe transfer check fails. 23 | SafeTransferCheckFailed(String), 24 | } 25 | 26 | #[cfg(feature = "std")] 27 | impl From for u32 { 28 | fn from(value: Psp34Error) -> u32 { 29 | match value { 30 | Psp34Error::NotApproved => u32::from_le_bytes([MODULE_ERROR, NFTS, 0, 0]), 31 | Psp34Error::TokenExists => u32::from_le_bytes([MODULE_ERROR, NFTS, 2, 0]), 32 | Psp34Error::TokenNotExists => u32::from_le_bytes([MODULE_ERROR, NFTS, 19, 0]), 33 | Psp34Error::Custom(value) => value.parse::().expect("Failed to parse"), 34 | _ => unimplemented!("Variant is not supported"), 35 | } 36 | } 37 | } 38 | 39 | impl From for Psp34Error { 40 | /// Converts a `StatusCode` to a `PSP34Error`. 41 | fn from(value: StatusCode) -> Self { 42 | let encoded = value.0.to_le_bytes(); 43 | match encoded { 44 | // NoPermission. 45 | [MODULE_ERROR, NFTS, 0, _] => Psp34Error::NotApproved, 46 | // AlreadyExists. 47 | [MODULE_ERROR, NFTS, 2, _] => Psp34Error::TokenExists, 48 | // ApprovalExpired. 49 | [MODULE_ERROR, NFTS, 3, _] => Psp34Error::NotApproved, 50 | // UnknownItem. 51 | [MODULE_ERROR, NFTS, 19, _] => Psp34Error::TokenNotExists, 52 | _ => Psp34Error::Custom(value.0.to_string()), 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /pop-api/src/v0/nonfungibles/events.rs: -------------------------------------------------------------------------------- 1 | //! A set of events for use in smart contracts interacting with the non-fungibles API. 2 | //! 3 | //! The `Transfer`, `Approval` and `AttributeSet` events conform to the PSP-34 standard. 4 | //! 5 | //! These events are not emitted by the API itself but can be used in your contracts to 6 | //! track token operations. Be mindful of the costs associated with emitting events. 7 | //! 8 | //! For more details, refer to [ink! events](https://use.ink/basics/events). 9 | 10 | use super::*; 11 | 12 | /// Event emitted when a token transfer occurs. 13 | #[ink::event] 14 | pub struct Transfer { 15 | /// The source of the transfer. `None` when minting. 16 | #[ink(topic)] 17 | pub from: Option, 18 | /// The recipient of the transfer. `None` when burning. 19 | #[ink(topic)] 20 | pub to: Option, 21 | /// The item transferred (or minted/burned). 22 | pub item: ItemId, 23 | } 24 | 25 | /// Event emitted when a token approve occurs. 26 | #[ink::event] 27 | pub struct Approval { 28 | /// The owner providing the allowance. 29 | #[ink(topic)] 30 | pub owner: AccountId, 31 | /// The beneficiary of the allowance. 32 | #[ink(topic)] 33 | pub operator: AccountId, 34 | /// The item which is (dis)approved. `None` for all owner's items. 35 | pub item: Option, 36 | /// Whether allowance is set or removed. 37 | pub approved: bool, 38 | } 39 | 40 | /// Event emitted when an attribute is set for a token. 41 | #[ink::event] 42 | pub struct AttributeSet { 43 | /// The item which attribute is set. 44 | #[ink(topic)] 45 | pub item: Option, 46 | /// The key for the attribute. 47 | pub key: Vec, 48 | /// The data for the attribute. 49 | pub data: Vec, 50 | } 51 | -------------------------------------------------------------------------------- /pop-api/src/v0/nonfungibles/traits.rs: -------------------------------------------------------------------------------- 1 | //! Traits that can be used by contracts. Including standard compliant traits. 2 | 3 | use core::result::Result; 4 | 5 | use super::*; 6 | 7 | /// The PSP34 trait. 8 | #[ink::trait_definition] 9 | pub trait Psp34 { 10 | /// Returns the collection ID. 11 | #[ink(message, selector = 0xffa27a5f)] 12 | fn collection_id(&self) -> CollectionId; 13 | 14 | // Returns the current total supply of the NFT collection. 15 | #[ink(message, selector = 0x628413fe)] 16 | fn total_supply(&self) -> u128; 17 | 18 | /// Returns the amount of items the owner has within a collection. 19 | /// 20 | /// # Parameters 21 | /// - `owner` - The account whose balance is being queried. 22 | #[ink(message, selector = 0xcde7e55f)] 23 | fn balance_of(&self, owner: AccountId) -> u32; 24 | 25 | /// Returns whether the operator is approved by the owner to withdraw `item`. If `item` is 26 | /// `None`, it returns whether the operator is approved to withdraw all owner's items for the 27 | /// given collection. 28 | /// 29 | /// # Parameters 30 | /// - `owner` - The account that owns the item(s). 31 | /// - `operator` - the account that is allowed to withdraw the item(s). 32 | /// - `item` - The item. If `None`, it is regarding all owner's items in collection. 33 | #[ink(message, selector = 0x4790f55a)] 34 | fn allowance(&self, owner: AccountId, operator: AccountId, item: Option) -> bool; 35 | 36 | /// Transfers an owned or approved item to the specified recipient. 37 | /// 38 | /// # Parameters 39 | /// - `to` - The recipient account. 40 | /// - `item` - The item. 41 | /// - `data` - Additional data in unspecified format. 42 | #[ink(message, selector = 0x3128d61b)] 43 | fn transfer(&mut self, to: AccountId, item: ItemId, data: Vec) -> Result<(), Psp34Error>; 44 | 45 | /// Approves operator to withdraw item(s) from the contract's account. 46 | /// 47 | /// # Parameters 48 | /// - `operator` - The account that is allowed to withdraw the item. 49 | /// - `item` - Optional item. `None` means all items owned in the specified collection. 50 | /// - `approved` - Whether the operator is given or removed the right to withdraw the item(s). 51 | #[ink(message, selector = 0x1932a8b0)] 52 | fn approve( 53 | &mut self, 54 | operator: AccountId, 55 | item: Option, 56 | approved: bool, 57 | ) -> Result<(), Psp34Error>; 58 | 59 | /// Returns the owner of an item within a specified collection, if any. 60 | /// 61 | /// # Parameters 62 | /// - `item` - The item. 63 | #[ink(message, selector = 0x1168624d)] 64 | fn owner_of(&self, item: ItemId) -> Option; 65 | } 66 | 67 | /// The PSP34 Metadata trait. 68 | #[ink::trait_definition] 69 | pub trait Psp34Metadata { 70 | /// Returns the attribute of `item` for the given `key`. 71 | /// 72 | /// # Parameters 73 | /// - `item` - The item. If `None` the attributes for the collection are queried. 74 | /// - `key` - The key of the attribute. 75 | #[ink(message, selector = 0xf19d48d1)] 76 | fn get_attribute(&self, item: Option, key: Vec) -> Option>; 77 | } 78 | 79 | /// The PSP34 Mintable trait. 80 | #[ink::trait_definition] 81 | pub trait Psp34Mintable { 82 | /// Mints an item to the specified address. 83 | /// 84 | /// # Parameters 85 | /// - `to` - The recipient account. 86 | /// - `item` - The ID for the item. 87 | #[ink(message, selector = 0x6c41f2ec)] 88 | fn mint(&mut self, to: AccountId, item: ItemId) -> Result<(), Psp34Error>; 89 | } 90 | 91 | /// The PSP34 Burnable trait. 92 | #[ink::trait_definition] 93 | pub trait Psp34Burnable { 94 | /// Destroys the specified item. Clearing the corresponding approvals. 95 | /// 96 | /// # Parameters 97 | /// - `item` - The item. 98 | #[ink(message, selector = 0x63c9877a)] 99 | fn burn(&mut self, item: ItemId) -> Result<(), Psp34Error>; 100 | } 101 | -------------------------------------------------------------------------------- /primitives/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | description = "Primitives crate for Pop" 3 | edition = "2021" 4 | license = "GPL-3.0-only" 5 | name = "pop-primitives" 6 | version = "0.0.0" 7 | 8 | [dependencies] 9 | codec.workspace = true 10 | scale-info.workspace = true 11 | 12 | [dev-dependencies] 13 | enum-iterator = "2.1.0" 14 | 15 | [features] 16 | default = [ "std" ] 17 | std = [ "codec/std", "scale-info/std" ] 18 | -------------------------------------------------------------------------------- /primitives/README.md: -------------------------------------------------------------------------------- 1 | Reserved crate for pop-primitives. -------------------------------------------------------------------------------- /runtime/common/src/genesis.rs: -------------------------------------------------------------------------------- 1 | #[cfg(not(feature = "std"))] 2 | use alloc::format; 3 | use alloc::vec::Vec; 4 | 5 | use parachains_common::AccountId; 6 | use polkadot_parachain_primitives::primitives::Sibling; 7 | pub use serde_json::{json, to_string, Value}; 8 | pub use sp_keyring::sr25519::Keyring; 9 | use sp_runtime::traits::AccountIdConversion; 10 | 11 | /// Sovereign account of AssetHub on Pop. 12 | pub fn asset_hub_sa_on_pop() -> AccountId { 13 | Sibling::from(1_000).into_account_truncating() 14 | } 15 | 16 | /// A set of dev accounts, typically used for endowments at genesis for development chains. 17 | pub fn dev_accounts() -> Vec { 18 | Keyring::well_known().map(|k| k.to_account_id()).collect() 19 | } 20 | 21 | /// Derive a multisig key from a given set of `accounts` and a `threshold`. 22 | pub fn derive_multisig( 23 | mut signatories: Vec, 24 | threshold: u16, 25 | ) -> T::AccountId { 26 | assert!(!signatories.is_empty(), "Signatories set cannot be empty"); 27 | assert!(threshold > 0, "Threshold for multisig cannot be 0"); 28 | assert!( 29 | signatories.len() >= threshold.into(), 30 | "Threshold must be less than or equal to the number of signatories" 31 | ); 32 | // Sorting is done to deterministically order the multisig set 33 | // So that a single authority set (A, B, C) may generate only a single unique multisig key 34 | // Otherwise, (B, A, C) or (C, A, B) could produce different keys and cause chaos 35 | signatories.sort(); 36 | 37 | // Derive a multisig with `threshold / signatories.len()` threshold 38 | pallet_multisig::Pallet::::multi_account_id(&signatories[..], threshold) 39 | } 40 | -------------------------------------------------------------------------------- /runtime/common/src/weights/block_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | #![allow(unused_parens)] 19 | #![allow(unused_imports)] 20 | #![allow(missing_docs)] 21 | pub mod constants { 22 | use frame_support::{ 23 | parameter_types, 24 | weights::{constants, Weight}, 25 | }; 26 | 27 | parameter_types! { 28 | /// Importing a block with 0 Extrinsics. 29 | pub const BlockExecutionWeight: Weight = 30 | Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0); 31 | } 32 | 33 | #[cfg(test)] 34 | mod test_weights { 35 | use frame_support::weights::constants; 36 | 37 | /// Checks that the weight exists and is sane. 38 | // NOTE: If this test fails but you are sure that the generated values are fine, 39 | // you can delete it. 40 | #[test] 41 | fn sane() { 42 | let w = super::constants::BlockExecutionWeight::get(); 43 | 44 | // At least 100 µs. 45 | assert!( 46 | w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS, 47 | "Weight should be at least 100 µs." 48 | ); 49 | // At most 50 ms. 50 | assert!( 51 | w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS, 52 | "Weight should be at most 50 ms." 53 | ); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /runtime/common/src/weights/cumulus_pallet_parachain_system.rs: -------------------------------------------------------------------------------- 1 | 2 | //! Autogenerated weights for `cumulus_pallet_parachain_system` 3 | //! 4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 46.0.0 5 | //! DATE: 2025-02-28, STEPS: `5`, REPEAT: `5`, LOW RANGE: `[]`, HIGH RANGE: `[]` 6 | //! WORST CASE MAP SIZE: `1000000` 7 | //! HOSTNAME: `tux`, CPU: `12th Gen Intel(R) Core(TM) i7-12700H` 8 | //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("pop")`, DB CACHE: `1024` 9 | 10 | // Executed Command: 11 | // ./target/release//pop-node 12 | // benchmark 13 | // pallet 14 | // --template=./scripts/templates/runtime-weight-template.hbs 15 | // --chain=pop 16 | // --wasm-execution=compiled 17 | // --pallet=cumulus_pallet_parachain_system 18 | // --extrinsic=* 19 | // --steps=5 20 | // --repeat=5 21 | // --output=./runtime/mainnet/src/weights/ 22 | 23 | #![cfg_attr(rustfmt, rustfmt_skip)] 24 | #![allow(unused_parens)] 25 | #![allow(unused_imports)] 26 | #![allow(missing_docs)] 27 | 28 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 29 | use core::marker::PhantomData; 30 | 31 | /// Weights for `cumulus_pallet_parachain_system`. 32 | pub struct WeightInfo(PhantomData); 33 | impl cumulus_pallet_parachain_system::WeightInfo for WeightInfo { 34 | /// Storage: `ParachainSystem::LastDmqMqcHead` (r:1 w:1) 35 | /// Proof: `ParachainSystem::LastDmqMqcHead` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) 36 | /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) 37 | /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) 38 | /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) 39 | /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) 40 | /// Storage: `ParachainSystem::ProcessedDownwardMessages` (r:0 w:1) 41 | /// Proof: `ParachainSystem::ProcessedDownwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) 42 | /// Storage: `MessageQueue::Pages` (r:0 w:1000) 43 | /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) 44 | /// The range of component `n` is `[0, 1000]`. 45 | fn enqueue_inbound_downward_messages(n: u32, ) -> Weight { 46 | // Proof Size summary in bytes: 47 | // Measured: `12` 48 | // Estimated: `3517` 49 | // Minimum execution time: 2_337_000 picoseconds. 50 | Weight::from_parts(2_339_000, 3517) 51 | // Standard Error: 1_263_086 52 | .saturating_add(Weight::from_parts(179_837_875, 0).saturating_mul(n.into())) 53 | .saturating_add(T::DbWeight::get().reads(2_u64)) 54 | .saturating_add(T::DbWeight::get().writes(2_u64)) 55 | .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /runtime/common/src/weights/cumulus_pallet_weight_reclaim.rs: -------------------------------------------------------------------------------- 1 | //! Autogenerated weights for `cumulus_pallet_weight_reclaim` 2 | //! 3 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 46.0.0 4 | //! DATE: 2025-02-28, STEPS: `5`, REPEAT: `5`, LOW RANGE: `[]`, HIGH RANGE: `[]` 5 | //! WORST CASE MAP SIZE: `1000000` 6 | //! HOSTNAME: `tux`, CPU: `12th Gen Intel(R) Core(TM) i7-12700H` 7 | //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("pop")`, DB CACHE: `1024` 8 | 9 | // Executed Command: 10 | // ./target/release//pop-node 11 | // benchmark 12 | // pallet 13 | // --template=./scripts/templates/runtime-weight-template.hbs 14 | // --chain=pop 15 | // --wasm-execution=compiled 16 | // --pallet=cumulus_pallet_weight_reclaim 17 | // --extrinsic=* 18 | // --steps=5 19 | // --repeat=5 20 | // --output=./runtime/mainnet/src/weights/ 21 | 22 | #![cfg_attr(rustfmt, rustfmt_skip)] 23 | #![allow(unused_parens)] 24 | #![allow(unused_imports)] 25 | #![allow(missing_docs)] 26 | 27 | use frame_support::{traits::Get, weights::Weight}; 28 | use core::marker::PhantomData; 29 | 30 | /// Weight functions for `cumulus_pallet_weight_reclaim`. 31 | pub struct WeightInfo(PhantomData); 32 | impl cumulus_pallet_weight_reclaim::WeightInfo for WeightInfo { 33 | /// Storage: `System::BlockWeight` (r:1 w:1) 34 | /// Proof: `System::BlockWeight` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) 35 | /// Storage: `System::ExtrinsicWeightReclaimed` (r:1 w:1) 36 | /// Proof: `System::ExtrinsicWeightReclaimed` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) 37 | /// Storage: `System::AllExtrinsicsLen` (r:1 w:0) 38 | /// Proof: `System::AllExtrinsicsLen` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) 39 | fn storage_weight_reclaim() -> Weight { 40 | // Proof Size summary in bytes: 41 | // Measured: `24` 42 | // Estimated: `1533` 43 | // Minimum execution time: 7_470_000 picoseconds. 44 | Weight::from_parts(7_695_000, 0) 45 | .saturating_add(Weight::from_parts(0, 1533)) 46 | .saturating_add(T::DbWeight::get().reads(3)) 47 | .saturating_add(T::DbWeight::get().writes(2)) 48 | } 49 | } -------------------------------------------------------------------------------- /runtime/common/src/weights/extrinsic_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | #![allow(unused_parens)] 19 | #![allow(unused_imports)] 20 | #![allow(missing_docs)] 21 | 22 | pub mod constants { 23 | use frame_support::{ 24 | parameter_types, 25 | weights::{constants, Weight}, 26 | }; 27 | 28 | parameter_types! { 29 | /// Executing a NO-OP `System::remarks` Extrinsic. 30 | pub const ExtrinsicBaseWeight: Weight = 31 | Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0); 32 | } 33 | 34 | #[cfg(test)] 35 | mod test_weights { 36 | use frame_support::weights::constants; 37 | 38 | /// Checks that the weight exists and is sane. 39 | // NOTE: If this test fails but you are sure that the generated values are fine, 40 | // you can delete it. 41 | #[test] 42 | fn sane() { 43 | let w = super::constants::ExtrinsicBaseWeight::get(); 44 | 45 | // At least 10 µs. 46 | assert!( 47 | w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS, 48 | "Weight should be at least 10 µs." 49 | ); 50 | // At most 1 ms. 51 | assert!( 52 | w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 53 | "Weight should be at most 1 ms." 54 | ); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /runtime/common/src/weights/frame_system_extensions.rs: -------------------------------------------------------------------------------- 1 | 2 | //! Autogenerated weights for `frame_system_extensions` 3 | //! 4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 46.0.0 5 | //! DATE: 2025-02-28, STEPS: `5`, REPEAT: `5`, LOW RANGE: `[]`, HIGH RANGE: `[]` 6 | //! WORST CASE MAP SIZE: `1000000` 7 | //! HOSTNAME: `tux`, CPU: `12th Gen Intel(R) Core(TM) i7-12700H` 8 | //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("pop")`, DB CACHE: `1024` 9 | 10 | // Executed Command: 11 | // ./target/release//pop-node 12 | // benchmark 13 | // pallet 14 | // --template=./scripts/templates/runtime-weight-template.hbs 15 | // --chain=pop 16 | // --wasm-execution=compiled 17 | // --pallet=frame_system_extensions 18 | // --extrinsic=* 19 | // --steps=5 20 | // --repeat=5 21 | // --output=./runtime/mainnet/src/weights/ 22 | 23 | #![cfg_attr(rustfmt, rustfmt_skip)] 24 | #![allow(unused_parens)] 25 | #![allow(unused_imports)] 26 | #![allow(missing_docs)] 27 | 28 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 29 | use core::marker::PhantomData; 30 | 31 | /// Weights for `frame_system_extensions`. 32 | pub struct WeightInfo(PhantomData); 33 | impl frame_system::ExtensionsWeightInfo for WeightInfo { 34 | fn check_genesis() -> Weight { 35 | // Proof Size summary in bytes: 36 | // Measured: `30` 37 | // Estimated: `0` 38 | // Minimum execution time: 4_271_000 picoseconds. 39 | Weight::from_parts(4_612_000, 0) 40 | } 41 | fn check_mortality_mortal_transaction() -> Weight { 42 | // Proof Size summary in bytes: 43 | // Measured: `68` 44 | // Estimated: `0` 45 | // Minimum execution time: 6_243_000 picoseconds. 46 | Weight::from_parts(6_285_000, 0) 47 | } 48 | fn check_mortality_immortal_transaction() -> Weight { 49 | // Proof Size summary in bytes: 50 | // Measured: `68` 51 | // Estimated: `0` 52 | // Minimum execution time: 6_142_000 picoseconds. 53 | Weight::from_parts(6_458_000, 0) 54 | } 55 | fn check_non_zero_sender() -> Weight { 56 | // Proof Size summary in bytes: 57 | // Measured: `0` 58 | // Estimated: `0` 59 | // Minimum execution time: 587_000 picoseconds. 60 | Weight::from_parts(621_000, 0) 61 | } 62 | /// Storage: `System::Account` (r:1 w:1) 63 | /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) 64 | fn check_nonce() -> Weight { 65 | // Proof Size summary in bytes: 66 | // Measured: `51` 67 | // Estimated: `3593` 68 | // Minimum execution time: 5_878_000 picoseconds. 69 | Weight::from_parts(6_322_000, 3593) 70 | .saturating_add(T::DbWeight::get().reads(1_u64)) 71 | .saturating_add(T::DbWeight::get().writes(1_u64)) 72 | } 73 | fn check_spec_version() -> Weight { 74 | // Proof Size summary in bytes: 75 | // Measured: `0` 76 | // Estimated: `0` 77 | // Minimum execution time: 455_000 picoseconds. 78 | Weight::from_parts(507_000, 0) 79 | } 80 | fn check_tx_version() -> Weight { 81 | // Proof Size summary in bytes: 82 | // Measured: `0` 83 | // Estimated: `0` 84 | // Minimum execution time: 463_000 picoseconds. 85 | Weight::from_parts(488_000, 0) 86 | } 87 | fn check_weight() -> Weight { 88 | // Proof Size summary in bytes: 89 | // Measured: `0` 90 | // Estimated: `0` 91 | // Minimum execution time: 3_409_000 picoseconds. 92 | Weight::from_parts(3_811_000, 0) 93 | } 94 | /// Storage: `System::ExtrinsicWeightReclaimed` (r:1 w:1) 95 | /// Proof: `System::ExtrinsicWeightReclaimed` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) 96 | /// Storage: `System::BlockWeight` (r:1 w:1) 97 | /// Proof: `System::BlockWeight` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) 98 | fn weight_reclaim() -> Weight { 99 | // Proof Size summary in bytes: 100 | // Measured: `0` 101 | // Estimated: `1533` 102 | // Minimum execution time: 4_890_000 picoseconds. 103 | Weight::from_parts(5_163_000, 0) 104 | .saturating_add(Weight::from_parts(0, 1533)) 105 | .saturating_add(T::DbWeight::get().reads(2)) 106 | .saturating_add(T::DbWeight::get().writes(2)) 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /runtime/common/src/weights/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | #![allow(unused_parens)] 19 | #![allow(unused_imports)] 20 | #![allow(missing_docs)] 21 | 22 | //! Expose the auto generated weight files. 23 | 24 | pub mod block_weights; 25 | pub mod cumulus_pallet_parachain_system; 26 | pub mod cumulus_pallet_weight_reclaim; 27 | pub mod cumulus_pallet_xcmp_queue; 28 | pub mod extrinsic_weights; 29 | pub mod frame_system; 30 | pub mod frame_system_extensions; 31 | pub mod pallet_assets; 32 | pub mod pallet_balances; 33 | pub mod pallet_collator_selection; 34 | pub mod pallet_collective; 35 | pub mod pallet_message_queue; 36 | pub mod pallet_migrations; 37 | pub mod pallet_motion; 38 | pub mod pallet_multisig; 39 | pub mod pallet_nfts; 40 | pub mod pallet_preimage; 41 | pub mod pallet_proxy; 42 | pub mod pallet_revive; 43 | pub mod pallet_scheduler; 44 | pub mod pallet_session; 45 | pub mod pallet_sudo; 46 | pub mod pallet_timestamp; 47 | pub mod pallet_transaction_payment; 48 | pub mod pallet_treasury; 49 | pub mod pallet_utility; 50 | pub mod pallet_xcm; 51 | pub mod paritydb_weights; 52 | pub mod rocksdb_weights; 53 | pub mod xcm; 54 | 55 | pub use block_weights::constants::BlockExecutionWeight; 56 | pub use extrinsic_weights::constants::ExtrinsicBaseWeight; 57 | pub use rocksdb_weights::constants::RocksDbWeight; 58 | -------------------------------------------------------------------------------- /runtime/common/src/weights/pallet_motion.rs: -------------------------------------------------------------------------------- 1 | 2 | //! Autogenerated weights for `pallet_motion` 3 | //! 4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 46.0.0 5 | //! DATE: 2025-03-04, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` 6 | //! WORST CASE MAP SIZE: `1000000` 7 | //! HOSTNAME: `tux`, CPU: `12th Gen Intel(R) Core(TM) i7-12700H` 8 | //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("pop")`, DB CACHE: 1024 9 | 10 | // Executed Command: 11 | // ./target/release/pop-node 12 | // benchmark 13 | // pallet 14 | // --chain 15 | // pop 16 | // --pallet=pallet_motion 17 | // --extrinsic=* 18 | // --output=./runtime/mainnet/src/weights 19 | 20 | #![cfg_attr(rustfmt, rustfmt_skip)] 21 | #![allow(unused_parens)] 22 | #![allow(unused_imports)] 23 | #![allow(missing_docs)] 24 | 25 | use frame_support::{traits::Get, weights::Weight}; 26 | use core::marker::PhantomData; 27 | 28 | /// Weight functions for `pallet_motion`. 29 | pub struct WeightInfo(PhantomData); 30 | impl pallet_motion::WeightInfo for WeightInfo { 31 | fn simple_majority() -> Weight { 32 | // Proof Size summary in bytes: 33 | // Measured: `0` 34 | // Estimated: `0` 35 | // Minimum execution time: 6_093_000 picoseconds. 36 | Weight::from_parts(6_399_000, 0) 37 | .saturating_add(Weight::from_parts(0, 0)) 38 | } 39 | fn super_majority() -> Weight { 40 | // Proof Size summary in bytes: 41 | // Measured: `0` 42 | // Estimated: `0` 43 | // Minimum execution time: 5_872_000 picoseconds. 44 | Weight::from_parts(6_181_000, 0) 45 | .saturating_add(Weight::from_parts(0, 0)) 46 | } 47 | fn unanimous() -> Weight { 48 | // Proof Size summary in bytes: 49 | // Measured: `0` 50 | // Estimated: `0` 51 | // Minimum execution time: 5_932_000 picoseconds. 52 | Weight::from_parts(6_406_000, 0) 53 | .saturating_add(Weight::from_parts(0, 0)) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /runtime/common/src/weights/pallet_session.rs: -------------------------------------------------------------------------------- 1 | 2 | //! Autogenerated weights for `pallet_session` 3 | //! 4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 46.0.0 5 | //! DATE: 2025-02-28, STEPS: `5`, REPEAT: `5`, LOW RANGE: `[]`, HIGH RANGE: `[]` 6 | //! WORST CASE MAP SIZE: `1000000` 7 | //! HOSTNAME: `tux`, CPU: `12th Gen Intel(R) Core(TM) i7-12700H` 8 | //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("pop")`, DB CACHE: `1024` 9 | 10 | // Executed Command: 11 | // ./target/release//pop-node 12 | // benchmark 13 | // pallet 14 | // --template=./scripts/templates/runtime-weight-template.hbs 15 | // --chain=pop 16 | // --wasm-execution=compiled 17 | // --pallet=pallet_session 18 | // --extrinsic=* 19 | // --steps=5 20 | // --repeat=5 21 | // --output=./runtime/mainnet/src/weights/ 22 | 23 | #![cfg_attr(rustfmt, rustfmt_skip)] 24 | #![allow(unused_parens)] 25 | #![allow(unused_imports)] 26 | #![allow(missing_docs)] 27 | 28 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 29 | use core::marker::PhantomData; 30 | 31 | /// Weights for `pallet_session`. 32 | pub struct WeightInfo(PhantomData); 33 | impl pallet_session::WeightInfo for WeightInfo { 34 | /// Storage: `Session::NextKeys` (r:1 w:1) 35 | /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) 36 | /// Storage: `Session::KeyOwner` (r:1 w:1) 37 | /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) 38 | fn set_keys() -> Weight { 39 | // Proof Size summary in bytes: 40 | // Measured: `271` 41 | // Estimated: `3736` 42 | // Minimum execution time: 19_107_000 picoseconds. 43 | Weight::from_parts(19_333_000, 3736) 44 | .saturating_add(T::DbWeight::get().reads(2_u64)) 45 | .saturating_add(T::DbWeight::get().writes(2_u64)) 46 | } 47 | /// Storage: `Session::NextKeys` (r:1 w:1) 48 | /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) 49 | /// Storage: `Session::KeyOwner` (r:0 w:1) 50 | /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) 51 | fn purge_keys() -> Weight { 52 | // Proof Size summary in bytes: 53 | // Measured: `243` 54 | // Estimated: `3708` 55 | // Minimum execution time: 13_144_000 picoseconds. 56 | Weight::from_parts(13_843_000, 3708) 57 | .saturating_add(T::DbWeight::get().reads(1_u64)) 58 | .saturating_add(T::DbWeight::get().writes(2_u64)) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /runtime/common/src/weights/pallet_sudo.rs: -------------------------------------------------------------------------------- 1 | 2 | //! Autogenerated weights for `pallet_sudo` 3 | //! 4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 46.0.0 5 | //! DATE: 2025-02-28, STEPS: `5`, REPEAT: `5`, LOW RANGE: `[]`, HIGH RANGE: `[]` 6 | //! WORST CASE MAP SIZE: `1000000` 7 | //! HOSTNAME: `tux`, CPU: `12th Gen Intel(R) Core(TM) i7-12700H` 8 | //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("pop")`, DB CACHE: `1024` 9 | 10 | // Executed Command: 11 | // ./target/release//pop-node 12 | // benchmark 13 | // pallet 14 | // --template=./scripts/templates/runtime-weight-template.hbs 15 | // --chain=pop 16 | // --wasm-execution=compiled 17 | // --pallet=pallet_sudo 18 | // --extrinsic=* 19 | // --steps=5 20 | // --repeat=5 21 | // --output=./runtime/mainnet/src/weights/ 22 | 23 | #![cfg_attr(rustfmt, rustfmt_skip)] 24 | #![allow(unused_parens)] 25 | #![allow(unused_imports)] 26 | #![allow(missing_docs)] 27 | 28 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 29 | use core::marker::PhantomData; 30 | 31 | /// Weights for `pallet_sudo`. 32 | pub struct WeightInfo(PhantomData); 33 | impl pallet_sudo::WeightInfo for WeightInfo { 34 | /// Storage: `Sudo::Key` (r:1 w:1) 35 | /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) 36 | fn set_key() -> Weight { 37 | // Proof Size summary in bytes: 38 | // Measured: `98` 39 | // Estimated: `1517` 40 | // Minimum execution time: 10_692_000 picoseconds. 41 | Weight::from_parts(11_697_000, 1517) 42 | .saturating_add(T::DbWeight::get().reads(1_u64)) 43 | .saturating_add(T::DbWeight::get().writes(1_u64)) 44 | } 45 | /// Storage: `Sudo::Key` (r:1 w:0) 46 | /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) 47 | fn sudo() -> Weight { 48 | // Proof Size summary in bytes: 49 | // Measured: `98` 50 | // Estimated: `1517` 51 | // Minimum execution time: 10_888_000 picoseconds. 52 | Weight::from_parts(12_006_000, 1517) 53 | .saturating_add(T::DbWeight::get().reads(1_u64)) 54 | } 55 | /// Storage: `Sudo::Key` (r:1 w:0) 56 | /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) 57 | fn sudo_as() -> Weight { 58 | // Proof Size summary in bytes: 59 | // Measured: `98` 60 | // Estimated: `1517` 61 | // Minimum execution time: 10_313_000 picoseconds. 62 | Weight::from_parts(11_363_000, 1517) 63 | .saturating_add(T::DbWeight::get().reads(1_u64)) 64 | } 65 | /// Storage: `Sudo::Key` (r:1 w:1) 66 | /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) 67 | fn remove_key() -> Weight { 68 | // Proof Size summary in bytes: 69 | // Measured: `98` 70 | // Estimated: `1517` 71 | // Minimum execution time: 9_381_000 picoseconds. 72 | Weight::from_parts(9_571_000, 1517) 73 | .saturating_add(T::DbWeight::get().reads(1_u64)) 74 | .saturating_add(T::DbWeight::get().writes(1_u64)) 75 | } 76 | /// Storage: `Sudo::Key` (r:1 w:0) 77 | /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) 78 | fn check_only_sudo_account() -> Weight { 79 | // Proof Size summary in bytes: 80 | // Measured: `98` 81 | // Estimated: `1517` 82 | // Minimum execution time: 7_040_000 picoseconds. 83 | Weight::from_parts(7_287_000, 1517) 84 | .saturating_add(T::DbWeight::get().reads(1_u64)) 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /runtime/common/src/weights/pallet_timestamp.rs: -------------------------------------------------------------------------------- 1 | 2 | //! Autogenerated weights for `pallet_timestamp` 3 | //! 4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 46.0.0 5 | //! DATE: 2025-02-28, STEPS: `5`, REPEAT: `5`, LOW RANGE: `[]`, HIGH RANGE: `[]` 6 | //! WORST CASE MAP SIZE: `1000000` 7 | //! HOSTNAME: `tux`, CPU: `12th Gen Intel(R) Core(TM) i7-12700H` 8 | //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("pop")`, DB CACHE: `1024` 9 | 10 | // Executed Command: 11 | // ./target/release//pop-node 12 | // benchmark 13 | // pallet 14 | // --template=./scripts/templates/runtime-weight-template.hbs 15 | // --chain=pop 16 | // --wasm-execution=compiled 17 | // --pallet=pallet_timestamp 18 | // --extrinsic=* 19 | // --steps=5 20 | // --repeat=5 21 | // --output=./runtime/mainnet/src/weights/ 22 | 23 | #![cfg_attr(rustfmt, rustfmt_skip)] 24 | #![allow(unused_parens)] 25 | #![allow(unused_imports)] 26 | #![allow(missing_docs)] 27 | 28 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 29 | use core::marker::PhantomData; 30 | 31 | /// Weights for `pallet_timestamp`. 32 | pub struct WeightInfo(PhantomData); 33 | impl pallet_timestamp::WeightInfo for WeightInfo { 34 | /// Storage: `Timestamp::Now` (r:1 w:1) 35 | /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) 36 | /// Storage: `Aura::CurrentSlot` (r:1 w:0) 37 | /// Proof: `Aura::CurrentSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) 38 | fn set() -> Weight { 39 | // Proof Size summary in bytes: 40 | // Measured: `86` 41 | // Estimated: `1493` 42 | // Minimum execution time: 8_135_000 picoseconds. 43 | Weight::from_parts(10_865_000, 1493) 44 | .saturating_add(T::DbWeight::get().reads(2_u64)) 45 | .saturating_add(T::DbWeight::get().writes(1_u64)) 46 | } 47 | fn on_finalize() -> Weight { 48 | // Proof Size summary in bytes: 49 | // Measured: `57` 50 | // Estimated: `0` 51 | // Minimum execution time: 5_184_000 picoseconds. 52 | Weight::from_parts(5_829_000, 0) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /runtime/common/src/weights/pallet_transaction_payment.rs: -------------------------------------------------------------------------------- 1 | 2 | //! Autogenerated weights for `pallet_transaction_payment` 3 | //! 4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 46.0.0 5 | //! DATE: 2025-02-28, STEPS: `5`, REPEAT: `5`, LOW RANGE: `[]`, HIGH RANGE: `[]` 6 | //! WORST CASE MAP SIZE: `1000000` 7 | //! HOSTNAME: `tux`, CPU: `12th Gen Intel(R) Core(TM) i7-12700H` 8 | //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("pop")`, DB CACHE: `1024` 9 | 10 | // Executed Command: 11 | // ./target/release//pop-node 12 | // benchmark 13 | // pallet 14 | // --template=./scripts/templates/runtime-weight-template.hbs 15 | // --chain=pop 16 | // --wasm-execution=compiled 17 | // --pallet=pallet_transaction_payment 18 | // --extrinsic=* 19 | // --steps=5 20 | // --repeat=5 21 | // --output=./runtime/mainnet/src/weights/ 22 | 23 | #![cfg_attr(rustfmt, rustfmt_skip)] 24 | #![allow(unused_parens)] 25 | #![allow(unused_imports)] 26 | #![allow(missing_docs)] 27 | 28 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 29 | use core::marker::PhantomData; 30 | 31 | /// Weights for `pallet_transaction_payment`. 32 | pub struct WeightInfo(PhantomData); 33 | impl pallet_transaction_payment::WeightInfo for WeightInfo { 34 | /// Storage: `System::Account` (r:3 w:2) 35 | /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) 36 | fn charge_transaction_payment() -> Weight { 37 | // Proof Size summary in bytes: 38 | // Measured: `153` 39 | // Estimated: `8799` 40 | // Minimum execution time: 64_439_000 picoseconds. 41 | Weight::from_parts(68_512_000, 8799) 42 | .saturating_add(T::DbWeight::get().reads(3_u64)) 43 | .saturating_add(T::DbWeight::get().writes(2_u64)) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /runtime/common/src/weights/pallet_utility.rs: -------------------------------------------------------------------------------- 1 | 2 | //! Autogenerated weights for `pallet_utility` 3 | //! 4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 46.0.0 5 | //! DATE: 2025-02-28, STEPS: `5`, REPEAT: `5`, LOW RANGE: `[]`, HIGH RANGE: `[]` 6 | //! WORST CASE MAP SIZE: `1000000` 7 | //! HOSTNAME: `tux`, CPU: `12th Gen Intel(R) Core(TM) i7-12700H` 8 | //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("pop")`, DB CACHE: `1024` 9 | 10 | // Executed Command: 11 | // ./target/release//pop-node 12 | // benchmark 13 | // pallet 14 | // --template=./scripts/templates/runtime-weight-template.hbs 15 | // --chain=pop 16 | // --wasm-execution=compiled 17 | // --pallet=pallet_utility 18 | // --extrinsic=* 19 | // --steps=5 20 | // --repeat=5 21 | // --output=./runtime/mainnet/src/weights/ 22 | 23 | #![cfg_attr(rustfmt, rustfmt_skip)] 24 | #![allow(unused_parens)] 25 | #![allow(unused_imports)] 26 | #![allow(missing_docs)] 27 | 28 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 29 | use core::marker::PhantomData; 30 | 31 | /// Weights for `pallet_utility`. 32 | pub struct WeightInfo(PhantomData); 33 | impl pallet_utility::WeightInfo for WeightInfo { 34 | /// The range of component `c` is `[0, 1000]`. 35 | fn batch(c: u32, ) -> Weight { 36 | // Proof Size summary in bytes: 37 | // Measured: `0` 38 | // Estimated: `0` 39 | // Minimum execution time: 4_895_000 picoseconds. 40 | Weight::from_parts(5_185_000, 0) 41 | // Standard Error: 36_519 42 | .saturating_add(Weight::from_parts(3_130_612, 0).saturating_mul(c.into())) 43 | } 44 | fn as_derivative() -> Weight { 45 | // Proof Size summary in bytes: 46 | // Measured: `0` 47 | // Estimated: `0` 48 | // Minimum execution time: 4_149_000 picoseconds. 49 | Weight::from_parts(4_209_000, 0) 50 | } 51 | /// The range of component `c` is `[0, 1000]`. 52 | fn batch_all(c: u32, ) -> Weight { 53 | // Proof Size summary in bytes: 54 | // Measured: `0` 55 | // Estimated: `0` 56 | // Minimum execution time: 4_614_000 picoseconds. 57 | Weight::from_parts(27_205_066, 0) 58 | // Standard Error: 49_136 59 | .saturating_add(Weight::from_parts(3_329_643, 0).saturating_mul(c.into())) 60 | } 61 | fn dispatch_as() -> Weight { 62 | // Proof Size summary in bytes: 63 | // Measured: `0` 64 | // Estimated: `0` 65 | // Minimum execution time: 6_633_000 picoseconds. 66 | Weight::from_parts(8_402_000, 0) 67 | } 68 | fn dispatch_as_fallible() -> Weight { 69 | // Proof Size summary in bytes: 70 | // Measured: `0` 71 | // Estimated: `0` 72 | // Minimum execution time: 6_848_000 picoseconds. 73 | Weight::from_parts(7_202_000, 0) 74 | .saturating_add(Weight::from_parts(0, 0)) 75 | } 76 | /// The range of component `c` is `[0, 1000]`. 77 | fn force_batch(c: u32, ) -> Weight { 78 | // Proof Size summary in bytes: 79 | // Measured: `0` 80 | // Estimated: `0` 81 | // Minimum execution time: 4_816_000 picoseconds. 82 | Weight::from_parts(433_933, 0) 83 | // Standard Error: 60_315 84 | .saturating_add(Weight::from_parts(3_128_533, 0).saturating_mul(c.into())) 85 | } 86 | fn if_else() -> Weight { 87 | // Proof Size summary in bytes: 88 | // Measured: `0` 89 | // Estimated: `0` 90 | // Minimum execution time: 6_000_000 picoseconds. 91 | Weight::from_parts(7_000_000, 0) 92 | .saturating_add(Weight::from_parts(0, 0)) 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /runtime/common/src/weights/paritydb_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | #![allow(unused_parens)] 19 | #![allow(unused_imports)] 20 | #![allow(missing_docs)] 21 | 22 | pub mod constants { 23 | use frame_support::{ 24 | parameter_types, 25 | weights::{constants, RuntimeDbWeight}, 26 | }; 27 | 28 | parameter_types! { 29 | /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights 30 | /// are available for brave runtime engineers who may want to try this out as default. 31 | pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { 32 | read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 33 | write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 34 | }; 35 | } 36 | 37 | #[cfg(test)] 38 | mod test_db_weights { 39 | use frame_support::weights::constants; 40 | 41 | use super::constants::ParityDbWeight as W; 42 | 43 | /// Checks that all weights exist and have sane values. 44 | // NOTE: If this test fails but you are sure that the generated values are fine, 45 | // you can delete it. 46 | #[test] 47 | fn sane() { 48 | // At least 1 µs. 49 | assert!( 50 | W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 51 | "Read weight should be at least 1 µs." 52 | ); 53 | assert!( 54 | W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 55 | "Write weight should be at least 1 µs." 56 | ); 57 | // At most 1 ms. 58 | assert!( 59 | W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 60 | "Read weight should be at most 1 ms." 61 | ); 62 | assert!( 63 | W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 64 | "Write weight should be at most 1 ms." 65 | ); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /runtime/common/src/weights/rocksdb_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | #![allow(unused_parens)] 19 | #![allow(unused_imports)] 20 | #![allow(missing_docs)] 21 | 22 | pub mod constants { 23 | use frame_support::{ 24 | parameter_types, 25 | weights::{constants, RuntimeDbWeight}, 26 | }; 27 | 28 | parameter_types! { 29 | /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout 30 | /// the runtime. 31 | pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { 32 | read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 33 | write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 34 | }; 35 | } 36 | 37 | #[cfg(test)] 38 | mod test_db_weights { 39 | use frame_support::weights::constants; 40 | 41 | use super::constants::RocksDbWeight as W; 42 | 43 | /// Checks that all weights exist and have sane values. 44 | // NOTE: If this test fails but you are sure that the generated values are fine, 45 | // you can delete it. 46 | #[test] 47 | fn sane() { 48 | // At least 1 µs. 49 | assert!( 50 | W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 51 | "Read weight should be at least 1 µs." 52 | ); 53 | assert!( 54 | W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 55 | "Write weight should be at least 1 µs." 56 | ); 57 | // At most 1 ms. 58 | assert!( 59 | W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 60 | "Read weight should be at most 1 ms." 61 | ); 62 | assert!( 63 | W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 64 | "Write weight should be at most 1 ms." 65 | ); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /runtime/common/src/weights/xcm/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod pallet_xcm_benchmarks_fungible; 2 | pub mod pallet_xcm_benchmarks_generic; 3 | -------------------------------------------------------------------------------- /runtime/devnet/build.rs: -------------------------------------------------------------------------------- 1 | #[cfg(all(feature = "std", feature = "metadata-hash"))] 2 | fn main() { 3 | substrate_wasm_builder::WasmBuilder::init_with_defaults() 4 | .enable_metadata_hash("PAS", 10) 5 | .build() 6 | } 7 | 8 | #[cfg(all(feature = "std", not(feature = "metadata-hash")))] 9 | fn main() { 10 | substrate_wasm_builder::WasmBuilder::build_using_defaults() 11 | } 12 | 13 | /// The wasm builder is deactivated when compiling 14 | /// this crate for wasm to speed up the compilation. 15 | #[cfg(not(feature = "std"))] 16 | fn main() {} 17 | -------------------------------------------------------------------------------- /runtime/devnet/src/config/ismp.rs: -------------------------------------------------------------------------------- 1 | use alloc::{boxed::Box, vec::Vec}; 2 | 3 | use frame_support::traits::Get; 4 | use frame_system::EnsureRoot; 5 | use ismp::{host::StateMachine, module::IsmpModule, router::IsmpRouter}; 6 | use ismp_parachain::ParachainConsensusClient; 7 | 8 | use crate::{ 9 | AccountId, Balance, Balances, Ismp, IsmpParachain, ParachainInfo, Runtime, RuntimeEvent, 10 | Timestamp, 11 | }; 12 | 13 | impl pallet_ismp::Config for Runtime { 14 | type AdminOrigin = EnsureRoot; 15 | type Balance = Balance; 16 | type ConsensusClients = (ParachainConsensusClient,); 17 | type Coprocessor = Coprocessor; 18 | type Currency = Balances; 19 | type HostStateMachine = HostStateMachine; 20 | type OffchainDB = (); 21 | type Router = Router; 22 | type RuntimeEvent = RuntimeEvent; 23 | type TimestampProvider = Timestamp; 24 | type WeightProvider = (); 25 | } 26 | 27 | impl ismp_parachain::Config for Runtime { 28 | type IsmpHost = Ismp; 29 | type RuntimeEvent = RuntimeEvent; 30 | } 31 | 32 | pub struct Coprocessor; 33 | impl Get> for Coprocessor { 34 | fn get() -> Option { 35 | Some(HostStateMachine::get()) 36 | } 37 | } 38 | 39 | pub struct HostStateMachine; 40 | impl Get for HostStateMachine { 41 | fn get() -> StateMachine { 42 | StateMachine::Polkadot(ParachainInfo::get().into()) 43 | } 44 | } 45 | 46 | #[derive(Default)] 47 | pub struct Router; 48 | impl IsmpRouter for Router { 49 | fn module_for_id(&self, id: Vec) -> Result, anyhow::Error> { 50 | Err(anyhow::anyhow!("Module not found: {:?}", id)) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /runtime/devnet/src/config/mod.rs: -------------------------------------------------------------------------------- 1 | mod api; 2 | // Public due to pop api integration tests crate. 3 | pub mod assets; 4 | mod contracts; 5 | mod ismp; 6 | mod proxy; 7 | // Public due to integration tests crate. 8 | pub mod xcm; 9 | -------------------------------------------------------------------------------- /runtime/devnet/src/weights/block_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, Weight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// Importing a block with 0 Extrinsics. 26 | pub const BlockExecutionWeight: Weight = 27 | Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0); 28 | } 29 | 30 | #[cfg(test)] 31 | mod test_weights { 32 | use frame_support::weights::constants; 33 | 34 | /// Checks that the weight exists and is sane. 35 | // NOTE: If this test fails but you are sure that the generated values are fine, 36 | // you can delete it. 37 | #[test] 38 | fn sane() { 39 | let w = super::constants::BlockExecutionWeight::get(); 40 | 41 | // At least 100 µs. 42 | assert!( 43 | w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS, 44 | "Weight should be at least 100 µs." 45 | ); 46 | // At most 50 ms. 47 | assert!( 48 | w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS, 49 | "Weight should be at most 50 ms." 50 | ); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /runtime/devnet/src/weights/extrinsic_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, Weight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// Executing a NO-OP `System::remarks` Extrinsic. 26 | pub const ExtrinsicBaseWeight: Weight = 27 | Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0); 28 | } 29 | 30 | #[cfg(test)] 31 | mod test_weights { 32 | use frame_support::weights::constants; 33 | 34 | /// Checks that the weight exists and is sane. 35 | // NOTE: If this test fails but you are sure that the generated values are fine, 36 | // you can delete it. 37 | #[test] 38 | fn sane() { 39 | let w = super::constants::ExtrinsicBaseWeight::get(); 40 | 41 | // At least 10 µs. 42 | assert!( 43 | w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS, 44 | "Weight should be at least 10 µs." 45 | ); 46 | // At most 1 ms. 47 | assert!( 48 | w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 49 | "Weight should be at most 1 ms." 50 | ); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /runtime/devnet/src/weights/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | //! Expose the auto generated weight files. 19 | 20 | pub mod block_weights; 21 | pub mod extrinsic_weights; 22 | pub mod paritydb_weights; 23 | pub mod rocksdb_weights; 24 | 25 | pub use block_weights::constants::BlockExecutionWeight; 26 | pub use extrinsic_weights::constants::ExtrinsicBaseWeight; 27 | pub use rocksdb_weights::constants::RocksDbWeight; 28 | -------------------------------------------------------------------------------- /runtime/devnet/src/weights/paritydb_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, RuntimeDbWeight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights 26 | /// are available for brave runtime engineers who may want to try this out as default. 27 | pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { 28 | read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 29 | write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 30 | }; 31 | } 32 | 33 | #[cfg(test)] 34 | mod test_db_weights { 35 | use frame_support::weights::constants; 36 | 37 | use super::constants::ParityDbWeight as W; 38 | 39 | /// Checks that all weights exist and have sane values. 40 | // NOTE: If this test fails but you are sure that the generated values are fine, 41 | // you can delete it. 42 | #[test] 43 | fn sane() { 44 | // At least 1 µs. 45 | assert!( 46 | W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 47 | "Read weight should be at least 1 µs." 48 | ); 49 | assert!( 50 | W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 51 | "Write weight should be at least 1 µs." 52 | ); 53 | // At most 1 ms. 54 | assert!( 55 | W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 56 | "Read weight should be at most 1 ms." 57 | ); 58 | assert!( 59 | W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 60 | "Write weight should be at most 1 ms." 61 | ); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /runtime/devnet/src/weights/rocksdb_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, RuntimeDbWeight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout 26 | /// the runtime. 27 | pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { 28 | read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 29 | write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 30 | }; 31 | } 32 | 33 | #[cfg(test)] 34 | mod test_db_weights { 35 | use frame_support::weights::constants; 36 | 37 | use super::constants::RocksDbWeight as W; 38 | 39 | /// Checks that all weights exist and have sane values. 40 | // NOTE: If this test fails but you are sure that the generated values are fine, 41 | // you can delete it. 42 | #[test] 43 | fn sane() { 44 | // At least 1 µs. 45 | assert!( 46 | W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 47 | "Read weight should be at least 1 µs." 48 | ); 49 | assert!( 50 | W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 51 | "Write weight should be at least 1 µs." 52 | ); 53 | // At most 1 ms. 54 | assert!( 55 | W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 56 | "Read weight should be at most 1 ms." 57 | ); 58 | assert!( 59 | W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 60 | "Write weight should be at most 1 ms." 61 | ); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /runtime/mainnet/build.rs: -------------------------------------------------------------------------------- 1 | #[cfg(all(feature = "std", feature = "metadata-hash"))] 2 | fn main() { 3 | substrate_wasm_builder::WasmBuilder::init_with_defaults() 4 | .enable_metadata_hash("DOT", 10) 5 | .build() 6 | } 7 | 8 | #[cfg(all(feature = "std", not(feature = "metadata-hash")))] 9 | fn main() { 10 | substrate_wasm_builder::WasmBuilder::build_using_defaults() 11 | } 12 | 13 | /// The wasm builder is deactivated when compiling 14 | /// this crate for wasm to speed up the compilation. 15 | #[cfg(not(feature = "std"))] 16 | fn main() {} 17 | -------------------------------------------------------------------------------- /runtime/mainnet/src/config/mod.rs: -------------------------------------------------------------------------------- 1 | // Assets. 2 | pub(crate) mod assets; 3 | // Collation. 4 | pub(crate) mod collation; 5 | /// Governance. 6 | pub mod governance; 7 | /// Monetary matters. 8 | pub(crate) mod monetary; 9 | /// Proxy. 10 | pub(crate) mod proxy; 11 | /// System functionality. 12 | pub mod system; 13 | // Revive. 14 | mod revive; 15 | // Utility. 16 | mod utility; 17 | /// XCM. 18 | pub mod xcm; 19 | mod xcm_weights; 20 | -------------------------------------------------------------------------------- /runtime/testnet/build.rs: -------------------------------------------------------------------------------- 1 | #[cfg(all(feature = "std", feature = "metadata-hash"))] 2 | fn main() { 3 | substrate_wasm_builder::WasmBuilder::init_with_defaults() 4 | .enable_metadata_hash("PAS", 10) 5 | .build() 6 | } 7 | 8 | #[cfg(all(feature = "std", not(feature = "metadata-hash")))] 9 | fn main() { 10 | substrate_wasm_builder::WasmBuilder::build_using_defaults() 11 | } 12 | 13 | /// The wasm builder is deactivated when compiling 14 | /// this crate for wasm to speed up the compilation. 15 | #[cfg(not(feature = "std"))] 16 | fn main() {} 17 | -------------------------------------------------------------------------------- /runtime/testnet/src/config/collation.rs: -------------------------------------------------------------------------------- 1 | use pallet_xcm::{EnsureXcm, IsVoiceOfBody}; 2 | use pop_runtime_common::{HOURS, SLOT_DURATION}; 3 | 4 | use crate::{ 5 | config::xcm::RelayLocation, parameter_types, AccountId, Aura, AuraId, Balances, BlockNumber, 6 | BodyId, CollatorSelection, ConstBool, ConstU32, ConstU64, EitherOfDiverse, EnsureRoot, 7 | PalletId, Runtime, RuntimeEvent, Session, SessionKeys, 8 | }; 9 | 10 | impl pallet_authorship::Config for Runtime { 11 | type EventHandler = (CollatorSelection,); 12 | type FindAuthor = pallet_session::FindAccountFromAuthorIndex; 13 | } 14 | 15 | #[docify::export(aura_config)] 16 | impl pallet_aura::Config for Runtime { 17 | type AllowMultipleBlocksPerSlot = ConstBool; 18 | type AuthorityId = AuraId; 19 | type DisabledValidators = (); 20 | type MaxAuthorities = ConstU32<100_000>; 21 | type SlotDuration = ConstU64; 22 | } 23 | 24 | parameter_types! { 25 | pub const PotId: PalletId = PalletId(*b"PotStake"); 26 | pub const SessionLength: BlockNumber = 6 * HOURS; 27 | // StakingAdmin pluralistic body. 28 | pub const StakingAdminBodyId: BodyId = BodyId::Defense; 29 | } 30 | 31 | /// We allow root and the StakingAdmin to execute privileged collator selection operations. 32 | pub type CollatorSelectionUpdateOrigin = EitherOfDiverse< 33 | EnsureRoot, 34 | EnsureXcm>, 35 | >; 36 | 37 | impl pallet_collator_selection::Config for Runtime { 38 | type Currency = Balances; 39 | // should be a multiple of session or things will get inconsistent 40 | type KickThreshold = Period; 41 | type MaxCandidates = ConstU32<100>; 42 | type MaxInvulnerables = ConstU32<20>; 43 | type MinEligibleCollators = ConstU32<4>; 44 | type PotId = PotId; 45 | type RuntimeEvent = RuntimeEvent; 46 | type UpdateOrigin = CollatorSelectionUpdateOrigin; 47 | type ValidatorId = ::AccountId; 48 | type ValidatorIdOf = pallet_collator_selection::IdentityCollator; 49 | type ValidatorRegistration = Session; 50 | type WeightInfo = (); 51 | } 52 | 53 | impl cumulus_pallet_aura_ext::Config for Runtime {} 54 | 55 | parameter_types! { 56 | pub const Period: u32 = 6 * HOURS; 57 | pub const Offset: u32 = 0; 58 | } 59 | 60 | impl pallet_session::Config for Runtime { 61 | type DisablingStrategy = (); 62 | type Keys = SessionKeys; 63 | type NextSessionRotation = pallet_session::PeriodicSessions; 64 | type RuntimeEvent = RuntimeEvent; 65 | // Essentially just Aura, but let's be pedantic. 66 | type SessionHandler = ::KeyTypeIdProviders; 67 | type SessionManager = CollatorSelection; 68 | type ShouldEndSession = pallet_session::PeriodicSessions; 69 | type ValidatorId = ::AccountId; 70 | // we don't have stash and controller, thus we don't need the convert as well. 71 | type ValidatorIdOf = pallet_collator_selection::IdentityCollator; 72 | type WeightInfo = (); 73 | } 74 | -------------------------------------------------------------------------------- /runtime/testnet/src/config/governance.rs: -------------------------------------------------------------------------------- 1 | use frame_support::{ 2 | parameter_types, 3 | traits::{EitherOfDiverse, NeverEnsureOrigin}, 4 | }; 5 | use frame_system::EnsureRoot; 6 | use pallet_collective::EnsureProportionAtLeast; 7 | use sp_core::crypto::Ss58Codec; 8 | 9 | use crate::{ 10 | config::system::RuntimeBlockWeights, AccountId, BlockNumber, Runtime, RuntimeCall, 11 | RuntimeEvent, RuntimeOrigin, Weight, DAYS, 12 | }; 13 | 14 | // Type aliases for council origins. 15 | type AtLeastThreeFourthsOfCouncil = EitherOfDiverse< 16 | EnsureRoot, 17 | EnsureProportionAtLeast, 18 | >; 19 | type UnanimousCouncilVote = EitherOfDiverse< 20 | EnsureRoot, 21 | EnsureProportionAtLeast, 22 | >; 23 | 24 | /// SUDO account set at genesis. 25 | const SUDO_ADDRESS: &str = "5FPL3ZLqUk6MyBoZrQZ1Co29WAteX6T6N68TZ6jitHvhpyuD"; 26 | 27 | parameter_types! { 28 | pub CouncilMotionDuration: BlockNumber = 7 * DAYS; 29 | pub const CouncilMaxProposals: u32 = 100; 30 | pub const CouncilMaxMembers: u32 = 100; 31 | pub MaxProposalWeight: Weight = sp_runtime::Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block; 32 | pub SudoAddress: AccountId = AccountId::from_ss58check(SUDO_ADDRESS).expect("sudo address is valid SS58"); 33 | } 34 | 35 | pub type CouncilCollective = pallet_collective::Instance1; 36 | impl pallet_collective::Config for Runtime { 37 | type Consideration = (); 38 | type DefaultVote = pallet_collective::MoreThanMajorityThenPrimeDefaultVote; 39 | type DisapproveOrigin = EnsureRoot; 40 | type KillOrigin = EnsureRoot; 41 | type MaxMembers = CouncilMaxMembers; 42 | type MaxProposalWeight = MaxProposalWeight; 43 | type MaxProposals = CouncilMaxProposals; 44 | type MotionDuration = CouncilMotionDuration; 45 | type Proposal = RuntimeCall; 46 | type RuntimeEvent = RuntimeEvent; 47 | type RuntimeOrigin = RuntimeOrigin; 48 | type SetMembersOrigin = EnsureRoot; 49 | type WeightInfo = pallet_collective::weights::SubstrateWeight; 50 | } 51 | 52 | impl pallet_motion::Config for Runtime { 53 | type RuntimeCall = RuntimeCall; 54 | type RuntimeEvent = RuntimeEvent; 55 | // Simple majority is disabled. 56 | type SimpleMajorityOrigin = NeverEnsureOrigin<()>; 57 | // At least 3/4 of the council vote is needed. 58 | type SuperMajorityOrigin = AtLeastThreeFourthsOfCouncil; 59 | // A unanimous council vote is needed. 60 | type UnanimousOrigin = UnanimousCouncilVote; 61 | type WeightInfo = pallet_motion::weights::SubstrateWeight; 62 | } 63 | 64 | impl pallet_sudo::Config for Runtime { 65 | type RuntimeCall = RuntimeCall; 66 | type RuntimeEvent = RuntimeEvent; 67 | type WeightInfo = (); 68 | } 69 | -------------------------------------------------------------------------------- /runtime/testnet/src/config/ismp.rs: -------------------------------------------------------------------------------- 1 | use alloc::{boxed::Box, vec::Vec}; 2 | 3 | use frame_support::traits::Get; 4 | use frame_system::EnsureRoot; 5 | use ismp::{error::Error, host::StateMachine, module::IsmpModule, router::IsmpRouter}; 6 | use ismp_parachain::ParachainConsensusClient; 7 | 8 | use crate::{ 9 | AccountId, Balance, Balances, Ismp, IsmpParachain, ParachainInfo, Runtime, RuntimeEvent, 10 | Timestamp, 11 | }; 12 | 13 | impl pallet_ismp::Config for Runtime { 14 | type AdminOrigin = EnsureRoot; 15 | type Balance = Balance; 16 | type ConsensusClients = (ParachainConsensusClient,); 17 | type Coprocessor = Coprocessor; 18 | type Currency = Balances; 19 | type HostStateMachine = HostStateMachine; 20 | type OffchainDB = (); 21 | type Router = Router; 22 | type RuntimeEvent = RuntimeEvent; 23 | type TimestampProvider = Timestamp; 24 | type WeightProvider = (); 25 | } 26 | 27 | impl ismp_parachain::Config for Runtime { 28 | type IsmpHost = Ismp; 29 | type RuntimeEvent = RuntimeEvent; 30 | } 31 | 32 | pub struct Coprocessor; 33 | impl Get> for Coprocessor { 34 | fn get() -> Option { 35 | Some(HostStateMachine::get()) 36 | } 37 | } 38 | 39 | pub struct HostStateMachine; 40 | impl Get for HostStateMachine { 41 | fn get() -> StateMachine { 42 | StateMachine::Polkadot(ParachainInfo::get().into()) 43 | } 44 | } 45 | 46 | #[derive(Default)] 47 | pub struct Router; 48 | impl IsmpRouter for Router { 49 | fn module_for_id(&self, id: Vec) -> Result, anyhow::Error> { 50 | use pallet_api::messaging::transports::ismp::*; 51 | if id == ID { 52 | return Ok(Box::new(Handler::::new())); 53 | } 54 | Err(Error::ModuleNotFound(id))? 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /runtime/testnet/src/config/mod.rs: -------------------------------------------------------------------------------- 1 | mod api; 2 | // Public due to pop api integration tests crate. 3 | pub mod assets; 4 | // Collation. 5 | pub(crate) mod collation; 6 | // Contracts. 7 | mod contracts; 8 | /// Governance. 9 | pub mod governance; 10 | // Public due to pop api integration tests crate. 11 | /// Ismp. 12 | pub mod ismp; 13 | /// Monetary matters. 14 | pub(crate) mod monetary; 15 | /// Proxy. 16 | pub(crate) mod proxy; 17 | /// System functionality. 18 | pub mod system; 19 | // Utility. 20 | mod utility; 21 | // Public due to integration tests crate. 22 | /// XCM. 23 | pub mod xcm; 24 | -------------------------------------------------------------------------------- /runtime/testnet/src/config/utility.rs: -------------------------------------------------------------------------------- 1 | use frame_support::{ 2 | pallet_prelude::ConstU32, 3 | parameter_types, 4 | traits::{fungible::HoldConsideration, EqualPrivilegeOnly, LinearStoragePrice}, 5 | }; 6 | use frame_system::EnsureRoot; 7 | use parachains_common::Balance; 8 | 9 | use crate::{ 10 | config::system::RuntimeBlockWeights, deposit, AccountId, Balances, OriginCaller, Perbill, 11 | Preimage, Runtime, RuntimeCall, RuntimeEvent, RuntimeHoldReason, RuntimeOrigin, System, Weight, 12 | }; 13 | 14 | parameter_types! { 15 | // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. 16 | pub const DepositBase: Balance = deposit(1, 88); 17 | // Additional storage item size of 32 bytes. 18 | pub const DepositFactor: Balance = deposit(0, 32); 19 | pub const MaxSignatories: u32 = 100; 20 | } 21 | 22 | impl pallet_multisig::Config for Runtime { 23 | type BlockNumberProvider = System; 24 | type Currency = Balances; 25 | type DepositBase = DepositBase; 26 | type DepositFactor = DepositFactor; 27 | type MaxSignatories = MaxSignatories; 28 | type RuntimeCall = RuntimeCall; 29 | type RuntimeEvent = RuntimeEvent; 30 | type WeightInfo = pallet_multisig::weights::SubstrateWeight; 31 | } 32 | 33 | parameter_types! { 34 | pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage); 35 | pub const PreimageBaseDeposit: Balance = deposit(2, 64); 36 | pub const PreimageByteDeposit: Balance = deposit(0, 1); 37 | } 38 | 39 | impl pallet_preimage::Config for Runtime { 40 | type Consideration = HoldConsideration< 41 | AccountId, 42 | Balances, 43 | PreimageHoldReason, 44 | LinearStoragePrice, 45 | >; 46 | type Currency = Balances; 47 | type ManagerOrigin = EnsureRoot; 48 | type RuntimeEvent = RuntimeEvent; 49 | type WeightInfo = pallet_preimage::weights::SubstrateWeight; 50 | } 51 | 52 | parameter_types! { 53 | pub MaximumSchedulerWeight: Weight = Perbill::from_percent(60) * 54 | RuntimeBlockWeights::get().max_block; 55 | } 56 | 57 | impl pallet_scheduler::Config for Runtime { 58 | type BlockNumberProvider = System; 59 | #[cfg(feature = "runtime-benchmarks")] 60 | type MaxScheduledPerBlock = ConstU32<512>; 61 | #[cfg(not(feature = "runtime-benchmarks"))] 62 | type MaxScheduledPerBlock = ConstU32<50>; 63 | type MaximumWeight = MaximumSchedulerWeight; 64 | type OriginPrivilegeCmp = EqualPrivilegeOnly; 65 | type PalletsOrigin = OriginCaller; 66 | type Preimages = Preimage; 67 | type RuntimeCall = RuntimeCall; 68 | type RuntimeEvent = RuntimeEvent; 69 | type RuntimeOrigin = RuntimeOrigin; 70 | type ScheduleOrigin = EnsureRoot; 71 | type WeightInfo = pallet_scheduler::weights::SubstrateWeight; 72 | } 73 | 74 | impl pallet_utility::Config for Runtime { 75 | type PalletsOrigin = OriginCaller; 76 | type RuntimeCall = RuntimeCall; 77 | type RuntimeEvent = RuntimeEvent; 78 | type WeightInfo = pallet_utility::weights::SubstrateWeight; 79 | } 80 | -------------------------------------------------------------------------------- /runtime/testnet/src/weights/block_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, Weight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// Importing a block with 0 Extrinsics. 26 | pub const BlockExecutionWeight: Weight = 27 | Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0); 28 | } 29 | 30 | #[cfg(test)] 31 | mod test_weights { 32 | use frame_support::weights::constants; 33 | 34 | /// Checks that the weight exists and is sane. 35 | // NOTE: If this test fails but you are sure that the generated values are fine, 36 | // you can delete it. 37 | #[test] 38 | fn sane() { 39 | let w = super::constants::BlockExecutionWeight::get(); 40 | 41 | // At least 100 µs. 42 | assert!( 43 | w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS, 44 | "Weight should be at least 100 µs." 45 | ); 46 | // At most 50 ms. 47 | assert!( 48 | w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS, 49 | "Weight should be at most 50 ms." 50 | ); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /runtime/testnet/src/weights/extrinsic_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, Weight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// Executing a NO-OP `System::remarks` Extrinsic. 26 | pub const ExtrinsicBaseWeight: Weight = 27 | Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0); 28 | } 29 | 30 | #[cfg(test)] 31 | mod test_weights { 32 | use frame_support::weights::constants; 33 | 34 | /// Checks that the weight exists and is sane. 35 | // NOTE: If this test fails but you are sure that the generated values are fine, 36 | // you can delete it. 37 | #[test] 38 | fn sane() { 39 | let w = super::constants::ExtrinsicBaseWeight::get(); 40 | 41 | // At least 10 µs. 42 | assert!( 43 | w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS, 44 | "Weight should be at least 10 µs." 45 | ); 46 | // At most 1 ms. 47 | assert!( 48 | w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 49 | "Weight should be at most 1 ms." 50 | ); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /runtime/testnet/src/weights/mod.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | //! Expose the auto generated weight files. 19 | 20 | pub mod block_weights; 21 | pub mod extrinsic_weights; 22 | pub mod paritydb_weights; 23 | pub mod rocksdb_weights; 24 | 25 | pub use block_weights::constants::BlockExecutionWeight; 26 | pub use extrinsic_weights::constants::ExtrinsicBaseWeight; 27 | pub use rocksdb_weights::constants::RocksDbWeight; 28 | -------------------------------------------------------------------------------- /runtime/testnet/src/weights/paritydb_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, RuntimeDbWeight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights 26 | /// are available for brave runtime engineers who may want to try this out as default. 27 | pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { 28 | read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 29 | write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 30 | }; 31 | } 32 | 33 | #[cfg(test)] 34 | mod test_db_weights { 35 | use frame_support::weights::constants; 36 | 37 | use super::constants::ParityDbWeight as W; 38 | 39 | /// Checks that all weights exist and have sane values. 40 | // NOTE: If this test fails but you are sure that the generated values are fine, 41 | // you can delete it. 42 | #[test] 43 | fn sane() { 44 | // At least 1 µs. 45 | assert!( 46 | W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 47 | "Read weight should be at least 1 µs." 48 | ); 49 | assert!( 50 | W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 51 | "Write weight should be at least 1 µs." 52 | ); 53 | // At most 1 ms. 54 | assert!( 55 | W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 56 | "Read weight should be at most 1 ms." 57 | ); 58 | assert!( 59 | W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 60 | "Write weight should be at most 1 ms." 61 | ); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /runtime/testnet/src/weights/rocksdb_weights.rs: -------------------------------------------------------------------------------- 1 | // This file is part of Substrate. 2 | 3 | // Copyright (C) Parity Technologies (UK) Ltd. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | pub mod constants { 19 | use frame_support::{ 20 | parameter_types, 21 | weights::{constants, RuntimeDbWeight}, 22 | }; 23 | 24 | parameter_types! { 25 | /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout 26 | /// the runtime. 27 | pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { 28 | read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 29 | write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS, 30 | }; 31 | } 32 | 33 | #[cfg(test)] 34 | mod test_db_weights { 35 | use frame_support::weights::constants; 36 | 37 | use super::constants::RocksDbWeight as W; 38 | 39 | /// Checks that all weights exist and have sane values. 40 | // NOTE: If this test fails but you are sure that the generated values are fine, 41 | // you can delete it. 42 | #[test] 43 | fn sane() { 44 | // At least 1 µs. 45 | assert!( 46 | W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 47 | "Read weight should be at least 1 µs." 48 | ); 49 | assert!( 50 | W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, 51 | "Write weight should be at least 1 µs." 52 | ); 53 | // At most 1 ms. 54 | assert!( 55 | W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 56 | "Read weight should be at most 1 ms." 57 | ); 58 | assert!( 59 | W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, 60 | "Write weight should be at most 1 ms." 61 | ); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | # Release of Rust 1.87.0 introduced issues on CI making tests involving instantiation of wasm smart contracts fail. 3 | # Pinning version to stable 1.86 until resolved. 4 | channel = "1.86" 5 | components = [ "clippy", "llvm-tools-preview", "rust-src", "rustfmt" ] 6 | targets = [ "wasm32v1-none" ] 7 | -------------------------------------------------------------------------------- /scripts/benchmarks-ci.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # sourced from: https://github.com/paritytech/polkadot-sdk/blob/master/cumulus/scripts/benchmarks-ci.sh 4 | 5 | # Script takes 5 arguments as shown below: 6 | # - specName: Name of one of the available genesis presets. 7 | # - artifactsDir: Directory where pop-node is stored. 8 | # - steps: Number of steps to run during benchmarking. Default is 50. 9 | # - repeat: Number of repetitions to run during benchmarking. Default is 20. 10 | # 11 | # Example: 12 | # $ ./becnhmarks-ci.sh pop ./target/release/ 2 1 13 | 14 | # One of the available genesis presets. 15 | specName=$1 16 | # Used to source the pop-node binary. 17 | artifactsDir=$2 18 | # Optional number of steps. Default value is 50. 19 | steps=${3:-50} 20 | # Optional number of repetitions. Default value is 20. 21 | repeat=${4:-20} 22 | 23 | # Default output directory is the weights folder of the corresponding runtime. 24 | benchmarkOutput=./runtime/common/src/weights 25 | # Directory with all benchmarking templates. 26 | benchmarkTemplates="./scripts/templates" 27 | 28 | # Load all pallet names in an array. 29 | pallets=($( 30 | ${artifactsDir}/pop-node benchmark pallet --list --chain="${specName}" |\ 31 | tail -n+2 |\ 32 | cut -d',' -f1 |\ 33 | sort |\ 34 | uniq 35 | )) 36 | 37 | if [ ${#pallets[@]} -ne 0 ]; then 38 | echo "[+] Benchmarking ${#pallets[@]} pallets for runtime $runtime" 39 | else 40 | echo "pallet list not found in benchmarks-ci.sh" 41 | exit 1 42 | fi 43 | 44 | for pallet in ${pallets[@]} 45 | do 46 | output_dir="" 47 | extra_args="--template=$benchmarkTemplates/runtime-weight-template.hbs" 48 | extrinsic="--extrinsic=*" 49 | # A little hack for pallet_xcm_benchmarks - we want to force custom implementation for XcmWeightInfo. 50 | if [[ "$pallet" == "pallet_xcm_benchmarks::generic" ]] || [[ "$pallet" == "pallet_xcm_benchmarks::fungible" ]]; then 51 | output_dir="xcm/" 52 | extra_args="--template=$benchmarkTemplates/xcm-bench-template.hbs" 53 | fi 54 | if [[ "$pallet" == "pallet_xcm_benchmarks::generic" ]]; then 55 | # Exclude extrinsics that involved features not present in pop atm. 56 | # A custom configuration for runtime-benchmarks feature could be provided in the runtime for the relevant types otherwise. 57 | extrinsic="--extrinsic=report_holding,unpaid_execution,set_fees_mode,clear_topic,set_topic,clear_transact_status,report_transact_status,expect_pallet,query_pallet,expect_transact_status,expect_error,expect_origin,expect_asset,burn_asset,unsubscribe_version,subscribe_version,trap,claim_asset,report_error,clear_origin,execute_with_origin,descend_origin,clear_error,set_appendix,set_error_handler,refund_surplus,transact,query_response,asset_claimer,pay_fees,buy_execution,report_holding" 58 | fi 59 | $artifactsDir/pop-node benchmark pallet \ 60 | $extra_args \ 61 | --chain=$specName \ 62 | --wasm-execution=compiled \ 63 | --pallet=$pallet \ 64 | $extrinsic \ 65 | --steps=$steps \ 66 | --repeat=$repeat \ 67 | --output="${benchmarkOutput}/${output_dir}" 68 | done 69 | -------------------------------------------------------------------------------- /scripts/runtime-weight-template.hbs: -------------------------------------------------------------------------------- 1 | {{header}} 2 | //! Autogenerated weights for `{{pallet}}` 3 | //! 4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION {{version}} 5 | //! DATE: {{date}}, STEPS: `{{cmd.steps}}`, REPEAT: `{{cmd.repeat}}`, LOW RANGE: `{{cmd.lowest_range_values}}`, HIGH RANGE: `{{cmd.highest_range_values}}` 6 | //! WORST CASE MAP SIZE: `{{cmd.worst_case_map_values}}` 7 | //! HOSTNAME: `{{hostname}}`, CPU: `{{cpuname}}` 8 | //! WASM-EXECUTION: `{{cmd.wasm_execution}}`, CHAIN: `{{cmd.chain}}`, DB CACHE: `{{cmd.db_cache}}` 9 | 10 | // Executed Command: 11 | {{#each args as |arg|}} 12 | // {{arg}} 13 | {{/each}} 14 | 15 | #![cfg_attr(rustfmt, rustfmt_skip)] 16 | #![allow(unused_parens)] 17 | #![allow(unused_imports)] 18 | #![allow(missing_docs)] 19 | 20 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 21 | use sp_std::marker::PhantomData; 22 | 23 | /// Weights for `{{pallet}}`. 24 | pub struct WeightInfo(PhantomData); 25 | impl {{pallet}}::WeightInfo for WeightInfo { 26 | {{#each benchmarks as |benchmark|}} 27 | {{#each benchmark.comments as |comment|}} 28 | /// {{comment}} 29 | {{/each}} 30 | {{#each benchmark.component_ranges as |range|}} 31 | /// The range of component `{{range.name}}` is `[{{range.min}}, {{range.max}}]`. 32 | {{/each}} 33 | fn {{benchmark.name~}} 34 | ( 35 | {{~#each benchmark.components as |c| ~}} 36 | {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} 37 | ) -> Weight { 38 | // Proof Size summary in bytes: 39 | // Measured: `{{benchmark.base_recorded_proof_size}}{{#each benchmark.component_recorded_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}` 40 | // Estimated: `{{benchmark.base_calculated_proof_size}}{{#each benchmark.component_calculated_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}` 41 | // Minimum execution time: {{underscore benchmark.min_execution_time}}_000 picoseconds. 42 | Weight::from_parts({{underscore benchmark.base_weight}}, {{benchmark.base_calculated_proof_size}}) 43 | {{#each benchmark.component_weight as |cw|}} 44 | // Standard Error: {{underscore cw.error}} 45 | .saturating_add(Weight::from_parts({{underscore cw.slope}}, 0).saturating_mul({{cw.name}}.into())) 46 | {{/each}} 47 | {{#if (ne benchmark.base_reads "0")}} 48 | .saturating_add(T::DbWeight::get().reads({{benchmark.base_reads}}_u64)) 49 | {{/if}} 50 | {{#each benchmark.component_reads as |cr|}} 51 | .saturating_add(T::DbWeight::get().reads(({{cr.slope}}_u64).saturating_mul({{cr.name}}.into()))) 52 | {{/each}} 53 | {{#if (ne benchmark.base_writes "0")}} 54 | .saturating_add(T::DbWeight::get().writes({{benchmark.base_writes}}_u64)) 55 | {{/if}} 56 | {{#each benchmark.component_writes as |cw|}} 57 | .saturating_add(T::DbWeight::get().writes(({{cw.slope}}_u64).saturating_mul({{cw.name}}.into()))) 58 | {{/each}} 59 | {{#each benchmark.component_calculated_proof_size as |cp|}} 60 | .saturating_add(Weight::from_parts(0, {{cp.slope}}).saturating_mul({{cp.name}}.into())) 61 | {{/each}} 62 | } 63 | {{/each}} 64 | } 65 | -------------------------------------------------------------------------------- /scripts/templates/runtime-weight-template.hbs: -------------------------------------------------------------------------------- 1 | {{header}} 2 | //! Autogenerated weights for `{{pallet}}` 3 | //! 4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION {{version}} 5 | //! DATE: {{date}}, STEPS: `{{cmd.steps}}`, REPEAT: `{{cmd.repeat}}`, LOW RANGE: `{{cmd.lowest_range_values}}`, HIGH RANGE: `{{cmd.highest_range_values}}` 6 | //! WORST CASE MAP SIZE: `{{cmd.worst_case_map_values}}` 7 | //! HOSTNAME: `{{hostname}}`, CPU: `{{cpuname}}` 8 | //! WASM-EXECUTION: `{{cmd.wasm_execution}}`, CHAIN: `{{cmd.chain}}`, DB CACHE: `{{cmd.db_cache}}` 9 | 10 | // Executed Command: 11 | {{#each args as |arg|}} 12 | // {{arg}} 13 | {{/each}} 14 | 15 | #![cfg_attr(rustfmt, rustfmt_skip)] 16 | #![allow(unused_parens)] 17 | #![allow(unused_imports)] 18 | #![allow(missing_docs)] 19 | 20 | use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; 21 | use core::marker::PhantomData; 22 | 23 | /// Weights for `{{pallet}}`. 24 | pub struct WeightInfo(PhantomData); 25 | impl {{pallet}}::WeightInfo for WeightInfo { 26 | {{#each benchmarks as |benchmark|}} 27 | {{#each benchmark.comments as |comment|}} 28 | /// {{comment}} 29 | {{/each}} 30 | {{#each benchmark.component_ranges as |range|}} 31 | /// The range of component `{{range.name}}` is `[{{range.min}}, {{range.max}}]`. 32 | {{/each}} 33 | fn {{benchmark.name~}} 34 | ( 35 | {{~#each benchmark.components as |c| ~}} 36 | {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} 37 | ) -> Weight { 38 | // Proof Size summary in bytes: 39 | // Measured: `{{benchmark.base_recorded_proof_size}}{{#each benchmark.component_recorded_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}` 40 | // Estimated: `{{benchmark.base_calculated_proof_size}}{{#each benchmark.component_calculated_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}` 41 | // Minimum execution time: {{underscore benchmark.min_execution_time}}_000 picoseconds. 42 | Weight::from_parts({{underscore benchmark.base_weight}}, {{benchmark.base_calculated_proof_size}}) 43 | {{#each benchmark.component_weight as |cw|}} 44 | // Standard Error: {{underscore cw.error}} 45 | .saturating_add(Weight::from_parts({{underscore cw.slope}}, 0).saturating_mul({{cw.name}}.into())) 46 | {{/each}} 47 | {{#if (ne benchmark.base_reads "0")}} 48 | .saturating_add(T::DbWeight::get().reads({{benchmark.base_reads}}_u64)) 49 | {{/if}} 50 | {{#each benchmark.component_reads as |cr|}} 51 | .saturating_add(T::DbWeight::get().reads(({{cr.slope}}_u64).saturating_mul({{cr.name}}.into()))) 52 | {{/each}} 53 | {{#if (ne benchmark.base_writes "0")}} 54 | .saturating_add(T::DbWeight::get().writes({{benchmark.base_writes}}_u64)) 55 | {{/if}} 56 | {{#each benchmark.component_writes as |cw|}} 57 | .saturating_add(T::DbWeight::get().writes(({{cw.slope}}_u64).saturating_mul({{cw.name}}.into()))) 58 | {{/each}} 59 | {{#each benchmark.component_calculated_proof_size as |cp|}} 60 | .saturating_add(Weight::from_parts(0, {{cp.slope}}).saturating_mul({{cp.name}}.into())) 61 | {{/each}} 62 | } 63 | {{/each}} 64 | } 65 | -------------------------------------------------------------------------------- /scripts/templates/xcm-bench-template.hbs: -------------------------------------------------------------------------------- 1 | {{header}} 2 | //! Autogenerated weights for `{{pallet}}` 3 | //! 4 | //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION {{version}} 5 | //! DATE: {{date}}, STEPS: `{{cmd.steps}}`, REPEAT: `{{cmd.repeat}}`, LOW RANGE: `{{cmd.lowest_range_values}}`, HIGH RANGE: `{{cmd.highest_range_values}}` 6 | //! WORST CASE MAP SIZE: `{{cmd.worst_case_map_values}}` 7 | //! HOSTNAME: `{{hostname}}`, CPU: `{{cpuname}}` 8 | //! WASM-EXECUTION: {{cmd.wasm_execution}}, CHAIN: {{cmd.chain}}, DB CACHE: {{cmd.db_cache}} 9 | 10 | // Executed Command: 11 | {{#each args as |arg|}} 12 | // {{arg}} 13 | {{/each}} 14 | 15 | #![cfg_attr(rustfmt, rustfmt_skip)] 16 | #![allow(unused_parens)] 17 | #![allow(unused_imports)] 18 | 19 | use frame_support::{traits::Get, weights::Weight}; 20 | use core::marker::PhantomData; 21 | 22 | /// Weights for `{{pallet}}`. 23 | pub struct WeightInfo(PhantomData); 24 | impl WeightInfo { 25 | {{#each benchmarks as |benchmark|}} 26 | {{#each benchmark.comments as |comment|}} 27 | // {{comment}} 28 | {{/each}} 29 | {{#each benchmark.component_ranges as |range|}} 30 | /// The range of component `{{range.name}}` is `[{{range.min}}, {{range.max}}]`. 31 | {{/each}} 32 | pub fn {{benchmark.name~}} 33 | ( 34 | {{~#each benchmark.components as |c| ~}} 35 | {{~#if (not c.is_used)}}_{{/if}}{{c.name}}: u32, {{/each~}} 36 | ) -> Weight { 37 | // Proof Size summary in bytes: 38 | // Measured: `{{benchmark.base_recorded_proof_size}}{{#each benchmark.component_recorded_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}` 39 | // Estimated: `{{benchmark.base_calculated_proof_size}}{{#each benchmark.component_calculated_proof_size as |cp|}} + {{cp.name}} * ({{cp.slope}} ±{{underscore cp.error}}){{/each}}` 40 | // Minimum execution time: {{underscore benchmark.min_execution_time}}_000 picoseconds. 41 | Weight::from_parts({{underscore benchmark.base_weight}}, {{benchmark.base_calculated_proof_size}}) 42 | {{#each benchmark.component_weight as |cw|}} 43 | // Standard Error: {{underscore cw.error}} 44 | .saturating_add(Weight::from_parts({{underscore cw.slope}}, 0).saturating_mul({{cw.name}}.into())) 45 | {{/each}} 46 | {{#if (ne benchmark.base_reads "0")}} 47 | .saturating_add(T::DbWeight::get().reads({{benchmark.base_reads}})) 48 | {{/if}} 49 | {{#each benchmark.component_reads as |cr|}} 50 | .saturating_add(T::DbWeight::get().reads(({{cr.slope}}_u64).saturating_mul({{cr.name}}.into()))) 51 | {{/each}} 52 | {{#if (ne benchmark.base_writes "0")}} 53 | .saturating_add(T::DbWeight::get().writes({{benchmark.base_writes}})) 54 | {{/if}} 55 | {{#each benchmark.component_writes as |cw|}} 56 | .saturating_add(T::DbWeight::get().writes(({{cw.slope}}_u64).saturating_mul({{cw.name}}.into()))) 57 | {{/each}} 58 | {{#each benchmark.component_calculated_proof_size as |cp|}} 59 | .saturating_add(Weight::from_parts(0, {{cp.slope}}).saturating_mul({{cp.name}}.into())) 60 | {{/each}} 61 | } 62 | {{/each}} 63 | } 64 | -------------------------------------------------------------------------------- /tests/contracts/filtered-call/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore build artifacts from the local tests sub-crate. 2 | /target/ 3 | 4 | # Ignore backup files creates by cargo fmt. 5 | **/*.rs.bk 6 | 7 | # Remove Cargo.lock when creating an executable, leave it for libraries 8 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 9 | Cargo.lock 10 | -------------------------------------------------------------------------------- /tests/contracts/filtered-call/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2021" 3 | name = "pop_api_filtered_call" 4 | 5 | [dependencies] 6 | ink = { version = "5.0.0", default-features = false } 7 | scale = { package = "parity-scale-codec", version = "3", default-features = false, features = [ "derive" ] } 8 | scale-info = { version = "2.6", default-features = false, features = [ "derive" ], optional = true } 9 | 10 | [lib] 11 | path = "lib.rs" 12 | 13 | [features] 14 | default = [ "std" ] 15 | e2e-tests = [ ] 16 | ink-as-dependency = [ ] 17 | std = [ 18 | "ink/std", 19 | "scale-info/std", 20 | "scale/std", 21 | ] 22 | -------------------------------------------------------------------------------- /tests/contracts/filtered-call/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(feature = "std"), no_std, no_main)] 2 | 3 | /// This is an example contract used for unit testing purposes. 4 | /// It is intended to ensure that the call filter for the Pop API chain 5 | /// extension works as expected. 6 | /// An Ok(()) returned from `get_filtered` means that the filter successfully 7 | /// BLOCKED the call. An Err() means that the filter did not block the call, 8 | /// which is incorrect behavior. 9 | /// The pop-api crate is not used because it does not support invalid calls ;) 10 | use scale::Encode; 11 | 12 | use ink::{env::Environment, prelude::vec::Vec}; 13 | 14 | // public visibility required as contract messages are required to be public 15 | #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] 16 | #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] 17 | pub enum ContractError { 18 | CallWasNotFiltered, 19 | } 20 | 21 | #[derive(Encode)] 22 | pub(crate) enum SystemCalls { 23 | #[codec(index = 0)] 24 | Remark { remark: Vec }, 25 | } 26 | #[derive(scale::Encode)] 27 | pub(crate) enum RuntimeCall { 28 | #[codec(index = 0)] 29 | System(SystemCalls), 30 | } 31 | 32 | pub type Result = core::result::Result; 33 | 34 | // chain extensions require public visibility. 35 | #[ink::chain_extension(extension = 909)] 36 | pub trait MyPopApi { 37 | type ErrorCode = ContractError; 38 | #[ink(function = 0)] 39 | #[allow(private_interfaces)] 40 | fn dispatch(call: RuntimeCall) -> Result<()>; 41 | } 42 | 43 | impl From for ContractError { 44 | fn from(_: ink::scale::Error) -> Self { 45 | panic!("encountered unexpected invalid SCALE encoding") 46 | } 47 | } 48 | 49 | impl ink::env::chain_extension::FromStatusCode for ContractError { 50 | fn from_status_code(status_code: u32) -> core::result::Result<(), Self> { 51 | ink::env::debug_println!("get_filtered status_code: {:?}", status_code); 52 | match status_code { 53 | 0 => Err(Self::CallWasNotFiltered), 54 | // CallFiltered originates from `frame_system` with pallet-index 0. The CallFiltered error is at index 5. 55 | // If this ever changes, this test will fail and the appropriate mapping can be made. 56 | 5 => Ok(()), 57 | _ => panic!("encountered unknown status code"), 58 | } 59 | } 60 | } 61 | 62 | #[derive(Debug, Clone, PartialEq, Eq)] 63 | #[ink::scale_derive(TypeInfo)] 64 | pub enum CustomEnvironment {} 65 | impl Environment for CustomEnvironment { 66 | const MAX_EVENT_TOPICS: usize = ::MAX_EVENT_TOPICS; 67 | 68 | type AccountId = ::AccountId; 69 | type Balance = ::Balance; 70 | type Hash = ::Hash; 71 | type Timestamp = ::Timestamp; 72 | type BlockNumber = ::BlockNumber; 73 | 74 | type ChainExtension = crate::MyPopApi; 75 | } 76 | 77 | #[ink::contract(env = crate::CustomEnvironment)] 78 | mod pop_api_filtered_call { 79 | use super::{ContractError, RuntimeCall, SystemCalls, Vec}; 80 | #[ink(storage)] 81 | #[derive(Default)] 82 | pub struct PopApiFilteredCall; 83 | 84 | impl PopApiFilteredCall { 85 | #[ink(constructor, payable)] 86 | pub fn new() -> Self { 87 | ink::env::debug_println!("Contract::new"); 88 | Default::default() 89 | } 90 | 91 | // Calls Pop API chain extension with non-allowed call. 92 | // If Ok(()) is returned the filter correctly blocked the call. 93 | #[ink(message)] 94 | pub fn get_filtered(&mut self) -> Result<(), ContractError> { 95 | ink::env::debug_println!("Contract::get_filtered"); 96 | 97 | let blocked_call = 98 | RuntimeCall::System(SystemCalls::Remark { remark: Vec::from([0u8; 8]) }); 99 | let res = self.env().extension().dispatch(blocked_call); 100 | 101 | ink::env::debug_println!("Contract::get_filtered res {:?}", res); 102 | 103 | res 104 | } 105 | } 106 | 107 | #[cfg(test)] 108 | mod tests { 109 | use super::*; 110 | 111 | #[ink::test] 112 | fn default_works() { 113 | PopApiFilteredCall::new(); 114 | } 115 | } 116 | } 117 | --------------------------------------------------------------------------------