From 033cf12f34d2b74b851c81a67c4ae89341e0ae07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=96zg=C3=BCn=20=C3=96zerk?= Date: Thu, 24 Oct 2024 09:36:38 +0300 Subject: [PATCH] merge changes/fixes from `v2` back into `main` (#333) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * update version for antora * improving zombienet guide (#280) * update docs version to 2.0.1 (#315) * Change all references from rococo to paseo (#330) * remove rococo-native featire from cargo.toml and other doc changes * use evm compatible accounts, and fix properties for chain spec (#326) * doc changes * bump node and docs versions * impl_runtime_apis need to be in the same file with construct runtime for the moment * account type fix * zombienet script update * slot duration fix --------- Co-authored-by: Nikita Khateev Co-authored-by: Özgün Özerk Co-authored-by: Gustavo Gonzalez --------- --- .typos.toml | 4 + docs/antora.yml | 2 +- .../ROOT/pages/guides/async_backing.adoc | 2 +- .../ROOT/pages/guides/quick_start.adoc | 49 +- .../pages/guides/testing_with_zombienet.adoc | 22 +- docs/modules/ROOT/pages/index.adoc | 6 +- docs/modules/ROOT/pages/runtimes/evm.adoc | 4 +- evm-template/Cargo.lock | 2 +- evm-template/node/Cargo.toml | 4 +- evm-template/node/src/chain_spec.rs | 51 +- evm-template/node/src/cli.rs | 6 +- evm-template/node/src/command.rs | 2 +- evm-template/node/src/service.rs | 2 +- evm-template/polkadot-launch/config.json | 2 +- evm-template/runtime/src/apis.rs | 664 ----------------- .../runtime/src/configs/asset_config.rs | 2 +- evm-template/runtime/src/configs/mod.rs | 11 +- evm-template/runtime/src/constants.rs | 4 +- evm-template/runtime/src/lib.rs | 669 +++++++++++++++++- evm-template/runtime/src/types.rs | 3 +- evm-template/runtime/tests/constants_test.rs | 2 +- evm-template/scripts/zombienet.sh | 23 +- evm-template/zombienet-config/devnet.toml | 4 +- generic-template/node/Cargo.toml | 2 +- generic-template/node/src/chain_spec.rs | 4 +- generic-template/node/src/cli.rs | 6 +- generic-template/node/src/command.rs | 2 +- generic-template/runtime/src/configs/mod.rs | 4 +- generic-template/runtime/src/lib.rs | 2 +- generic-template/scripts/zombienet.sh | 6 +- generic-template/zombienet-config/devnet.toml | 2 +- 31 files changed, 767 insertions(+), 801 deletions(-) create mode 100644 .typos.toml delete mode 100644 evm-template/runtime/src/apis.rs diff --git a/.typos.toml b/.typos.toml new file mode 100644 index 00000000..0fa20483 --- /dev/null +++ b/.typos.toml @@ -0,0 +1,4 @@ +[default] +extend-ignore-re = [ + 'AccountId::from\(hex!\("[0-9a-fA-F]{40}"\)\)', +] diff --git a/docs/antora.yml b/docs/antora.yml index 07732a06..0a536b51 100644 --- a/docs/antora.yml +++ b/docs/antora.yml @@ -1,6 +1,6 @@ name: substrate-runtimes title: Substrate Runtimes -version: 1.1.0 +version: 2.0.2 nav: - modules/ROOT/nav.adoc asciidoc: diff --git a/docs/modules/ROOT/pages/guides/async_backing.adoc b/docs/modules/ROOT/pages/guides/async_backing.adoc index 1d476cfc..cf7281a4 100644 --- a/docs/modules/ROOT/pages/guides/async_backing.adoc +++ b/docs/modules/ROOT/pages/guides/async_backing.adoc @@ -16,7 +16,7 @@ cargo build --release --features="async-backing" == How to test -You can always test it against Rococo (it should already have enabled async backing), but the fastest way is to test against a local relay chain. In our repository you can find a script, a config and a link:https://github.com/OpenZeppelin/polkadot-runtime-templates/tree/main/generic-template/zombienet-config[manual] that will run both relay chain and a parachain. To launch a parachain with a relay chain, you will need to run these commands: +You can always test it against Paseo (it should already have enabled async backing), but the fastest way is to test against a local relay chain. In our repository you can find a script, a config and a link:https://github.com/OpenZeppelin/polkadot-runtime-templates/tree/main/generic-template/zombienet-config[manual] that will run both relay chain and a parachain. To launch a parachain with a relay chain, you will need to run these commands: * Get the Polkadot binaries: ** If you are using some Linux distro, you can download the binaries: diff --git a/docs/modules/ROOT/pages/guides/quick_start.adoc b/docs/modules/ROOT/pages/guides/quick_start.adoc index 53e586f8..f629415d 100644 --- a/docs/modules/ROOT/pages/guides/quick_start.adoc +++ b/docs/modules/ROOT/pages/guides/quick_start.adoc @@ -4,12 +4,12 @@ = Quick start -* Begin by visiting our link:https://github.com/OpenZeppelin/polkadot-runtime-templates[repository]. You can fork it, use it as a template, or simply clone it to your local directory. +* Begin by visiting our link:https://github.com/OpenZeppelin/polkadot-runtime-templates[repository]. You can fork it, or simply clone it to your local directory. ```bash git clone git@github.com:OpenZeppelin/polkadot-runtime-templates.git ``` -* Move to the directory of the template you want to use. We will use the `generic runtime template` for this tutorial. +* Move to the directory of the template you want to use. We will use the `generic runtime template` for this tutorial, but it is the same for the same applies to the xref:runtimes/evm.adoc[EVM Runtime Template]. ```bash cd generic-template ``` @@ -19,41 +19,46 @@ cd generic-template cargo build --release ``` -* Receive some `ROC` from the link:https://paritytech.github.io/polkadot-testnet-faucet/[Rococo faucet] +* Receive some `PSO` from the link:https://paritytech.github.io/polkadot-testnet-faucet/[Paseo faucet] -* Reserve a ParaId on Rococo: +* Reserve a ParaId on Paseo: -** Go to link:https://polkadot.js.org/apps[PolkadotJS]. Check that it points to Rococo testnet. +** Go to link:https://polkadot.js.org/apps[PolkadotJS]. Check that it points to Paseo testnet. ** Go to `Network` > `Parachains` ** Go to `Parathreads` tab ** Click the `+ ParaId` button -** Save a `parachain id` for the further usage. +** Save the `parachain id` for the further usage. ** Click `Submit` and `Sign and Submit`. * Generate and customize a chainspec: +[NOTE] +==== +We use the `generic-template-node` executable throughout all the commands since we are using the `generic-template`, but make sure to update the name of the executable if you are using any of the other runtime template. +==== + ** Generate a plain chainspec with this command: + ```bash -./target/release/parachain-template-node build-spec --disable-default-bootnode > plain-parachain-chainspec.json +./target/release/generic-template-node build-spec --disable-default-bootnode > plain-parachain-chainspec.json ``` ** Edit the chainspec: *** Update `name`, `id` and `protocolId` to unique values. -*** Change `relay_chain` from `rococo-local` to `rococo`. +*** Change `relay_chain` from `paseo-local` to `paseo`. *** Change `para_id` and `parachainInfo.parachainId` from `1000` to the previously saved parachain id. ** Generate a raw chainspec with this command: + ```bash -./target/release/parachain-template-node build-spec --chain plain-parachain-chainspec.json --disable-default-bootnode --raw > raw-parachain-chainspec.json +./target/release/generic-template-node build-spec --chain plain-parachain-chainspec.json --disable-default-bootnode --raw > raw-parachain-chainspec.json ``` -* Run two nodes and wait until it syncs with the Rococo relay chain. This can take a fairly long time(up to 2 days), so we can use the `fast-unsafe` flag to make the process faster since we are on a testnet(~ 3 hours). `fast` downloads the blocks without executing the transactions, and `unsafe` skips downloading the state proofs(which we are ok with since it is Rococo). +* Run two nodes and wait until it syncs with the Paseo relay chain. This can take a fairly long time(up to 2 days), so we can use the `fast-unsafe` flag to make the process faster since we are on a testnet(~ 3 hours). `fast` downloads the blocks without executing the transactions, and `unsafe` skips downloading the state proofs(which we are ok with since it is a testnet). + ```bash -./target/release/parachain-template-node \ +./target/release/generic-template-node \ --alice \ --collator \ --force-authoring \ @@ -63,14 +68,14 @@ cargo build --release --rpc-port 8844 \ -- \ --execution wasm \ - --chain \ + --chain \ --port 30343 \ --rpc-port 9977 \ --sync fast-unsafe ``` + ```bash -./target/release/parachain-template-node \ +./target/release/generic-template-node \ --bob \ --collator \ --force-authoring \ @@ -80,27 +85,27 @@ cargo build --release --rpc-port 8845 \ -- \ --execution wasm \ - --chain \ + --chain \ --port 30343 \ --rpc-port 9977 \ --sync fast-unsafe ``` ** `` is where the downloaded chain state will be stored. It can be any folder on your computer. -** `` is where your Rococo chainspec is stored. You can download this file from the link:https://github.com/paritytech/polkadot-sdk/blob/release-polkadot-v1.10.0/polkadot/node/service/chain-specs/rococo.jsonofficial[official Polkadot sdk repository]. +** `` is where your Paseo chainspec is stored. You can download this file from the link:https://github.com/paritytech/polkadot-sdk/blob/release-polkadot-v1.10.0/polkadot/node/service/chain-specs/paseo.json[official Polkadot sdk repository]. * Register a parathread: ** Generate a genesis state: + ```bash -./target/release/parachain-template-node export-genesis-state --chain raw-parachain-chainspec.json para--genesis-state +./target/release/generic-template-node export-genesis-state --chain raw-parachain-chainspec.json para--genesis-state ``` ** Generate a genesis wasm: + ```bash -./target/release/parachain-template-node export-genesis-wasm --chain raw-parachain-chainspec.json para--wasm +./target/release/generic-template-node export-genesis-wasm --chain raw-parachain-chainspec.json para--wasm ``` -** Go to link:https://polkadot.js.org/apps[PolkadotJS]. Check that it points to Rococo testnet. +** Go to link:https://polkadot.js.org/apps[PolkadotJS]. Check that it points to Paseo testnet. ** Go to `Network` > `Parachains`. ** Go to `Parathreads` tab. ** Click the `+ ParaThread` button. @@ -110,16 +115,16 @@ cargo build --release * When a parachain gets synced with a relaychain, you may start producing blocks as a parathread: ** Create some transaction with a PolkadotJS pointing to your parachain setup. -** With a PolkadotJS pointing to Rococo go to `Developer` > `Extrinsics`. +** With a PolkadotJS pointing to Paseo go to `Developer` > `Extrinsics`. ** Submit an extrinsic `onDemandAssignmentProvider.placeOrderAllowDeath` or `onDemandAssignmentProvider.placeOrderKeepAlive`: -*** `maxAmount` should be not less than 10_000_000 and it is amount of 0.00001 ROC. It is an amount of ROC paid for the block. +*** `maxAmount` should be not less than 10_000_000 and it is amount of 0.00001 PAS. It is an amount of PAS paid for the block. *** `paraId` should be set to your parachain id. *** Click `Submit` and `Sign and Submit`. -** In some time your parathread will produce a block and in one of the next blocks of Rococo there will be an inclusion of this block +** In some time your parathread will produce a block and in one of the next blocks of Paseo there will be an inclusion of this block == What's next? - Read our general guides to understand more about the concepts of runtime development. -- Learn more about the runtime configuration. Currently, we have two runtime templates: xref:guides/runtimes/generic.adoc[Generic Runtime Template] and xref:runtimes/evm.adoc[EVM Runtime Template]. +- Learn more about the runtime configuration. Currently, we have two runtime templates: xref:runtimes/generic.adoc[Generic Runtime Template] and xref:runtimes/evm.adoc[EVM Runtime Template]. - Explore the documentation for pallets. It may be useful if you are considering building a frontend for your parachain. diff --git a/docs/modules/ROOT/pages/guides/testing_with_zombienet.adoc b/docs/modules/ROOT/pages/guides/testing_with_zombienet.adoc index e791160f..ae7b2841 100644 --- a/docs/modules/ROOT/pages/guides/testing_with_zombienet.adoc +++ b/docs/modules/ROOT/pages/guides/testing_with_zombienet.adoc @@ -7,7 +7,7 @@ In this tutorial, we will demonstrate how to deploy your parachain using Zombienet, and test the functionalities of your parachain. Below are the main steps of this demo: -. Deploy our parachain against the locally simulated rococo testnet by Zombienet. +. Deploy our parachain against the locally simulated Paseo testnet by Zombienet. . Deploy a Solidity smart contract on our parachain. . Successfully invoke the Solidity smart contract deployed on our parachain. @@ -25,7 +25,7 @@ cd evm-template + ```rust [relaychain] -chain = "rococo-local" +chain = "paseo-local" default_command = "./bin-v1.6.0/polkadot" [[relaychain.nodes]] @@ -162,12 +162,11 @@ image::zombie-chain-spec.png[Zombie Chain Spec] --rpc-port 8844 \ -- \ --execution wasm \ - --chain /var/folders/...{redacted}.../rococo-local.json \ + --chain /var/folders/...{redacted}.../paseo-local.json \ --port 30343 \ --rpc-port 9977 ``` - . your node should be running without any problem, and should see block production in your node terminal! + image::node-success.png[Node Success] @@ -221,15 +220,16 @@ import { Web3 } from "web3"; const web3 = new Web3("ws://127.0.0.1:8844"); console.log("Balance:"); -web3.eth.getBalance("0xe04cc55ebee1cbce552f250e85c57b70b2e2625b").then(console.log); +// this is the address of `Alith` in our chainspec +web3.eth.getBalance("0xf24FF3a9CF04c71Dbc94D0b566f7A27B94566cac").then(console.log); let raw = await web3.eth.accounts.signTransaction({ gas: 21000, gasPrice: 10000000000, - from: "0xe04cc55ebee1cbce552f250e85c57b70b2e2625b", - to: "0x7c98a1801f0B28dF559bCd828fc67Bd6ab558074", + from: "0xf24FF3a9CF04c71Dbc94D0b566f7A27B94566cac", // Alith's address + to: "0x7c98a1801f0B28dF559bCd828fc67Bd6ab558074", // Baltathar's address value: '100000000000000000' -}, "0xcb6df9de1efca7a3998a8ead4e02159d5fa99c3e0d4fd6432667390bb4726854"); +}, "0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133"); // Alith's private key let res = await web3.eth.sendSignedTransaction(raw.rawTransaction); console.log("Transaction details:"); @@ -289,13 +289,13 @@ export var MyAbi = [ node sanity_check.js ``` -. open a terminal instance where the current directory has the `HelloWorld.sol` file, and run: +. open a terminal instance where the current directory has the `HelloWorld.sol` file, and run the below command to deploy the contract with Alith's private key: + ```solidity -forge create --rpc-url http://localhost:8844 --private-key 0xcb6df9de1efca7a3998a8ead4e02159d5fa99c3e0d4fd6432667390bb4726854 HelloWorld.sol:HelloWorld +forge create --rpc-url http://localhost:9933 --private-key 0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133 HelloWorld.sol:HelloWorld ``` + -* don’t forget to copy the address this contract deployed to! +* don’t forget to copy the address this contract deployed to (shown in the output of the command)! diff --git a/docs/modules/ROOT/pages/index.adoc b/docs/modules/ROOT/pages/index.adoc index 440361ad..190515f7 100644 --- a/docs/modules/ROOT/pages/index.adoc +++ b/docs/modules/ROOT/pages/index.adoc @@ -3,14 +3,14 @@ = Polkadot Parachain Runtimes -A collection of runtimes that describe parachains with different purposes. +A collection of secure runtime templates to build parachains more easily on Polkadot. -=== Runtimes +== Runtimes * xref:runtimes/generic.adoc[Generic Runtime Template] * xref:runtimes/evm.adoc[EVM Runtime Template] -=== A Couple of Good Starting Places +== Where to get started * xref:guides/quick_start.adoc[Quick Start]: a generic parachain runtime that works out of the box. It has all the must have features, and allows further customization based on your project's needs. Generic Runtime Template also serves as the base for our other runtime templates. * xref:guides/testing_with_zombienet.adoc[Testing with Zombienet]: a more opinionated parachain runtime template that maximizes Ethereum compatibility by using `AccountId20` and configures a local EVM instance. You can easily migrate/deploy Solidity Smart Contracts to this one. diff --git a/docs/modules/ROOT/pages/runtimes/evm.adoc b/docs/modules/ROOT/pages/runtimes/evm.adoc index 875f9899..39edf030 100644 --- a/docs/modules/ROOT/pages/runtimes/evm.adoc +++ b/docs/modules/ROOT/pages/runtimes/evm.adoc @@ -1,11 +1,11 @@ :source-highlighter: highlight.js :highlightjs-languages: rust :github-icon: pass:[] -= Generic Runtime += EVM Runtime == Purpose -EVM Runtime Template is built on top of the link:generic.adoc[Generic Runtime Template]. +EVM Runtime Template is built on top of the xref:runtimes/generic.adoc[Generic Runtime Template]. The purpose of this template is to provide EVM compatibilities embedded into the runtime. diff --git a/evm-template/Cargo.lock b/evm-template/Cargo.lock index 24802328..15588086 100644 --- a/evm-template/Cargo.lock +++ b/evm-template/Cargo.lock @@ -3067,7 +3067,7 @@ dependencies = [ [[package]] name = "evm-template-node" -version = "1.0.0" +version = "2.0.0" dependencies = [ "clap", "color-print", diff --git a/evm-template/node/Cargo.toml b/evm-template/node/Cargo.toml index 96f77396..474a7ca4 100644 --- a/evm-template/node/Cargo.toml +++ b/evm-template/node/Cargo.toml @@ -7,7 +7,7 @@ edition = { workspace = true } license = { workspace = true } publish = false repository = { workspace = true } -version = "1.0.0" +version = "2.0.0" [dependencies] clap = { workspace = true } @@ -59,7 +59,7 @@ substrate-frame-rpc-system = { workspace = true } substrate-prometheus-endpoint = { workspace = true } # Polkadot -polkadot-cli = { workspace = true, features = [ "rococo-native" ] } +polkadot-cli = { workspace = true } polkadot-primitives = { workspace = true } xcm = { workspace = true } diff --git a/evm-template/node/src/chain_spec.rs b/evm-template/node/src/chain_spec.rs index 527de33d..af8a9623 100644 --- a/evm-template/node/src/chain_spec.rs +++ b/evm-template/node/src/chain_spec.rs @@ -77,13 +77,14 @@ pub fn development_config(contracts_path: ContractsPath) -> ChainSpec { properties.insert("tokenSymbol".into(), "UNIT".into()); properties.insert("tokenDecimals".into(), 12.into()); properties.insert("ss58Format".into(), 42.into()); + properties.insert("isEthereum".into(), true.into()); // This is very important for us, it lets us track the usage of our templates, and have no downside for the node/runtime. Please do not remove :) properties.insert("basedOn".into(), "OpenZeppelin EVM Template".into()); ChainSpec::builder( evm_runtime_template::WASM_BINARY.expect("WASM binary was not built, please build it!"), Extensions { - relay_chain: "rococo-local".into(), + relay_chain: "paseo-local".into(), // You MUST set this to the correct network! para_id: 1000, }, @@ -101,25 +102,19 @@ pub fn development_config(contracts_path: ContractsPath) -> ChainSpec { (get_account_id_from_seed::("Bob"), get_collator_keys_from_seed("Bob")), ], vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Ferdie"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - get_account_id_from_seed::("Charlie//stash"), - get_account_id_from_seed::("Dave//stash"), - get_account_id_from_seed::("Eve//stash"), - get_account_id_from_seed::("Ferdie//stash"), - AccountId::from(hex!("33c7c88f2B2Fcb83975fCDB08d2B5bf7eA29FDCE")), - AccountId::from(hex!("c02db867898f227416BCB6d97190126A6b04988A")), + // Alith, Baltathar, Charleth and Dorothy, Ethan + AccountId::from(hex!("f24FF3a9CF04c71Dbc94D0b566f7A27B94566cac")), + AccountId::from(hex!("3Cd0A705a2DC65e5b1E1205896BaA2be8A07c6e0")), + AccountId::from(hex!("798d4Ba9baf0064Ec19eB4F0a1a45785ae9D6DFc")), + AccountId::from(hex!("773539d4Ac0e786233D90A233654ccEE26a613D9")), + AccountId::from(hex!("Ff64d3F6efE2317EE2807d223a0Bdc4c0c49dfDB")), ], - get_account_id_from_seed::("Alice"), + // Alith + AccountId::from(hex!("f24FF3a9CF04c71Dbc94D0b566f7A27B94566cac")), 1000.into(), contracts_path, )) + .with_properties(properties) .build() } @@ -129,12 +124,13 @@ pub fn local_testnet_config(contracts_path: ContractsPath) -> ChainSpec { properties.insert("tokenSymbol".into(), "UNIT".into()); properties.insert("tokenDecimals".into(), 12.into()); properties.insert("ss58Format".into(), 42.into()); + properties.insert("isEthereum".into(), true.into()); #[allow(deprecated)] ChainSpec::builder( evm_runtime_template::WASM_BINARY.expect("WASM binary was not built, please build it!"), Extensions { - relay_chain: "rococo-local".into(), + relay_chain: "paseo-local".into(), // You MUST set this to the correct network! para_id: 1000, }, @@ -152,20 +148,15 @@ pub fn local_testnet_config(contracts_path: ContractsPath) -> ChainSpec { (get_account_id_from_seed::("Bob"), get_collator_keys_from_seed("Bob")), ], vec![ - get_account_id_from_seed::("Alice"), - get_account_id_from_seed::("Bob"), - get_account_id_from_seed::("Charlie"), - get_account_id_from_seed::("Dave"), - get_account_id_from_seed::("Eve"), - get_account_id_from_seed::("Ferdie"), - get_account_id_from_seed::("Alice//stash"), - get_account_id_from_seed::("Bob//stash"), - get_account_id_from_seed::("Charlie//stash"), - get_account_id_from_seed::("Dave//stash"), - get_account_id_from_seed::("Eve//stash"), - get_account_id_from_seed::("Ferdie//stash"), + // Alith, Baltathar, Charleth and Dorothy, Ethan + AccountId::from(hex!("f24FF3a9CF04c71Dbc94D0b566f7A27B94566cac")), + AccountId::from(hex!("3Cd0A705a2DC65e5b1E1205896BaA2be8A07c6e0")), + AccountId::from(hex!("798d4Ba9baf0064Ec19eB4F0a1a45785ae9D6DFc")), + AccountId::from(hex!("773539d4Ac0e786233D90A233654ccEE26a613D9")), + AccountId::from(hex!("Ff64d3F6efE2317EE2807d223a0Bdc4c0c49dfDB")), ], - get_account_id_from_seed::("Alice"), + // Alith + AccountId::from(hex!("f24FF3a9CF04c71Dbc94D0b566f7A27B94566cac")), 1000.into(), contracts_path, )) diff --git a/evm-template/node/src/cli.rs b/evm-template/node/src/cli.rs index 3ee871e6..a9f56cf1 100644 --- a/evm-template/node/src/cli.rs +++ b/evm-template/node/src/cli.rs @@ -96,12 +96,12 @@ const AFTER_HELP_EXAMPLE: &str = color_print::cstr!( r#"Examples: parachain-template-node build-spec --disable-default-bootnode > plain-parachain-chainspec.json Export a chainspec for a local testnet in json format. - parachain-template-node --chain plain-parachain-chainspec.json --tmp -- --chain rococo-local + parachain-template-node --chain plain-parachain-chainspec.json --tmp -- --chain paseo-local Launch a full node with chain specification loaded from plain-parachain-chainspec.json. parachain-template-node - Launch a full node with default parachain local-testnet and relay chain rococo-local. + Launch a full node with default parachain local-testnet and relay chain paseo-local. parachain-template-node --collator - Launch a collator with default parachain local-testnet and relay chain rococo-local. + Launch a collator with default parachain local-testnet and relay chain paseo-local. "# ); #[derive(Debug, clap::Parser)] diff --git a/evm-template/node/src/command.rs b/evm-template/node/src/command.rs index bf5c33fd..992136ff 100644 --- a/evm-template/node/src/command.rs +++ b/evm-template/node/src/command.rs @@ -25,7 +25,7 @@ fn load_spec( ) -> std::result::Result, String> { Ok(match id { "dev" => Box::new(chain_spec::development_config(contracts_path)), - "template-rococo" => Box::new(chain_spec::local_testnet_config(contracts_path)), + "template-paseo" => Box::new(chain_spec::local_testnet_config(contracts_path)), "" | "local" => Box::new(chain_spec::local_testnet_config(contracts_path)), path => Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?), }) diff --git a/evm-template/node/src/service.rs b/evm-template/node/src/service.rs index dcc6feac..fe02b4b6 100644 --- a/evm-template/node/src/service.rs +++ b/evm-template/node/src/service.rs @@ -19,9 +19,9 @@ use cumulus_primitives_core::{relay_chain::CollatorPair, ParaId}; use cumulus_relay_chain_interface::{OverseerHandle, RelayChainInterface}; // Local Runtime Types use evm_runtime_template::{ - apis::RuntimeApi, configs::TransactionConverter, opaque::{Block, Hash}, + RuntimeApi, }; // Substrate Imports use frame_benchmarking_cli::SUBSTRATE_REFERENCE_HARDWARE; diff --git a/evm-template/polkadot-launch/config.json b/evm-template/polkadot-launch/config.json index f03f983a..9a1f1d5b 100644 --- a/evm-template/polkadot-launch/config.json +++ b/evm-template/polkadot-launch/config.json @@ -1,7 +1,7 @@ { "relaychain": { "bin": "../../polkadot/target/release/polkadot", - "chain": "rococo-local", + "chain": "paseo-local", "nodes": [ { "name": "alice", diff --git a/evm-template/runtime/src/apis.rs b/evm-template/runtime/src/apis.rs deleted file mode 100644 index dc824693..00000000 --- a/evm-template/runtime/src/apis.rs +++ /dev/null @@ -1,664 +0,0 @@ -use frame_support::{ - genesis_builder_helper::{build_state, get_preset}, - traits::OnFinalize, - weights::Weight, -}; -use pallet_ethereum::{ - Call::transact, Transaction as EthereumTransaction, TransactionAction, TransactionData, - TransactionStatus, -}; -use pallet_evm::{Account as EVMAccount, FeeCalculator, Runner}; -use sp_api::impl_runtime_apis; -use sp_consensus_aura::sr25519::AuthorityId as AuraId; -use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H160, H256, U256}; -use sp_runtime::{ - traits::{Block as BlockT, Get, UniqueSaturatedInto}, - transaction_validity::{TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, Permill, -}; -use sp_std::prelude::Vec; -use sp_version::RuntimeVersion; - -#[cfg(not(feature = "async-backing"))] -use crate::Aura; -#[cfg(feature = "async-backing")] -use crate::{constants::SLOT_DURATION, types::ConsensusHook}; -use crate::{ - constants::VERSION, - types::{AccountId, Balance, Block, Executive, Nonce}, - Ethereum, InherentDataExt, ParachainSystem, Runtime, RuntimeCall, RuntimeGenesisConfig, - SessionKeys, System, TransactionPayment, UncheckedExtrinsic, -}; - -impl_runtime_apis! { - impl sp_consensus_aura::AuraApi for Runtime { - fn slot_duration() -> sp_consensus_aura::SlotDuration { - #[cfg(feature = "async-backing")] - return sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION); - #[cfg(not(feature = "async-backing"))] - sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) - } - - fn authorities() -> Vec { - pallet_aura::Authorities::::get().into_inner() - } - } - - impl sp_api::Core for Runtime { - fn version() -> RuntimeVersion { - VERSION - } - - fn execute_block(block: Block) { - Executive::execute_block(block) - } - - fn initialize_block(header: &::Header) -> sp_runtime::ExtrinsicInclusionMode { - Executive::initialize_block(header) - } - } - - impl sp_api::Metadata for Runtime { - fn metadata() -> OpaqueMetadata { - OpaqueMetadata::new(Runtime::metadata().into()) - } - - fn metadata_at_version(version: u32) -> Option { - Runtime::metadata_at_version(version) - } - - fn metadata_versions() -> sp_std::vec::Vec { - Runtime::metadata_versions() - } - } - - impl sp_block_builder::BlockBuilder for Runtime { - fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { - Executive::apply_extrinsic(extrinsic) - } - - fn finalize_block() -> ::Header { - Executive::finalize_block() - } - - fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { - data.create_extrinsics() - } - - fn check_inherents( - block: Block, - data: sp_inherents::InherentData, - ) -> sp_inherents::CheckInherentsResult { - data.check_extrinsics(&block) - } - } - - impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { - fn validate_transaction( - source: TransactionSource, - tx: ::Extrinsic, - block_hash: ::Hash, - ) -> TransactionValidity { - Executive::validate_transaction(source, tx, block_hash) - } - } - - impl sp_offchain::OffchainWorkerApi for Runtime { - fn offchain_worker(header: &::Header) { - Executive::offchain_worker(header) - } - } - - impl sp_session::SessionKeys for Runtime { - fn generate_session_keys(seed: Option>) -> Vec { - SessionKeys::generate(seed) - } - - fn decode_session_keys( - encoded: Vec, - ) -> Option, KeyTypeId)>> { - SessionKeys::decode_into_raw_public_keys(&encoded) - } - } - - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Nonce { - System::account_nonce(account) - } - } - - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { - fn query_info( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { - TransactionPayment::query_info(uxt, len) - } - fn query_fee_details( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_fee_details(uxt, len) - } - fn query_weight_to_fee(weight: Weight) -> Balance { - TransactionPayment::weight_to_fee(weight) - } - fn query_length_to_fee(length: u32) -> Balance { - TransactionPayment::length_to_fee(length) - } - } - - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi - for Runtime - { - fn query_call_info( - call: RuntimeCall, - len: u32, - ) -> pallet_transaction_payment::RuntimeDispatchInfo { - TransactionPayment::query_call_info(call, len) - } - fn query_call_fee_details( - call: RuntimeCall, - len: u32, - ) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_call_fee_details(call, len) - } - fn query_weight_to_fee(weight: Weight) -> Balance { - TransactionPayment::weight_to_fee(weight) - } - fn query_length_to_fee(length: u32) -> Balance { - TransactionPayment::length_to_fee(length) - } - } - - impl fp_rpc::EthereumRuntimeRPCApi for Runtime { - /// Returns runtime defined pallet_evm::ChainId. - fn chain_id() -> u64 { - ::ChainId::get() - } - - /// Returns pallet_evm::Accounts by address. - fn account_basic(address: H160) -> EVMAccount { - let (account, _) = pallet_evm::Pallet::::account_basic(&address); - account - } - - /// Returns FixedGasPrice::min_gas_price - fn gas_price() -> U256 { - let (gas_price, _) = ::FeeCalculator::min_gas_price(); - gas_price - } - - /// For a given account address, returns pallet_evm::AccountCodes. - fn account_code_at(address: H160) -> Vec { - pallet_evm::AccountCodes::::get(address) - } - - /// Returns the converted FindAuthor::find_author authority id. - fn author() -> H160 { - >::find_author() - } - - /// For a given account address and index, returns pallet_evm::AccountStorages. - fn storage_at(address: H160, index: U256) -> H256 { - let mut tmp = [0u8; 32]; - index.to_big_endian(&mut tmp); - pallet_evm::AccountStorages::::get(address, H256::from_slice(&tmp[..])) - } - - /// Returns a frame_ethereum::call response. - fn call( - from: H160, - to: H160, - data: Vec, - value: U256, - gas_limit: U256, - max_fee_per_gas: Option, - max_priority_fee_per_gas: Option, - nonce: Option, - estimate: bool, - access_list: Option)>>, - ) -> Result { - let config = if estimate { - let mut config = ::config().clone(); - config.estimate = true; - Some(config) - } else { - None - }; - - let gas_limit = gas_limit.min(u64::MAX.into()); - let transaction_data = TransactionData::new( - TransactionAction::Call(to), - data.clone(), - nonce.unwrap_or_default(), - gas_limit, - None, - max_fee_per_gas, - max_priority_fee_per_gas, - value, - Some(::ChainId::get()), - access_list.clone().unwrap_or_default(), - ); - let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::::transaction_weight(&transaction_data); - - ::Runner::call( - from, - to, - data, - value, - gas_limit.unique_saturated_into(), - max_fee_per_gas, - max_priority_fee_per_gas, - nonce, - access_list.unwrap_or_default(), - false, - true, - weight_limit, - proof_size_base_cost, - config.as_ref().unwrap_or(::config()), - ).map_err(|err| err.error.into()) - } - - /// Returns a frame_ethereum::create response. - fn create( - from: H160, - data: Vec, - value: U256, - gas_limit: U256, - max_fee_per_gas: Option, - max_priority_fee_per_gas: Option, - nonce: Option, - estimate: bool, - access_list: Option)>>, - ) -> Result { - let config = if estimate { - let mut config = ::config().clone(); - config.estimate = true; - Some(config) - } else { - None - }; - - let transaction_data = TransactionData::new( - TransactionAction::Create, - data.clone(), - nonce.unwrap_or_default(), - gas_limit, - None, - max_fee_per_gas, - max_priority_fee_per_gas, - value, - Some(::ChainId::get()), - access_list.clone().unwrap_or_default(), - ); - let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::::transaction_weight(&transaction_data); - - ::Runner::create( - from, - data, - value, - gas_limit.unique_saturated_into(), - max_fee_per_gas, - max_priority_fee_per_gas, - nonce, - access_list.unwrap_or_default(), - false, - true, - weight_limit, - proof_size_base_cost, - config.as_ref().unwrap_or(::config()), - ).map_err(|err| err.error.into()) - } - - /// Return the current transaction status. - fn current_transaction_statuses() -> Option> { - pallet_ethereum::CurrentTransactionStatuses::::get() - } - - /// Return the current block. - fn current_block() -> Option { - pallet_ethereum::CurrentBlock::::get() - } - - /// Return the current receipts. - fn current_receipts() -> Option> { - pallet_ethereum::CurrentReceipts::::get() - } - - /// Return all the current data for a block in a single runtime call. - fn current_all() -> ( - Option, - Option>, - Option> - ) { - ( - pallet_ethereum::CurrentBlock::::get(), - pallet_ethereum::CurrentReceipts::::get(), - pallet_ethereum::CurrentTransactionStatuses::::get() - ) - } - - /// Receives a `Vec` and filters out all the non-ethereum transactions. - fn extrinsic_filter( - xts: Vec<::Extrinsic>, - ) -> Vec { - xts.into_iter().filter_map(|xt| match xt.0.function { - RuntimeCall::Ethereum(transact { transaction }) => Some(transaction), - _ => None - }).collect::>() - } - - /// Return the elasticity multiplier. - fn elasticity() -> Option { - Some(pallet_base_fee::Elasticity::::get()) - } - - /// Used to determine if gas limit multiplier for non-transactional calls (eth_call/estimateGas) - /// is supported. - fn gas_limit_multiplier_support() {} - - /// Return the pending block. - fn pending_block( - xts: Vec<::Extrinsic>, - ) -> (Option, Option>) { - for ext in xts.into_iter() { - let _ = Executive::apply_extrinsic(ext); - } - - Ethereum::on_finalize(System::block_number() + 1); - - ( - pallet_ethereum::CurrentBlock::::get(), - pallet_ethereum::CurrentTransactionStatuses::::get() - ) - } - - fn initialize_pending_block(header: &::Header) { - Executive::initialize_block(header); - } - } - - impl fp_rpc::ConvertTransactionRuntimeApi for Runtime { - /// Converts an ethereum transaction into a transaction suitable for the runtime. - fn convert_transaction(transaction: EthereumTransaction) -> ::Extrinsic { - UncheckedExtrinsic::new_unsigned( - pallet_ethereum::Call::::transact { transaction }.into(), - ) - } - } - - - - impl cumulus_primitives_core::CollectCollationInfo for Runtime { - fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { - ParachainSystem::collect_collation_info(header) - } - } - - #[cfg(feature = "async-backing")] - impl cumulus_primitives_aura::AuraUnincludedSegmentApi for Runtime { - fn can_build_upon( - included_hash: ::Hash, - slot: cumulus_primitives_aura::Slot - ) -> bool { - ConsensusHook::can_build_upon(included_hash, slot) - } - } - - #[cfg(feature = "try-runtime")] - impl frame_try_runtime::TryRuntime for Runtime { - fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { - use super::configs::RuntimeBlockWeights; - - let weight = Executive::try_runtime_upgrade(checks).unwrap(); - (weight, RuntimeBlockWeights::get().max_block) - } - - fn execute_block( - block: Block, - state_root_check: bool, - signature_check: bool, - select: frame_try_runtime::TryStateSelect, - ) -> Weight { - // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to - // have a backtrace here. - Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap() - } - } - - #[cfg(feature = "runtime-benchmarks")] - impl frame_benchmarking::Benchmark for Runtime { - fn benchmark_metadata(extra: bool) -> ( - Vec, - Vec, - ) { - use frame_benchmarking::{Benchmarking, BenchmarkList}; - use frame_support::traits::StorageInfoTrait; - use frame_system_benchmarking::Pallet as SystemBench; - use cumulus_pallet_session_benchmarking::Pallet as SessionBench; - - use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; - - use super::*; - - let mut list = Vec::::new(); - list_benchmarks!(list, extra); - - let storage_info = AllPalletsWithSystem::storage_info(); - (list, storage_info) - } - - fn dispatch_benchmark( - config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { - use frame_benchmarking::{BenchmarkError, Benchmarking, BenchmarkBatch}; - use frame_support::parameter_types; - use cumulus_primitives_core::ParaId; - use frame_system_benchmarking::Pallet as SystemBench; - - use super::{*, types::*, configs::*, constants::currency::CENTS}; - - impl frame_system_benchmarking::Config for Runtime { - fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { - ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); - Ok(()) - } - - fn verify_set_code() { - System::assert_last_event(cumulus_pallet_parachain_system::Event::::ValidationFunctionStored.into()); - } - } - - parameter_types! { - pub const RandomParaId: ParaId = ParaId::new(43211234); - pub ExistentialDepositAsset: Option = Some(( - RelayLocation::get(), - ExistentialDeposit::get() - ).into()); - /// The base fee for the message delivery fees. Kusama is based for the reference. - pub const ToParentBaseDeliveryFee: u128 = CENTS.saturating_mul(3); - pub const InitialTransferAssetAmount: u128 = 4001070000100; - } - pub type PriceForParentDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice< - FeeAssetId, - ToParentBaseDeliveryFee, - TransactionByteFee, - ParachainSystem, - >; - use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; - use xcm::latest::prelude::{Asset, AssetId, Assets as AssetList, Fungible, Location, Parachain, Parent, ParentThen, PalletInstance, GeneralIndex}; - impl pallet_xcm::benchmarking::Config for Runtime { - type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< - xcm_config::XcmConfig, - ExistentialDepositAsset, - PriceForParentDelivery, - >; - - fn reachable_dest() -> Option { - Some(Parent.into()) - } - - fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { - None - } - - fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { - use frame_support::traits::PalletInfoAccess; - use xcm_primitives::AssetTypeGetter; - use frame_system::RawOrigin; - - // set up fee asset - let fee_location = RelayLocation::get(); - let who: AccountId = frame_benchmarking::whitelisted_caller(); - - let Some(location_v3) = xcm::v3::Location::try_from(fee_location.clone()).ok() else { - return None; - }; - let asset_type = AssetType::Xcm(location_v3); - - let local_asset_id: crate::types::AssetId = asset_type.clone().into(); - let manager_id = AssetManager::account_id(); - let _ = Assets::force_create(RuntimeOrigin::root(), local_asset_id.clone().into(), sp_runtime::MultiAddress::Id(manager_id.clone()), true, 1); - let _ = Assets::mint( - RawOrigin::Signed(manager_id.clone()).into(), - local_asset_id.into(), - sp_runtime::MultiAddress::Id(who), - InitialTransferAssetAmount::get(), - ); - AssetManager::set_asset_type_asset_id(asset_type.clone(), local_asset_id.into()); - - // open a mock parachain channel - ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( - RandomParaId::get().into() - ); - - // set up transfer asset - let initial_asset_amount: u128 = InitialTransferAssetAmount::get(); - let (asset_id, _, _) = pallet_assets::benchmarking::create_default_minted_asset::< - Runtime, - () - >(true, initial_asset_amount); - - let asset_id_u128: u128 = asset_id.into(); - let self_reserve = Location { - parents: 0, - interior: [ - PalletInstance(::index() as u8), GeneralIndex(asset_id_u128) - ].into() - }; - - let Some(location_v3) = xcm::v3::Location::try_from(self_reserve.clone()).ok() else { - return None; - }; - let asset_type = AssetType::Xcm(location_v3); - AssetManager::set_asset_type_asset_id(asset_type.clone(), asset_id_u128); - - let asset = Asset { - fun: Fungible(ExistentialDeposit::get()), - id: AssetId(self_reserve.into()) - }.into(); - Some(( - asset, - ParentThen(Parachain(RandomParaId::get().into()).into()).into(), - )) - } - - fn set_up_complex_asset_transfer( - ) -> Option<(AssetList, u32, Location, Box)> { - use frame_support::traits::PalletInfoAccess; - use xcm_primitives::AssetTypeGetter; - // set up local asset - let initial_asset_amount: u128 = 1000000011; - - let (asset_id, _, _) = pallet_assets::benchmarking::create_default_minted_asset::< - Runtime, - () - >(true, initial_asset_amount); - - let asset_id_u128: u128 = asset_id.into(); - - let self_reserve = Location { - parents:0, - interior: [ - PalletInstance(::index() as u8), GeneralIndex(asset_id_u128) - ].into() - }; - - let Some(location_v3) = xcm::v3::Location::try_from(self_reserve.clone()).ok() else { - return None; - }; - let asset_type = AssetType::Xcm(location_v3); - AssetManager::set_asset_type_asset_id(asset_type.clone(), asset_id_u128); - - let destination: xcm::v4::Location = Parent.into(); - - // set up fee asset - let fee_amount: u128 = ::ExistentialDeposit::get(); - let asset_amount: u128 = 10; - let fee_asset: Asset = (self_reserve.clone(), fee_amount).into(); - let transfer_asset: Asset = (self_reserve.clone(), asset_amount).into(); - - let assets: cumulus_primitives_core::Assets = vec![fee_asset.clone(), transfer_asset].into(); - let fee_index: u32 = 0; - - let who = frame_benchmarking::whitelisted_caller(); - - let verify: Box = Box::new(move || { - // verify balance after transfer, decreased by - // transferred amount (and delivery fees) - assert!(Assets::balance(asset_id_u128, &who) <= initial_asset_amount - fee_amount); - }); - - Some((assets, fee_index, destination, verify)) - } - - fn get_asset() -> Asset { - use xcm_primitives::AssetTypeGetter; - let location = Location::parent(); - let asset_id = AssetId(location.clone()); - let asset = Asset { - id: asset_id.clone(), - fun: Fungible(ExistentialDeposit::get()), - }; - let Some(location_v3) = xcm::v3::Location::try_from(location).ok() else { - return asset; - }; - let asset_type = AssetType::Xcm(location_v3); - let local_asset_id: crate::types::AssetId = asset_type.clone().into(); - let manager_id = AssetManager::account_id(); - let _ = Assets::force_create(RuntimeOrigin::root(), local_asset_id.clone().into(), sp_runtime::MultiAddress::Id(manager_id), true, 1); - AssetManager::set_asset_type_asset_id(asset_type.clone(), local_asset_id); - asset - } - } - - use cumulus_pallet_session_benchmarking::Pallet as SessionBench; - impl cumulus_pallet_session_benchmarking::Config for Runtime {} - - use frame_support::traits::WhitelistedStorageKeys; - let whitelist = AllPalletsWithSystem::whitelisted_storage_keys(); - - let mut batches = Vec::::new(); - let params = (&config, &whitelist); - add_benchmarks!(params, batches); - - if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } - Ok(batches) - } - } - - impl sp_genesis_builder::GenesisBuilder for Runtime { - fn build_state(config: Vec) -> sp_genesis_builder::Result { - build_state::(config) - } - - fn get_preset(id: &Option) -> Option> { - get_preset::(id, |_| None) - } - - fn preset_names() -> Vec { - Default::default() - } - } -} diff --git a/evm-template/runtime/src/configs/asset_config.rs b/evm-template/runtime/src/configs/asset_config.rs index f71aabcd..b590eff3 100644 --- a/evm-template/runtime/src/configs/asset_config.rs +++ b/evm-template/runtime/src/configs/asset_config.rs @@ -130,7 +130,7 @@ impl pallet_asset_manager::AssetRegistrar for AssetRegistrar { Assets::force_create( RuntimeOrigin::root(), asset.into(), - sp_runtime::MultiAddress::Id(AssetManager::account_id()), + AssetManager::account_id(), is_sufficient, min_balance, )?; diff --git a/evm-template/runtime/src/configs/mod.rs b/evm-template/runtime/src/configs/mod.rs index 6f265dc2..25acbb0c 100644 --- a/evm-template/runtime/src/configs/mod.rs +++ b/evm-template/runtime/src/configs/mod.rs @@ -33,7 +33,7 @@ use scale_info::TypeInfo; use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::{H160, U256}; use sp_runtime::{ - traits::{AccountIdLookup, BlakeTwo256, IdentityLookup}, + traits::{BlakeTwo256, IdentityLookup}, ConsensusEngineId, Perbill, Permill, RuntimeDebug, }; use sp_std::marker::PhantomData; @@ -46,13 +46,11 @@ use xcm_config::{RelayLocation, XcmOriginToTransactDispatchOrigin}; #[cfg(feature = "runtime-benchmarks")] use crate::benchmark::{OpenHrmpChannel, PayWithEnsure}; -#[cfg(feature = "async-backing")] -use crate::constants::SLOT_DURATION; use crate::{ constants::{ currency::{deposit, CENTS, EXISTENTIAL_DEPOSIT, GRAND, MICROCENTS}, AVERAGE_ON_INITIALIZE_RATIO, DAYS, HOURS, MAXIMUM_BLOCK_WEIGHT, MAX_BLOCK_LENGTH, - NORMAL_DISPATCH_RATIO, VERSION, WEIGHT_PER_GAS, + NORMAL_DISPATCH_RATIO, SLOT_DURATION, VERSION, WEIGHT_PER_GAS, }, opaque, types::{ @@ -140,7 +138,7 @@ impl frame_system::Config for Runtime { type Hash = Hash; /// The lookup mechanism to get account ID from whatever is passed in /// dispatchers. - type Lookup = AccountIdLookup; + type Lookup = sp_runtime::traits::IdentityLookup; /// The maximum number of consumers allowed on a single account. type MaxConsumers = ConstU32<16>; /// The index type for storing how many extrinsics an account has signed. @@ -484,10 +482,7 @@ impl pallet_aura::Config for Runtime { type AuthorityId = AuraId; type DisabledValidators = (); type MaxAuthorities = MaxAuthorities; - #[cfg(feature = "async-backing")] type SlotDuration = ConstU64; - #[cfg(not(feature = "async-backing"))] - type SlotDuration = pallet_aura::MinimumPeriodTimesTwo; } parameter_types! { diff --git a/evm-template/runtime/src/constants.rs b/evm-template/runtime/src/constants.rs index d917cba3..ef8a0fcc 100644 --- a/evm-template/runtime/src/constants.rs +++ b/evm-template/runtime/src/constants.rs @@ -2,7 +2,7 @@ use frame_support::weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight}; use sp_runtime::{create_runtime_str, Perbill}; use sp_version::RuntimeVersion; -use crate::{apis, types::BlockNumber}; +use crate::types::BlockNumber; pub mod currency { use crate::types::Balance; @@ -40,7 +40,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { authoring_version: 1, spec_version: 1, impl_version: 0, - apis: apis::RUNTIME_API_VERSIONS, + apis: crate::RUNTIME_API_VERSIONS, transaction_version: 1, state_version: 1, }; diff --git a/evm-template/runtime/src/lib.rs b/evm-template/runtime/src/lib.rs index d45a76a7..054e6894 100644 --- a/evm-template/runtime/src/lib.rs +++ b/evm-template/runtime/src/lib.rs @@ -6,7 +6,6 @@ #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); -pub mod apis; pub mod configs; pub mod constants; mod precompiles; @@ -14,27 +13,39 @@ pub use precompiles::OpenZeppelinPrecompiles; mod types; mod weights; -use frame_support::weights::{ - WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, +use frame_support::{ + genesis_builder_helper::{build_state, get_preset}, + traits::OnFinalize, + weights::{Weight, WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial}, }; +use pallet_ethereum::{ + Call::transact, Transaction as EthereumTransaction, TransactionAction, TransactionData, + TransactionStatus, +}; +use pallet_evm::{Account as EVMAccount, FeeCalculator, Runner}; use smallvec::smallvec; +use sp_api::impl_runtime_apis; pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; -use sp_core::H160; +use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H160, H256, U256}; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; use sp_runtime::{ impl_opaque_keys, - traits::{DispatchInfoOf, Dispatchable, PostDispatchInfoOf}, - transaction_validity::{TransactionValidity, TransactionValidityError}, + traits::{ + Block as BlockT, DispatchInfoOf, Dispatchable, Get, PostDispatchInfoOf, UniqueSaturatedInto, + }, + transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError}, + ApplyExtrinsicResult, }; pub use sp_runtime::{MultiAddress, Perbill, Permill}; -use sp_std::prelude::*; +use sp_std::prelude::{Vec, *}; #[cfg(feature = "std")] use sp_version::NativeVersion; +use sp_version::RuntimeVersion; use crate::{ configs::pallet_custom_origins, - constants::{currency::MILLICENTS, POLY_DEGREE, P_FACTOR, Q_FACTOR}, + constants::{currency::MILLICENTS, POLY_DEGREE, P_FACTOR, Q_FACTOR, VERSION}, weights::ExtrinsicBaseWeight, }; pub use crate::{ @@ -43,6 +54,8 @@ pub use crate::{ AccountId, Balance, Block, BlockNumber, Executive, Nonce, Signature, UncheckedExtrinsic, }, }; +#[cfg(feature = "async-backing")] +use crate::{constants::SLOT_DURATION, types::ConsensusHook}; impl fp_self_contained::SelfContainedCall for RuntimeCall { type SignedInfo = H160; @@ -118,7 +131,7 @@ impl WeightToFeePolynomial for WeightToFee { type Balance = Balance; fn polynomial() -> WeightToFeeCoefficients { - // in Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1 + // in Paseo, extrinsic base weight (smallest non-zero weight) is mapped to 1 // MILLIUNIT: in our template, we map to 1/10 of that, or 1/10 MILLIUNIT let p = MILLICENTS / P_FACTOR; let q = Q_FACTOR * Balance::from(ExtrinsicBaseWeight::get().ref_time()); @@ -266,5 +279,643 @@ cumulus_pallet_parachain_system::register_validate_block! { BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, } +impl_runtime_apis! { + impl sp_consensus_aura::AuraApi for Runtime { + fn slot_duration() -> sp_consensus_aura::SlotDuration { + #[cfg(feature = "async-backing")] + return sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION); + #[cfg(not(feature = "async-backing"))] + sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) + } + + fn authorities() -> Vec { + pallet_aura::Authorities::::get().into_inner() + } + } + + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } + + fn execute_block(block: Block) { + Executive::execute_block(block) + } + + fn initialize_block(header: &::Header) -> sp_runtime::ExtrinsicInclusionMode { + Executive::initialize_block(header) + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + OpaqueMetadata::new(Runtime::metadata().into()) + } + + fn metadata_at_version(version: u32) -> Option { + Runtime::metadata_at_version(version) + } + + fn metadata_versions() -> sp_std::vec::Vec { + Runtime::metadata_versions() + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + block_hash: ::Hash, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx, block_hash) + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + SessionKeys::generate(seed) + } + + fn decode_session_keys( + encoded: Vec, + ) -> Option, KeyTypeId)>> { + SessionKeys::decode_into_raw_public_keys(&encoded) + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { + System::account_nonce(account) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { + fn query_info( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + TransactionPayment::query_info(uxt, len) + } + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_fee_details(uxt, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi + for Runtime + { + fn query_call_info( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::RuntimeDispatchInfo { + TransactionPayment::query_call_info(call, len) + } + fn query_call_fee_details( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_call_fee_details(call, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl fp_rpc::EthereumRuntimeRPCApi for Runtime { + /// Returns runtime defined pallet_evm::ChainId. + fn chain_id() -> u64 { + ::ChainId::get() + } + + /// Returns pallet_evm::Accounts by address. + fn account_basic(address: H160) -> EVMAccount { + let (account, _) = pallet_evm::Pallet::::account_basic(&address); + account + } + + /// Returns FixedGasPrice::min_gas_price + fn gas_price() -> U256 { + let (gas_price, _) = ::FeeCalculator::min_gas_price(); + gas_price + } + + /// For a given account address, returns pallet_evm::AccountCodes. + fn account_code_at(address: H160) -> Vec { + pallet_evm::AccountCodes::::get(address) + } + + /// Returns the converted FindAuthor::find_author authority id. + fn author() -> H160 { + >::find_author() + } + + /// For a given account address and index, returns pallet_evm::AccountStorages. + fn storage_at(address: H160, index: U256) -> H256 { + let mut tmp = [0u8; 32]; + index.to_big_endian(&mut tmp); + pallet_evm::AccountStorages::::get(address, H256::from_slice(&tmp[..])) + } + + /// Returns a frame_ethereum::call response. + fn call( + from: H160, + to: H160, + data: Vec, + value: U256, + gas_limit: U256, + max_fee_per_gas: Option, + max_priority_fee_per_gas: Option, + nonce: Option, + estimate: bool, + access_list: Option)>>, + ) -> Result { + let config = if estimate { + let mut config = ::config().clone(); + config.estimate = true; + Some(config) + } else { + None + }; + + let gas_limit = gas_limit.min(u64::MAX.into()); + let transaction_data = TransactionData::new( + TransactionAction::Call(to), + data.clone(), + nonce.unwrap_or_default(), + gas_limit, + None, + max_fee_per_gas, + max_priority_fee_per_gas, + value, + Some(::ChainId::get()), + access_list.clone().unwrap_or_default(), + ); + let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::::transaction_weight(&transaction_data); + + ::Runner::call( + from, + to, + data, + value, + gas_limit.unique_saturated_into(), + max_fee_per_gas, + max_priority_fee_per_gas, + nonce, + access_list.unwrap_or_default(), + false, + true, + weight_limit, + proof_size_base_cost, + config.as_ref().unwrap_or(::config()), + ).map_err(|err| err.error.into()) + } + + /// Returns a frame_ethereum::create response. + fn create( + from: H160, + data: Vec, + value: U256, + gas_limit: U256, + max_fee_per_gas: Option, + max_priority_fee_per_gas: Option, + nonce: Option, + estimate: bool, + access_list: Option)>>, + ) -> Result { + let config = if estimate { + let mut config = ::config().clone(); + config.estimate = true; + Some(config) + } else { + None + }; + + let transaction_data = TransactionData::new( + TransactionAction::Create, + data.clone(), + nonce.unwrap_or_default(), + gas_limit, + None, + max_fee_per_gas, + max_priority_fee_per_gas, + value, + Some(::ChainId::get()), + access_list.clone().unwrap_or_default(), + ); + let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::::transaction_weight(&transaction_data); + + ::Runner::create( + from, + data, + value, + gas_limit.unique_saturated_into(), + max_fee_per_gas, + max_priority_fee_per_gas, + nonce, + access_list.unwrap_or_default(), + false, + true, + weight_limit, + proof_size_base_cost, + config.as_ref().unwrap_or(::config()), + ).map_err(|err| err.error.into()) + } + + /// Return the current transaction status. + fn current_transaction_statuses() -> Option> { + pallet_ethereum::CurrentTransactionStatuses::::get() + } + + /// Return the current block. + fn current_block() -> Option { + pallet_ethereum::CurrentBlock::::get() + } + + /// Return the current receipts. + fn current_receipts() -> Option> { + pallet_ethereum::CurrentReceipts::::get() + } + + /// Return all the current data for a block in a single runtime call. + fn current_all() -> ( + Option, + Option>, + Option> + ) { + ( + pallet_ethereum::CurrentBlock::::get(), + pallet_ethereum::CurrentReceipts::::get(), + pallet_ethereum::CurrentTransactionStatuses::::get() + ) + } + + /// Receives a `Vec` and filters out all the non-ethereum transactions. + fn extrinsic_filter( + xts: Vec<::Extrinsic>, + ) -> Vec { + xts.into_iter().filter_map(|xt| match xt.0.function { + RuntimeCall::Ethereum(transact { transaction }) => Some(transaction), + _ => None + }).collect::>() + } + + /// Return the elasticity multiplier. + fn elasticity() -> Option { + Some(pallet_base_fee::Elasticity::::get()) + } + + /// Used to determine if gas limit multiplier for non-transactional calls (eth_call/estimateGas) + /// is supported. + fn gas_limit_multiplier_support() {} + + /// Return the pending block. + fn pending_block( + xts: Vec<::Extrinsic>, + ) -> (Option, Option>) { + for ext in xts.into_iter() { + let _ = Executive::apply_extrinsic(ext); + } + + Ethereum::on_finalize(System::block_number() + 1); + + ( + pallet_ethereum::CurrentBlock::::get(), + pallet_ethereum::CurrentTransactionStatuses::::get() + ) + } + + fn initialize_pending_block(header: &::Header) { + Executive::initialize_block(header); + } + } + + impl fp_rpc::ConvertTransactionRuntimeApi for Runtime { + /// Converts an ethereum transaction into a transaction suitable for the runtime. + fn convert_transaction(transaction: EthereumTransaction) -> ::Extrinsic { + UncheckedExtrinsic::new_unsigned( + pallet_ethereum::Call::::transact { transaction }.into(), + ) + } + } + + + + impl cumulus_primitives_core::CollectCollationInfo for Runtime { + fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { + ParachainSystem::collect_collation_info(header) + } + } + + #[cfg(feature = "async-backing")] + impl cumulus_primitives_aura::AuraUnincludedSegmentApi for Runtime { + fn can_build_upon( + included_hash: ::Hash, + slot: cumulus_primitives_aura::Slot + ) -> bool { + ConsensusHook::can_build_upon(included_hash, slot) + } + } + + #[cfg(feature = "try-runtime")] + impl frame_try_runtime::TryRuntime for Runtime { + fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { + use crate::configs::RuntimeBlockWeights; + + let weight = Executive::try_runtime_upgrade(checks).unwrap(); + (weight, RuntimeBlockWeights::get().max_block) + } + + fn execute_block( + block: Block, + state_root_check: bool, + signature_check: bool, + select: frame_try_runtime::TryStateSelect, + ) -> Weight { + // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to + // have a backtrace here. + Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap() + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(extra: bool) -> ( + Vec, + Vec, + ) { + use frame_benchmarking::{Benchmarking, BenchmarkList}; + use frame_support::traits::StorageInfoTrait; + use frame_system_benchmarking::Pallet as SystemBench; + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + + use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; + + use crate::*; + + let mut list = Vec::::new(); + list_benchmarks!(list, extra); + + let storage_info = AllPalletsWithSystem::storage_info(); + (list, storage_info) + } + + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + ) -> Result, sp_runtime::RuntimeString> { + use frame_benchmarking::{BenchmarkError, Benchmarking, BenchmarkBatch}; + use frame_support::parameter_types; + use cumulus_primitives_core::ParaId; + use frame_system_benchmarking::Pallet as SystemBench; + + use crate::{*, types::*, configs::*, constants::currency::CENTS}; + + #[allow(non_local_definitions)] + impl frame_system_benchmarking::Config for Runtime { + fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); + Ok(()) + } + + fn verify_set_code() { + System::assert_last_event(cumulus_pallet_parachain_system::Event::::ValidationFunctionStored.into()); + } + } + + parameter_types! { + pub const RandomParaId: ParaId = ParaId::new(43211234); + pub ExistentialDepositAsset: Option = Some(( + RelayLocation::get(), + ExistentialDeposit::get() + ).into()); + /// The base fee for the message delivery fees. Kusama is based for the reference. + pub const ToParentBaseDeliveryFee: u128 = CENTS.saturating_mul(3); + pub const InitialTransferAssetAmount: u128 = 4001070000100; + } + pub type PriceForParentDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice< + FeeAssetId, + ToParentBaseDeliveryFee, + TransactionByteFee, + ParachainSystem, + >; + use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; + use xcm::latest::prelude::{Asset, AssetId, Assets as AssetList, Fungible, Location, Parachain, Parent, ParentThen, PalletInstance, GeneralIndex}; + + #[allow(non_local_definitions)] + impl pallet_xcm::benchmarking::Config for Runtime { + type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< + xcm_config::XcmConfig, + ExistentialDepositAsset, + PriceForParentDelivery, + >; + + fn reachable_dest() -> Option { + Some(Parent.into()) + } + + fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { + None + } + + fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { + use frame_support::traits::PalletInfoAccess; + use xcm_primitives::AssetTypeGetter; + use frame_system::RawOrigin; + + // set up fee asset + let fee_location = RelayLocation::get(); + let who: AccountId = frame_benchmarking::whitelisted_caller(); + + let Some(location_v3) = xcm::v3::Location::try_from(fee_location.clone()).ok() else { + return None; + }; + let asset_type = AssetType::Xcm(location_v3); + + let local_asset_id: crate::types::AssetId = asset_type.clone().into(); + let manager_id = AssetManager::account_id(); + let _ = Assets::force_create(RuntimeOrigin::root(), local_asset_id.clone().into(), manager_id.clone(), true, 1); + let _ = Assets::mint( + RawOrigin::Signed(manager_id.clone()).into(), + local_asset_id.into(), + who, + InitialTransferAssetAmount::get(), + ); + AssetManager::set_asset_type_asset_id(asset_type.clone(), local_asset_id.into()); + + // open a mock parachain channel + ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( + RandomParaId::get().into() + ); + + // set up transfer asset + let initial_asset_amount: u128 = InitialTransferAssetAmount::get(); + let (asset_id, _, _) = pallet_assets::benchmarking::create_default_minted_asset::< + Runtime, + () + >(true, initial_asset_amount); + + let asset_id_u128: u128 = asset_id.into(); + let self_reserve = Location { + parents: 0, + interior: [ + PalletInstance(::index() as u8), GeneralIndex(asset_id_u128) + ].into() + }; + + let Some(location_v3) = xcm::v3::Location::try_from(self_reserve.clone()).ok() else { + return None; + }; + let asset_type = AssetType::Xcm(location_v3); + AssetManager::set_asset_type_asset_id(asset_type.clone(), asset_id_u128); + + let asset = Asset { + fun: Fungible(ExistentialDeposit::get()), + id: AssetId(self_reserve.into()) + }.into(); + Some(( + asset, + ParentThen(Parachain(RandomParaId::get().into()).into()).into(), + )) + } + + fn set_up_complex_asset_transfer( + ) -> Option<(AssetList, u32, Location, Box)> { + use frame_support::traits::PalletInfoAccess; + use xcm_primitives::AssetTypeGetter; + // set up local asset + let initial_asset_amount: u128 = 1000000011; + + let (asset_id, _, _) = pallet_assets::benchmarking::create_default_minted_asset::< + Runtime, + () + >(true, initial_asset_amount); + + let asset_id_u128: u128 = asset_id.into(); + + let self_reserve = Location { + parents:0, + interior: [ + PalletInstance(::index() as u8), GeneralIndex(asset_id_u128) + ].into() + }; + + let Some(location_v3) = xcm::v3::Location::try_from(self_reserve.clone()).ok() else { + return None; + }; + let asset_type = AssetType::Xcm(location_v3); + AssetManager::set_asset_type_asset_id(asset_type.clone(), asset_id_u128); + + let destination: xcm::v4::Location = Parent.into(); + + // set up fee asset + let fee_amount: u128 = ::ExistentialDeposit::get(); + let asset_amount: u128 = 10; + let fee_asset: Asset = (self_reserve.clone(), fee_amount).into(); + let transfer_asset: Asset = (self_reserve.clone(), asset_amount).into(); + + let assets: cumulus_primitives_core::Assets = vec![fee_asset.clone(), transfer_asset].into(); + let fee_index: u32 = 0; + + let who = frame_benchmarking::whitelisted_caller(); + + let verify: Box = Box::new(move || { + // verify balance after transfer, decreased by + // transferred amount (and delivery fees) + assert!(Assets::balance(asset_id_u128, &who) <= initial_asset_amount - fee_amount); + }); + + Some((assets, fee_index, destination, verify)) + } + + fn get_asset() -> Asset { + use xcm_primitives::AssetTypeGetter; + let location = Location::parent(); + let asset_id = AssetId(location.clone()); + let asset = Asset { + id: asset_id.clone(), + fun: Fungible(ExistentialDeposit::get()), + }; + let Some(location_v3) = xcm::v3::Location::try_from(location).ok() else { + return asset; + }; + let asset_type = AssetType::Xcm(location_v3); + let local_asset_id: crate::types::AssetId = asset_type.clone().into(); + let manager_id = AssetManager::account_id(); + let _ = Assets::force_create(RuntimeOrigin::root(), local_asset_id.clone().into(), manager_id, true, 1); + AssetManager::set_asset_type_asset_id(asset_type.clone(), local_asset_id); + asset + } + } + + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + + #[allow(non_local_definitions)] + impl cumulus_pallet_session_benchmarking::Config for Runtime {} + + use frame_support::traits::WhitelistedStorageKeys; + let whitelist = AllPalletsWithSystem::whitelisted_storage_keys(); + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + add_benchmarks!(params, batches); + + if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } + Ok(batches) + } + } + + impl sp_genesis_builder::GenesisBuilder for Runtime { + fn build_state(config: Vec) -> sp_genesis_builder::Result { + build_state::(config) + } + + fn get_preset(id: &Option) -> Option> { + get_preset::(id, |_| None) + } + + fn preset_names() -> Vec { + Default::default() + } + } +} + #[cfg(feature = "runtime-benchmarks")] mod benchmark; diff --git a/evm-template/runtime/src/types.rs b/evm-template/runtime/src/types.rs index 63ece021..ce5ae834 100644 --- a/evm-template/runtime/src/types.rs +++ b/evm-template/runtime/src/types.rs @@ -9,7 +9,6 @@ use sp_core::ConstU32; use sp_runtime::{ generic, traits::{BlakeTwo256, IdentifyAccount, Verify}, - MultiAddress, }; use xcm::VersionedLocation; use xcm_builder::{ConvertedConcreteId, PayOverXcm}; @@ -58,7 +57,7 @@ pub type Hash = sp_core::H256; pub type BlockNumber = u32; /// The address format for describing accounts. -pub type Address = MultiAddress; +pub type Address = AccountId; /// Block header type as expected by this runtime. pub type Header = generic::Header; diff --git a/evm-template/runtime/tests/constants_test.rs b/evm-template/runtime/tests/constants_test.rs index 3a81b273..d8e37023 100644 --- a/evm-template/runtime/tests/constants_test.rs +++ b/evm-template/runtime/tests/constants_test.rs @@ -40,7 +40,7 @@ mod runtime_tests { authoring_version: 1, spec_version: 1, impl_version: 0, - apis: evm_runtime_template::apis::RUNTIME_API_VERSIONS, + apis: evm_runtime_template::RUNTIME_API_VERSIONS, transaction_version: 1, state_version: 1, } diff --git a/evm-template/scripts/zombienet.sh b/evm-template/scripts/zombienet.sh index 2dabdf12..137edb71 100755 --- a/evm-template/scripts/zombienet.sh +++ b/evm-template/scripts/zombienet.sh @@ -1,7 +1,7 @@ #!/bin/bash ZOMBIENET_V=v1.3.106 -POLKADOT_V=v1.6.0 +POLKADOT_V=stable2407-1 # Detect the operating system case "$(uname -s)" in @@ -45,7 +45,7 @@ build_polkadot() { pushd /tmp git clone https://github.com/paritytech/polkadot-sdk.git pushd polkadot-sdk - git checkout release-polkadot-$POLKADOT_V + git checkout polkadot-$POLKADOT_V echo "building polkadot executable..." cargo build --release --features fast-runtime cp target/release/polkadot "$CWD/$BIN_DIR" @@ -55,27 +55,12 @@ build_polkadot() { popd } -fetch_polkadot() { - echo "fetching from polkadot repository..." - echo $BIN_DIR - mkdir -p "$BIN_DIR" - pushd "$BIN_DIR" - wget https://github.com/paritytech/polkadot-sdk/releases/download/polkadot-$POLKADOT_V/polkadot - wget https://github.com/paritytech/polkadot-sdk/releases/download/polkadot-$POLKADOT_V/polkadot-execute-worker - wget https://github.com/paritytech/polkadot-sdk/releases/download/polkadot-$POLKADOT_V/polkadot-prepare-worker - chmod +x * - popd -} - zombienet_init() { if [ ! -f $ZOMBIENET_BIN ]; then echo "fetching zombienet executable..." curl -LO https://github.com/paritytech/zombienet/releases/download/$ZOMBIENET_V/$ZOMBIENET_BIN chmod +x $ZOMBIENET_BIN fi - if [ ! -f $BIN_DIR/polkadot ]; then - fetch_polkadot - fi } zombienet_build() { @@ -92,7 +77,7 @@ zombienet_build() { zombienet_devnet() { zombienet_init cargo build --release - echo "spawning rococo-local relay chain plus devnet as a parachain..." + echo "spawning paseo-local relay chain plus devnet as a parachain..." local dir=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) ./$ZOMBIENET_BIN spawn "$dir/../zombienet-config/devnet.toml" -p native } @@ -103,7 +88,7 @@ print_help() { echo "" echo "$ ./zombienet.sh init # fetches zombienet and polkadot executables" echo "$ ./zombienet.sh build # builds polkadot executables from source" - echo "$ ./zombienet.sh devnet # spawns a rococo-local relay chain plus parachain devnet-local as a parachain" + echo "$ ./zombienet.sh devnet # spawns a paseo-local relay chain plus parachain devnet-local as a parachain" } SUBCOMMAND=$1 diff --git a/evm-template/zombienet-config/devnet.toml b/evm-template/zombienet-config/devnet.toml index 92492415..0be2b612 100644 --- a/evm-template/zombienet-config/devnet.toml +++ b/evm-template/zombienet-config/devnet.toml @@ -1,6 +1,6 @@ [relaychain] -chain = "rococo-local" -default_command = "./bin-v1.6.0/polkadot" +chain = "paseo-local" +default_command = "./bin-stable2407-1/polkadot" [[relaychain.nodes]] name = "alice" diff --git a/generic-template/node/Cargo.toml b/generic-template/node/Cargo.toml index 83061d8a..758ae40b 100644 --- a/generic-template/node/Cargo.toml +++ b/generic-template/node/Cargo.toml @@ -54,7 +54,7 @@ substrate-frame-rpc-system = { workspace = true } substrate-prometheus-endpoint = { workspace = true } # Polkadot -polkadot-cli = { workspace = true, features = [ "rococo-native" ] } +polkadot-cli = { workspace = true } polkadot-primitives = { workspace = true } xcm = { workspace = true } diff --git a/generic-template/node/src/chain_spec.rs b/generic-template/node/src/chain_spec.rs index afaaeaa2..46eca8b0 100644 --- a/generic-template/node/src/chain_spec.rs +++ b/generic-template/node/src/chain_spec.rs @@ -76,7 +76,7 @@ pub fn development_config() -> ChainSpec { ChainSpec::builder( generic_runtime_template::WASM_BINARY.expect("WASM binary was not built, please build it!"), Extensions { - relay_chain: "rococo-local".into(), + relay_chain: "paseo-local".into(), // You MUST set this to the correct network! para_id: 1000, }, @@ -127,7 +127,7 @@ pub fn local_testnet_config() -> ChainSpec { ChainSpec::builder( generic_runtime_template::WASM_BINARY.expect("WASM binary was not built, please build it!"), Extensions { - relay_chain: "rococo-local".into(), + relay_chain: "paseo-local".into(), // You MUST set this to the correct network! para_id: 1000, }, diff --git a/generic-template/node/src/cli.rs b/generic-template/node/src/cli.rs index 8b01cf3a..bb29b67a 100644 --- a/generic-template/node/src/cli.rs +++ b/generic-template/node/src/cli.rs @@ -49,12 +49,12 @@ const AFTER_HELP_EXAMPLE: &str = color_print::cstr!( r#"Examples: parachain-template-node build-spec --disable-default-bootnode > plain-parachain-chainspec.json Export a chainspec for a local testnet in json format. - parachain-template-node --chain plain-parachain-chainspec.json --tmp -- --chain rococo-local + parachain-template-node --chain plain-parachain-chainspec.json --tmp -- --chain paseo-local Launch a full node with chain specification loaded from plain-parachain-chainspec.json. parachain-template-node - Launch a full node with default parachain local-testnet and relay chain rococo-local. + Launch a full node with default parachain local-testnet and relay chain paseo-local. parachain-template-node --collator - Launch a collator with default parachain local-testnet and relay chain rococo-local. + Launch a collator with default parachain local-testnet and relay chain paseo-local. "# ); #[derive(Debug, clap::Parser)] diff --git a/generic-template/node/src/command.rs b/generic-template/node/src/command.rs index 00a805c1..0fe079c4 100644 --- a/generic-template/node/src/command.rs +++ b/generic-template/node/src/command.rs @@ -21,7 +21,7 @@ use crate::{ fn load_spec(id: &str) -> std::result::Result, String> { Ok(match id { "dev" => Box::new(chain_spec::development_config()), - "template-rococo" => Box::new(chain_spec::local_testnet_config()), + "template-paseo" => Box::new(chain_spec::local_testnet_config()), "" | "local" => Box::new(chain_spec::local_testnet_config()), path => Box::new(chain_spec::ChainSpec::from_json_file(std::path::PathBuf::from(path))?), }) diff --git a/generic-template/runtime/src/configs/mod.rs b/generic-template/runtime/src/configs/mod.rs index 639fbef2..c460105e 100644 --- a/generic-template/runtime/src/configs/mod.rs +++ b/generic-template/runtime/src/configs/mod.rs @@ -48,7 +48,7 @@ use crate::{ constants::{ currency::{deposit, CENTS, EXISTENTIAL_DEPOSIT, GRAND, MICROCENTS}, AVERAGE_ON_INITIALIZE_RATIO, DAYS, HOURS, MAXIMUM_BLOCK_WEIGHT, MAX_BLOCK_LENGTH, - NORMAL_DISPATCH_RATIO, VERSION, + NORMAL_DISPATCH_RATIO, SLOT_DURATION, VERSION, }, types::{ AccountId, AssetKind, Balance, Beneficiary, Block, BlockNumber, @@ -512,7 +512,7 @@ impl pallet_aura::Config for Runtime { type AuthorityId = AuraId; type DisabledValidators = (); type MaxAuthorities = MaxAuthorities; - type SlotDuration = pallet_aura::MinimumPeriodTimesTwo; + type SlotDuration = ConstU64; } parameter_types! { diff --git a/generic-template/runtime/src/lib.rs b/generic-template/runtime/src/lib.rs index c64d062c..9f597175 100644 --- a/generic-template/runtime/src/lib.rs +++ b/generic-template/runtime/src/lib.rs @@ -54,7 +54,7 @@ impl WeightToFeePolynomial for WeightToFee { type Balance = Balance; fn polynomial() -> WeightToFeeCoefficients { - // in Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1 + // in Paseo, extrinsic base weight (smallest non-zero weight) is mapped to 1 // MILLIUNIT: in our template, we map to 1/10 of that, or 1/10 MILLIUNIT let p = MILLICENTS / P_FACTOR; let q = Q_FACTOR * Balance::from(ExtrinsicBaseWeight::get().ref_time()); diff --git a/generic-template/scripts/zombienet.sh b/generic-template/scripts/zombienet.sh index 2dabdf12..b4c751e7 100755 --- a/generic-template/scripts/zombienet.sh +++ b/generic-template/scripts/zombienet.sh @@ -1,7 +1,7 @@ #!/bin/bash ZOMBIENET_V=v1.3.106 -POLKADOT_V=v1.6.0 +POLKADOT_V=stable-2407-01 # Detect the operating system case "$(uname -s)" in @@ -92,7 +92,7 @@ zombienet_build() { zombienet_devnet() { zombienet_init cargo build --release - echo "spawning rococo-local relay chain plus devnet as a parachain..." + echo "spawning paseo-local relay chain plus devnet as a parachain..." local dir=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) ./$ZOMBIENET_BIN spawn "$dir/../zombienet-config/devnet.toml" -p native } @@ -103,7 +103,7 @@ print_help() { echo "" echo "$ ./zombienet.sh init # fetches zombienet and polkadot executables" echo "$ ./zombienet.sh build # builds polkadot executables from source" - echo "$ ./zombienet.sh devnet # spawns a rococo-local relay chain plus parachain devnet-local as a parachain" + echo "$ ./zombienet.sh devnet # spawns a paseo-local relay chain plus parachain devnet-local as a parachain" } SUBCOMMAND=$1 diff --git a/generic-template/zombienet-config/devnet.toml b/generic-template/zombienet-config/devnet.toml index e7346c8f..d59efefd 100644 --- a/generic-template/zombienet-config/devnet.toml +++ b/generic-template/zombienet-config/devnet.toml @@ -1,5 +1,5 @@ [relaychain] -chain = "rococo-local" +chain = "paseo-local" default_command = "./bin-v1.6.0/polkadot" [[relaychain.nodes]]