diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 11c67e2af..96a48dacf 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -32,13 +32,11 @@ jobs: with: submodules: recursive - name: Install toolchain - uses: actions-rs/toolchain@v1 + uses: dtolnay/rust-toolchain@nightly with: - profile: minimal - toolchain: nightly-2022-08-05 + toolchain: nightly-2022-10-30 components: rustfmt target: wasm32-unknown-unknown - default: true - name: Generate code coverage run: | wget https://github.com/xd009642/tarpaulin/releases/download/${{ env.TARPAULIN_VERSION }}/cargo-tarpaulin-${{ env.TARPAULIN_VERSION }}-travis.tar.gz @@ -46,6 +44,7 @@ jobs: make Cargo.toml cargo tarpaulin --verbose --no-fail-fast --workspace --timeout 300 --out Xml - name: Upload to codecov.io - uses: codecov/codecov-action@v2 + uses: codecov/codecov-action@v3 with: + token: ${{ secrets.CODECOV_TOKEN }} fail_ci_if_error: true diff --git a/.github/workflows/master.yml.disabled b/.github/workflows/master.yml.disabled index c42472afe..a1bdac623 100644 --- a/.github/workflows/master.yml.disabled +++ b/.github/workflows/master.yml.disabled @@ -13,12 +13,9 @@ jobs: steps: - uses: actions/checkout@v3 - name: Install toolchain - uses: actions-rs/toolchain@v1 + uses: dtolnay/rust-toolchain@nightly with: - profile: minimal - toolchain: nightly-2022-08-05 - override: true - default: true + toolchain: nightly-2022-10-30 - name: Install cargo-unleash run: cargo install cargo-unleash --git https://github.com/xlc/cargo-unleash.git # https://github.com/paritytech/cargo-unleash/pull/38 - name: Prepare diff --git a/.github/workflows/publish_packages.yml b/.github/workflows/publish_packages.yml index 356061838..5d4a21142 100644 --- a/.github/workflows/publish_packages.yml +++ b/.github/workflows/publish_packages.yml @@ -10,10 +10,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - uses: actions-rs/toolchain@v1 + - uses: dtolnay/rust-toolchain@stable with: toolchain: stable - override: true - run: make Cargo.toml - run: cargo install cargo-unleash --git https://github.com/xlc/cargo-unleash.git # https://github.com/paritytech/cargo-unleash/pull/38 - run: cargo unleash em-dragons diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 89ac1033e..6b8f74e5f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -4,11 +4,13 @@ on: pull_request: branches: - master + - polkadot-** paths-ignore: - '**/README.md' push: branches: - master + - polkadot-** paths-ignore: - '**/README.md' @@ -30,14 +32,11 @@ jobs: steps: - uses: actions/checkout@v3 - name: Install toolchain - uses: actions-rs/toolchain@v1 + uses: dtolnay/rust-toolchain@nightly with: - profile: minimal - toolchain: nightly-2022-08-05 + toolchain: nightly-2022-10-30 components: rustfmt target: wasm32-unknown-unknown - override: true - default: true - name: Install Wasm toolchain run: rustup target add wasm32-unknown-unknown - name: Check format diff --git a/Cargo.dev.toml b/Cargo.dev.toml index 2b277bc5f..f59a2f46e 100644 --- a/Cargo.dev.toml +++ b/Cargo.dev.toml @@ -4,6 +4,7 @@ members = [ "auction", "authority", "bencher", + "bencher/test", "benchmarking", "currencies", "gradually-update", @@ -11,6 +12,8 @@ members = [ "oracle/rpc", "oracle/rpc/runtime-api", "tokens", + "tokens/rpc", + "tokens/rpc/runtime-api", "traits", "utilities", "vesting", @@ -25,6 +28,8 @@ members = [ "weight-meter", ] +exclude = ["bencher/test"] + resolver = "2" [profile.dev] @@ -45,7 +50,6 @@ frame-system = { git = "https://github.com/mangata-finance//substrate", branch = pallet-beefy = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } pallet-membership = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } frame-benchmarking = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } -pallet-gilt = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } pallet-identity = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } pallet-session = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } pallet-aura = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } @@ -70,7 +74,6 @@ pallet-democracy = { git = "https://github.com/mangata-finance//substrate", bran pallet-grandpa = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } frame-election-provider-support = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } pallet-collective = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } -pallet-mmr-rpc = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } pallet-mmr = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } #pallet-mmr-primitives = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } pallet-uniques = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } @@ -138,7 +141,6 @@ substrate-wasm-builder = { git = "https://github.com/mangata-finance//substrate" try-runtime-cli = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } frame-benchmarking-cli = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } substrate-frame-rpc-system = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } -remote-externalities = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } substrate-build-script-utils = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } substrate-prometheus-endpoint = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } pallet-template = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } @@ -152,7 +154,8 @@ sp-authorship = { git = "https://github.com/mangata-finance//substrate", branch sp-storage = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } sp-std = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } sp-finality-grandpa = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } -beefy-primitives = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } +beefy-primitives = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev", package = "sp-beefy" } +remote-externalities = { git = "https://github.com/mangata-finance//substrate" } sp-version-proc-macro = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } sp-version = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } sp-transaction-pool = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } @@ -165,7 +168,6 @@ sp-core-hashing = { git = "https://github.com/mangata-finance//substrate", branc sp-core = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } sp-keyring = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } sp-authority-discovery = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } -sp-tasks = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } sp-runtime-interface-proc-macro = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } sp-runtime-interface = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } sp-arithmetic = { git = "https://github.com/mangata-finance//substrate", branch = "mangata-dev" } diff --git a/Makefile b/Makefile index 51dfe8fe8..c57206900 100644 --- a/Makefile +++ b/Makefile @@ -44,9 +44,11 @@ dev-check: Cargo.toml check dev-check-tests: Cargo.toml cargo check --tests --all + cargo check --tests --features=bench --package=orml-weight-meter --package=orml-bencher-test dev-test: Cargo.toml - cargo test --all --features runtime-benchmarks + cargo test --all --features=runtime-benchmarks + cargo test --features=bench --package=orml-weight-meter --package=orml-bencher-test # run benchmarks via Acala node benchmark-all: diff --git a/README.md b/README.md index bc6e44106..62ede983b 100644 --- a/README.md +++ b/README.md @@ -8,29 +8,53 @@ The Open Runtime Module Library (ORML) is a community maintained collection of S ## Runtime Modules Overview -- [orml-auction](./auction) - - Auction module that implements `Auction` trait. -- [orml-currencies](./currencies) - - Provide `MultiCurrency` implementation using `pallet-balances` and `orml-tokens` module. -- [orml-gradually-update](./gradually-update) +#### Utility +- [auction](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/auction) + - Implements a generalized auction interface, used by Acala for liquidation auctions. +- [authority](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/authority) + - Allow more advanced permission configuration such as timelock for governance actions. +- [gradually-update](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/gradually-update) - Provides way to adjust numeric parameter gradually over a period of time. -- [orml-nft](./nft) - - Non-fungible-token module provides basic functions to create and manager NFT(non fungible token) such as `create_class`, `transfer`, `mint`, `burn`, `destroy_class`. -- [orml-oracle](./oracle) - - Oracle module that makes off-chain data available on-chain. -- [orml-tokens](./tokens) - - Fungible tokens module that implements `MultiCurrency` trait. -- [orml-traits](./traits) - - Shared traits including `BasicCurrency`, `MultiCurrency`, `Auction` and more. -- [orml-utilities](./utilities) - - Various utilities including `OrderSet`. -- [orml-vesting](./vesting) +- [oracle](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/oracle) + - Allow offchain oracle providers to feed data to be consumed by onchain pallets. +- [rewards](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/rewards) + - Implements ability to calculate and distribute token staking rewards. +- [traits](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/traits) + - Implements various utility traits including BasicCurrency, MultiCurrency, Auction and more. Used by other ORML pallets. + +#### Tokens +- [asset-registry](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/asset-registry) + - Register asset / token metadata including name, decimals, and XCM MultiLocation + - Partially based on the Acala’s asset-registry pallet, which includes some Acala specific code (e.g. EVM+) so not suitable for other teams. +- [currencies](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/currencies) + - Provide an unified interface to combine pallet-balances and orml-tokens +- [nft](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/nft) + - Provide a non-fungible-token implementation +- [payments](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/payments) + - This pallet allows users to create secure reversible payments that keep funds locked in a merchant’s account until the off-chain goods are confirmed to be received. Each payment gets assigned its own judge that can help resolve any disputes between the two parties. +- [tokens](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/tokens) + - Implements fungible tokens pallet with compatibility with Substrate tokens abstractions +- [vesting](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/vesting) - Provides scheduled balance locking mechanism, in a *graded vesting* way. -- [orml-xcm-support](./xcm-support) - - Provides traits, types, and implementations to support XCM integration. -- [orml-xtokens](./xtokens) - - Provides way to do cross-chain assets transfer. - - [Step-by-Step guide](https://github.com/open-web3-stack/open-runtime-module-library/wiki/xtokens) to make XCM cross-chain fungible asset transfer available on your parachain + +#### XCM +- [xcm-support](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/xcm-support) + - Provides supporting traits, types and implementations, to support cross-chain message(XCM) integration with ORML modules. +- [xcm](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/xcm) + - Provides a way for governance body to dispatch XCM. +- [xtokens](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/xtokens) + - Provide crosschain token transfer functionality. + - Used by multiple parachains for their XCM token transfer implementation. + +#### Benchmarking +- [bencher](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/bencher) + - Benchmarking tool using cargo bench for benchmarking +- [benchmarking](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/benchmarking) + - Fork of frame-benchmarking in Substrate to allow implement runtime specific benchmarks +- [weight-gen](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/weight-gen) + - Weight meter file generation +- [weight-meter](https://github.com/open-web3-stack/open-runtime-module-library/tree/master/weight-meter) + - A low overhead dynamic weight meter ## Example @@ -64,9 +88,12 @@ ORML is part of the bigger `Open-Web3-Stack` initiative, that is currently under _In alphabetical order_ - [Acala Network](https://github.com/AcalaNetwork/Acala) +- [Astar Network](https://github.com/AstarNetwork) - [Bifrost Finance](https://github.com/bifrost-finance/bifrost) - [Bit.Country](https://github.com/bit-country/Bit-Country-Blockchain) +- [Centrifuge](https://github.com/centrifuge/centrifuge-chain) - [ChainX](https://github.com/chainx-org/ChainX) +- [Crust](https://github.com/crustio/crust) - [GameDAO Protocol](https://github.com/gamedaoco) - [HydraDX](https://github.com/galacticcouncil/hack.HydraDX-node) - [Interlay and Kintsugi](https://github.com/interlay/interbtc) @@ -77,7 +104,6 @@ _In alphabetical order_ - [Manta Network](https://github.com/Manta-Network) - [Minterest](https://github.com/minterest-finance/minterest-chain-node) - [OAK](https://github.com/OAK-Foundation/OAK-blockchain) -- [Plasm Network](https://github.com/PlasmNetwork) - [PolkaFoundry Network](https://github.com/PolkaFoundry) - [Setheum Network](https://github.com/Setheum-Labs/Setheum) - [Valiu Liquidity Network](https://github.com/valibre-org/vln-node) diff --git a/asset-registry/Cargo.toml b/asset-registry/Cargo.toml index 32ba03193..6b121d52a 100644 --- a/asset-registry/Cargo.toml +++ b/asset-registry/Cargo.toml @@ -13,17 +13,17 @@ serde = { version = "1.0.136", optional = true } codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["max-encoded-len"] } # substrate -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31", default-features = false , optional = true } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36", default-features = false , optional = true } # polkadot -pallet-xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.31" } -xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.31" } -xcm-builder = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.31" } -xcm-executor = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.31" } +pallet-xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.36" } +xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.36" } +xcm-builder = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.36" } +xcm-executor = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.36" } # orml orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false } @@ -34,55 +34,58 @@ mangata-types = { git = "https://github.com/mangata-finance/substrate", default- [dev-dependencies] # substrate -sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } # cumulus -cumulus-primitives-core = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.31" } -cumulus-pallet-dmp-queue = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.31" } -cumulus-pallet-xcmp-queue = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.31" } -cumulus-pallet-xcm = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.31" } -parachain-info = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.31" } +cumulus-primitives-core = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.36" } +cumulus-pallet-dmp-queue = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.36" } +cumulus-pallet-xcmp-queue = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.36" } +cumulus-pallet-xcm = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.36" } +parachain-info = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.36" } # polkadot -polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.31" } -polkadot-runtime-parachains = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.31" } -xcm-simulator = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.31" } +polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.36" } +polkadot-runtime-parachains = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.36" } +xcm-simulator = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.36" } # orml orml-tokens = { path = "../tokens" } -orml-xtokens = { path = "../xtokens" } orml-xcm = { path = "../xcm" } orml-xcm-support = { path = "../xcm-support", default-features = false } +orml-xtokens = { path = "../xtokens" } [features] default = ["std"] std = [ "serde", + "codec/std", - "scale-info/std", - "sp-runtime/std", - "sp-std/std", "frame-support/std", "frame-system/std", "frame-benchmarking/std", "orml-traits/std", "pallet-xcm/std", - "xcm/std", + "scale-info/std", + "sp-runtime/std", + "sp-std/std", "xcm-builder/std", "xcm-executor/std", - "mangata-types/std" + "mangata-types/std", + "xcm/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", "pallet-xcm/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", + "xcm-executor/runtime-benchmarks", ] - try-runtime = [ - "frame-system/try-runtime", "frame-support/try-runtime", + "frame-system/try-runtime", + "pallet-xcm/try-runtime", ] diff --git a/asset-registry/src/impls.rs b/asset-registry/src/impls.rs index b49b486e2..744263669 100644 --- a/asset-registry/src/impls.rs +++ b/asset-registry/src/impls.rs @@ -1,4 +1,5 @@ -use frame_support::{log, pallet_prelude::*, weights::constants::WEIGHT_PER_SECOND}; +use crate::module::*; +use frame_support::{log, pallet_prelude::*, weights::constants::{WEIGHT_REF_TIME_PER_SECOND}}; use orml_traits::{ asset_registry::{AssetMetadata, FixedConversionRateProvider, Inspect, Mutate, WeightToFeeConverter}, GetByKey, @@ -53,7 +54,7 @@ pub struct FixedRateAssetRegistryTrader(PhantomD impl WeightToFeeConverter for FixedRateAssetRegistryTrader

{ fn convert_weight_to_fee(location: &MultiLocation, weight: Weight) -> Option { let fee_per_second = P::get_fee_per_second(location)?; - let weight_ratio = FixedU128::saturating_from_rational(weight.ref_time(), WEIGHT_PER_SECOND.ref_time() as u128); + let weight_ratio = FixedU128::saturating_from_rational(weight.ref_time(), WEIGHT_REF_TIME_PER_SECOND); let amount = weight_ratio.saturating_mul_int(fee_per_second); Some(amount) } diff --git a/asset-registry/src/lib.rs b/asset-registry/src/lib.rs index b99e80431..b6a64e3d5 100644 --- a/asset-registry/src/lib.rs +++ b/asset-registry/src/lib.rs @@ -131,6 +131,7 @@ pub mod module { #[pallet::call] impl Pallet { + #[pallet::call_index(0)] #[pallet::weight(T::WeightInfo::register_asset())] #[transactional] pub fn register_asset( @@ -143,6 +144,7 @@ pub mod module { Self::do_register_asset(metadata, asset_id) } + #[pallet::call_index(1)] #[pallet::weight(T::WeightInfo::update_asset())] #[transactional] pub fn update_asset( @@ -304,7 +306,7 @@ impl Pallet { fn do_insert_location(asset_id: T::AssetId, location: VersionedMultiLocation) -> DispatchResult { // if the metadata contains a location, set the LocationToAssetId let location: MultiLocation = location.try_into().map_err(|()| Error::::BadVersion)?; - LocationToAssetId::::try_mutate(&location, |maybe_asset_id| { + LocationToAssetId::::try_mutate(location, |maybe_asset_id| { ensure!(maybe_asset_id.is_none(), Error::::ConflictingLocation); *maybe_asset_id = Some(asset_id); Ok(()) diff --git a/asset-registry/src/mock/para.rs b/asset-registry/src/mock/para.rs index 3e4f45b69..a3f226eca 100644 --- a/asset-registry/src/mock/para.rs +++ b/asset-registry/src/mock/para.rs @@ -10,7 +10,7 @@ use frame_support::traits::{EnsureOrigin, EnsureOriginWithArg}; use frame_support::{ construct_runtime, match_types, ord_parameter_types, parameter_types, traits::{ConstU128, ConstU32, ConstU64, Everything, Nothing}, - weights::constants::WEIGHT_PER_SECOND, + weights::constants::WEIGHT_REF_TIME_PER_SECOND, PalletId, }; use frame_system::{EnsureRoot, EnsureSignedBy}; @@ -92,16 +92,11 @@ impl orml_tokens::Config for Runtime { type CurrencyId = CurrencyId; type WeightInfo = (); type ExistentialDeposits = ExistentialDeposits; - type OnDust = (); - type OnSlash = (); - type OnDeposit = (); - type OnTransfer = (); + type CurrencyHooks = (); type ReserveIdentifier = [u8; 8]; type MaxReserves = (); type MaxLocks = ConstU32<50>; type DustRemovalWhitelist = Nothing; - type OnNewTokenAccount = (); - type OnKilledTokenAccount = (); } #[derive(scale_info::TypeInfo, Encode, Decode, Clone, Eq, PartialEq, Debug)] @@ -174,8 +169,8 @@ impl orml_asset_registry::Config for Runtime { } parameter_types! { - pub const ReservedXcmpWeight: Weight = WEIGHT_PER_SECOND.ref_time() / 4; - pub const ReservedDmpWeight: Weight = WEIGHT_PER_SECOND.ref_time() / 4; + pub const ReservedXcmpWeight: Weight = WEIGHT_REF_TIME_PER_SECOND / 4; + pub const ReservedDmpWeight: Weight = WEIGHT_REF_TIME_PER_SECOND / 4; } impl parachain_info::Config for Runtime {} diff --git a/asset-registry/src/tests.rs b/asset-registry/src/tests.rs index 5815b5490..23f0842e9 100644 --- a/asset-registry/src/tests.rs +++ b/asset-registry/src/tests.rs @@ -361,7 +361,15 @@ fn test_register_duplicate_location_returns_error() { ParaA::execute_with(|| { let metadata = dummy_metadata(); - assert_ok!(AssetRegistry::register_asset(RuntimeOrigin::root(), metadata.clone(), None)); + assert_ok!(AssetRegistry::register_asset( + RuntimeOrigin::root(), + metadata.clone(), + None + )); + let register_asset = RuntimeCall::AssetRegistry(crate::Call::::register_asset { + metadata: metadata.clone(), + asset_id: None, + }); assert_noop!( AssetRegistry::do_register_asset_without_asset_processor(metadata.clone(), 2), Error::::ConflictingLocation diff --git a/auction/Cargo.toml b/auction/Cargo.toml index fd464166e..034d2d97b 100644 --- a/auction/Cargo.toml +++ b/auction/Cargo.toml @@ -8,34 +8,35 @@ authors = ["Acala Developers"] edition = "2021" [dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } serde = { version = "1.0.136", optional = true } -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false } [dev-dependencies] -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } [features] default = ["std"] std = [ "serde", + "codec/std", - "scale-info/std", - "sp-runtime/std", - "sp-std/std", "frame-support/std", "frame-system/std", "orml-traits/std", + "scale-info/std", + "sp-runtime/std", + "sp-std/std", ] try-runtime = [ - "frame-system/try-runtime", "frame-support/try-runtime", + "frame-system/try-runtime", ] diff --git a/auction/src/lib.rs b/auction/src/lib.rs index 7874a28e8..5c4e00010 100644 --- a/auction/src/lib.rs +++ b/auction/src/lib.rs @@ -109,12 +109,12 @@ pub mod module { #[pallet::hooks] impl Hooks for Pallet { fn on_initialize(now: T::BlockNumber) -> Weight { - T::WeightInfo::on_finalize(AuctionEndTime::::iter_prefix(&now).count() as u32) + T::WeightInfo::on_finalize(AuctionEndTime::::iter_prefix(now).count() as u32) } fn on_finalize(now: T::BlockNumber) { - for (auction_id, _) in AuctionEndTime::::drain_prefix(&now) { - if let Some(auction) = Auctions::::take(&auction_id) { + for (auction_id, _) in AuctionEndTime::::drain_prefix(now) { + if let Some(auction) = Auctions::::take(auction_id) { T::Handler::on_auction_ended(auction_id, auction.bid); } } @@ -127,6 +127,7 @@ pub mod module { /// /// The dispatch origin for this call must be `Signed` by the /// transactor. + #[pallet::call_index(0)] #[pallet::weight(T::WeightInfo::bid_collateral_auction())] pub fn bid(origin: OriginFor, id: T::AuctionId, #[pallet::compact] value: T::Balance) -> DispatchResult { let from = ensure_signed(origin)?; @@ -150,10 +151,10 @@ pub mod module { match bid_result.auction_end_change { Change::NewValue(new_end) => { if let Some(old_end_block) = auction.end { - AuctionEndTime::::remove(&old_end_block, id); + AuctionEndTime::::remove(old_end_block, id); } if let Some(new_end_block) = new_end { - AuctionEndTime::::insert(&new_end_block, id, ()); + AuctionEndTime::::insert(new_end_block, id, ()); } auction.end = new_end; } @@ -188,10 +189,10 @@ impl Auction for Pallet { ) -> DispatchResult { let auction = Auctions::::get(id).ok_or(Error::::AuctionNotExist)?; if let Some(old_end) = auction.end { - AuctionEndTime::::remove(&old_end, id); + AuctionEndTime::::remove(old_end, id); } if let Some(new_end) = info.end { - AuctionEndTime::::insert(&new_end, id, ()); + AuctionEndTime::::insert(new_end, id, ()); } Auctions::::insert(id, info); Ok(()) @@ -210,14 +211,14 @@ impl Auction for Pallet { })?; Auctions::::insert(auction_id, auction); if let Some(end_block) = end { - AuctionEndTime::::insert(&end_block, auction_id, ()); + AuctionEndTime::::insert(end_block, auction_id, ()); } Ok(auction_id) } fn remove_auction(id: Self::AuctionId) { - if let Some(auction) = Auctions::::take(&id) { + if let Some(auction) = Auctions::::take(id) { if let Some(end_block) = auction.end { AuctionEndTime::::remove(end_block, id); } diff --git a/authority/Cargo.toml b/authority/Cargo.toml index 76410e7c2..b58121a69 100644 --- a/authority/Cargo.toml +++ b/authority/Cargo.toml @@ -8,26 +8,30 @@ authors = ["Acala Developers"] edition = "2021" [dependencies] + scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } serde = { version = "1.0.145", optional = true } codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-core = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } [dev-dependencies] -sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -pallet-scheduler = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -pallet-preimage = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +pallet-preimage = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +pallet-scheduler = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +pallet-root-testing = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } + [features] default = ["std"] std = [ "serde", + "codec/std", "scale-info/std", "sp-runtime/std", @@ -35,12 +39,19 @@ std = [ "sp-io/std", "frame-support/std", "frame-system/std", + "scale-info/std", + "sp-core/std", + "sp-io/std", + "sp-runtime/std", + "sp-std/std", ] runtime-benchmarks = [ "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", ] try-runtime = [ - "frame-system/try-runtime", "frame-support/try-runtime", + "frame-system/try-runtime", ] + diff --git a/authority/src/lib.rs b/authority/src/lib.rs index cc49a9074..506f96578 100644 --- a/authority/src/lib.rs +++ b/authority/src/lib.rs @@ -11,6 +11,13 @@ //! Two functionalities are provided by this module: //! - schedule a dispatchable //! - dispatch method with on behalf of other origins +//! +//! NOTE: +//! +//! In order to derive a feasible max encoded len for `DelayedOrigin`, it is +//! assumed that there are no nested `DelayedOrigin` in `OriginCaller`. +//! In practice, this means there should not be nested `schedule_dispatch`. +//! Otherwise the proof size estimation may not be accurate. #![cfg_attr(not(feature = "std"), no_std)] // Disable the following three lints since they originate from an external macro @@ -32,6 +39,7 @@ use frame_support::{ }; use frame_system::{pallet_prelude::*, EnsureRoot, EnsureSigned}; use scale_info::TypeInfo; +use sp_core::defer; use sp_runtime::{ traits::{CheckedSub, Dispatchable, Hash, Saturating}, ArithmeticError, DispatchError, DispatchResult, Either, RuntimeDebug, @@ -45,12 +53,71 @@ mod weights; pub use weights::WeightInfo; /// A delayed origin. Can only be dispatched via `dispatch_as` with a delay. -#[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)] +#[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode, TypeInfo)] pub struct DelayedOrigin { /// Number of blocks that this call have been delayed. - pub delay: BlockNumber, + pub(crate) delay: BlockNumber, /// The initial origin. - pub origin: Box, + pub(crate) origin: Box, +} + +#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))] +impl DelayedOrigin { + pub fn new(delay: BlockNumber, origin: Box) -> Self { + Self { delay, origin } + } +} + +#[cfg(feature = "std")] +mod helper { + use std::cell::RefCell; + + thread_local! { + static NESTED_MAX_ENCODED_LEN: RefCell = RefCell::new(false); + } + + pub fn set_nested_max_encoded_len(val: bool) { + NESTED_MAX_ENCODED_LEN.with(|v| *v.borrow_mut() = val); + } + + pub fn nested_max_encoded_len() -> bool { + NESTED_MAX_ENCODED_LEN.with(|v| *v.borrow()) + } +} + +#[cfg(not(feature = "std"))] +mod helper { + static mut NESTED_MAX_ENCODED_LEN: bool = false; + + pub fn set_nested_max_encoded_len(val: bool) { + unsafe { + NESTED_MAX_ENCODED_LEN = val; + } + } + + pub fn nested_max_encoded_len() -> bool { + unsafe { NESTED_MAX_ENCODED_LEN } + } +} + +// Manual implementation to break recursive calls of `MaxEncodedLen` as the +// implementation of `PalletsOrigin::max_encoded_len` will also call +// `MaxEncodedLen` on `DelayedOrigin`. This is only safe if there are no nested +// `DelayedOrigin`. It is only possible to construct a `DelayedOrigin` via +// `schedule_dispatch` which is a protected call only accessible via governance. +impl MaxEncodedLen + for DelayedOrigin +{ + fn max_encoded_len() -> usize { + if helper::nested_max_encoded_len() { + return 0; + } + + helper::set_nested_max_encoded_len(true); + defer!(helper::set_nested_max_encoded_len(false)); + + BlockNumber::max_encoded_len() + PalletsOrigin::max_encoded_len() + } } /// Ensure the origin have a minimum amount of delay. @@ -99,10 +166,10 @@ pub trait AuthorityConfig { new_delay: BlockNumber, ) -> DispatchResult; /// Check if the `origin` is allow to delay a scheduled task that - /// initially created by `inital_origin`. + /// initially created by `initial_origin`. fn check_delay_schedule(origin: Origin, initial_origin: &PalletsOrigin) -> DispatchResult; /// Check if the `origin` is allow to cancel a scheduled task that - /// initially created by `inital_origin`. + /// initially created by `initial_origin`. fn check_cancel_schedule(origin: Origin, initial_origin: &PalletsOrigin) -> DispatchResult; } @@ -240,6 +307,7 @@ pub mod module { #[pallet::call] impl Pallet { /// Dispatch a dispatchable on behalf of other origin + #[pallet::call_index(0)] #[pallet::weight({ let info = call.get_dispatch_info(); (T::WeightInfo::dispatch_as().saturating_add(info.weight), info.class) @@ -257,6 +325,7 @@ pub mod module { /// Schedule a dispatchable to be dispatched at later block. /// This is the only way to dispatch a call with `DelayedOrigin`. + #[pallet::call_index(1)] #[pallet::weight(T::WeightInfo::schedule_dispatch_without_delay())] pub fn schedule_dispatch( origin: OriginFor, @@ -308,6 +377,7 @@ pub mod module { } /// Fast track a scheduled dispatchable. + #[pallet::call_index(2)] #[pallet::weight(T::WeightInfo::fast_track_scheduled_dispatch())] pub fn fast_track_scheduled_dispatch( origin: OriginFor, @@ -338,6 +408,7 @@ pub mod module { } /// Delay a scheduled dispatchable. + #[pallet::call_index(3)] #[pallet::weight(T::WeightInfo::delay_scheduled_dispatch())] pub fn delay_scheduled_dispatch( origin: OriginFor, @@ -365,6 +436,7 @@ pub mod module { } /// Cancel a scheduled dispatchable. + #[pallet::call_index(4)] #[pallet::weight(T::WeightInfo::cancel_scheduled_dispatch())] pub fn cancel_scheduled_dispatch( origin: OriginFor, @@ -381,6 +453,7 @@ pub mod module { Ok(()) } + #[pallet::call_index(5)] #[pallet::weight(T::WeightInfo::authorize_call())] pub fn authorize_call( origin: OriginFor, @@ -394,14 +467,15 @@ pub mod module { Ok(()) } + #[pallet::call_index(6)] #[pallet::weight(T::WeightInfo::remove_authorized_call())] pub fn remove_authorized_call(origin: OriginFor, hash: T::Hash) -> DispatchResult { - let root_or_sigend = + let root_or_signed = EitherOfDiverse::, EnsureSigned>::ensure_origin(origin)?; SavedCalls::::try_mutate_exists(hash, |maybe_call| { let (_, maybe_caller) = maybe_call.take().ok_or(Error::::CallNotAuthorized)?; - match root_or_sigend { + match root_or_signed { Either::Left(_) => {} // root, do nothing Either::Right(who) => { // signed, ensure it's the caller @@ -414,6 +488,7 @@ pub mod module { }) } + #[pallet::call_index(7)] #[pallet::weight(( T::WeightInfo::trigger_call().saturating_add((*call_weight_bound).into()), DispatchClass::Operational, @@ -445,6 +520,7 @@ pub mod module { }) } + #[pallet::call_index(8)] #[pallet::weight(( T::WeightInfo::trigger_call().saturating_add(*call_weight_bound), DispatchClass::Operational, diff --git a/authority/src/mock.rs b/authority/src/mock.rs index 1301ba0cc..5709698ff 100644 --- a/authority/src/mock.rs +++ b/authority/src/mock.rs @@ -79,6 +79,8 @@ impl pallet_scheduler::Config for Runtime { type Preimages = Preimage; } +impl pallet_root_testing::Config for Runtime {} + #[derive(Clone, Encode, Decode, Eq, PartialEq, Ord, PartialOrd, Debug, TypeInfo)] pub enum MockAsOriginId { Root, @@ -182,6 +184,7 @@ frame_support::construct_runtime!( Authority: authority::{Pallet, Call, Origin, Event}, Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event}, Preimage: pallet_preimage::{Pallet, Call, Storage, Event}, + RootTesting: pallet_root_testing::{Pallet, Call}, } ); diff --git a/authority/src/tests.rs b/authority/src/tests.rs index f44c2a840..9aa301588 100644 --- a/authority/src/tests.rs +++ b/authority/src/tests.rs @@ -3,6 +3,7 @@ #![cfg(test)] use super::*; +use codec::MaxEncodedLen; use frame_support::{ assert_noop, assert_ok, dispatch::DispatchErrorWithPostInfo, @@ -19,7 +20,8 @@ use sp_runtime::{traits::BadOrigin, Perbill}; #[test] fn dispatch_as_work() { ExtBuilder::default().build().execute_with(|| { - let ensure_root_call = RuntimeCall::System(frame_system::Call::fill_block { ratio: Perbill::one() }); + let ensure_root_call = + RuntimeCall::RootTesting(pallet_root_testing::Call::fill_block { ratio: Perbill::one() }); let ensure_signed_call = RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); assert_ok!(Authority::dispatch_as( RuntimeOrigin::root(), @@ -58,7 +60,7 @@ fn dispatch_as_work() { #[test] fn schedule_dispatch_at_work() { ExtBuilder::default().build().execute_with(|| { - let ensure_root_call = RuntimeCall::System(frame_system::Call::fill_block { + let ensure_root_call = RuntimeCall::RootTesting(pallet_root_testing::Call::fill_block { ratio: Perbill::from_percent(50), }); let call = RuntimeCall::Authority(authority::Call::dispatch_as { @@ -128,7 +130,7 @@ fn schedule_dispatch_at_work() { #[test] fn schedule_dispatch_after_work() { ExtBuilder::default().build().execute_with(|| { - let ensure_root_call = RuntimeCall::System(frame_system::Call::fill_block { + let ensure_root_call = RuntimeCall::RootTesting(pallet_root_testing::Call::fill_block { ratio: Perbill::from_percent(50), }); let call = RuntimeCall::Authority(authority::Call::dispatch_as { @@ -199,7 +201,7 @@ fn schedule_dispatch_after_work() { fn fast_track_scheduled_dispatch_work() { ExtBuilder::default().build().execute_with(|| { System::set_block_number(1); - let ensure_root_call = RuntimeCall::System(frame_system::Call::fill_block { + let ensure_root_call = RuntimeCall::RootTesting(pallet_root_testing::Call::fill_block { ratio: Perbill::from_percent(50), }); let call = RuntimeCall::Authority(authority::Call::dispatch_as { @@ -278,7 +280,7 @@ fn fast_track_scheduled_dispatch_work() { fn delay_scheduled_dispatch_work() { ExtBuilder::default().build().execute_with(|| { System::set_block_number(1); - let ensure_root_call = RuntimeCall::System(frame_system::Call::fill_block { + let ensure_root_call = RuntimeCall::RootTesting(pallet_root_testing::Call::fill_block { ratio: Perbill::from_percent(50), }); let call = RuntimeCall::Authority(authority::Call::dispatch_as { @@ -356,7 +358,7 @@ fn delay_scheduled_dispatch_work() { #[test] fn cancel_scheduled_dispatch_work() { ExtBuilder::default().build().execute_with(|| { - let ensure_root_call = RuntimeCall::System(frame_system::Call::fill_block { + let ensure_root_call = RuntimeCall::RootTesting(pallet_root_testing::Call::fill_block { ratio: Perbill::from_percent(50), }); let call = RuntimeCall::Authority(authority::Call::dispatch_as { @@ -441,7 +443,7 @@ fn call_size_limit() { fn authorize_call_works() { ExtBuilder::default().build().execute_with(|| { run_to_block(1); - let ensure_root_call = RuntimeCall::System(frame_system::Call::fill_block { + let ensure_root_call = RuntimeCall::RootTesting(pallet_root_testing::Call::fill_block { ratio: Perbill::from_percent(50), }); let call = RuntimeCall::Authority(authority::Call::dispatch_as { @@ -480,7 +482,7 @@ fn authorize_call_works() { fn trigger_call_works() { ExtBuilder::default().build().execute_with(|| { run_to_block(1); - let ensure_root_call = RuntimeCall::System(frame_system::Call::fill_block { + let ensure_root_call = RuntimeCall::RootTesting(pallet_root_testing::Call::fill_block { ratio: Perbill::from_percent(50), }); let call = RuntimeCall::Authority(authority::Call::dispatch_as { @@ -558,7 +560,7 @@ fn trigger_call_works() { fn remove_authorized_call_works() { ExtBuilder::default().build().execute_with(|| { run_to_block(1); - let ensure_root_call = RuntimeCall::System(frame_system::Call::fill_block { + let ensure_root_call = RuntimeCall::RootTesting(pallet_root_testing::Call::fill_block { ratio: Perbill::from_percent(50), }); let call = RuntimeCall::Authority(authority::Call::dispatch_as { @@ -611,7 +613,7 @@ fn remove_authorized_call_works() { #[test] fn trigger_call_should_be_free_and_operational() { ExtBuilder::default().build().execute_with(|| { - let call = RuntimeCall::System(frame_system::Call::fill_block { + let call = RuntimeCall::RootTesting(pallet_root_testing::Call::fill_block { ratio: Perbill::from_percent(50), }); let hash = ::Hashing::hash_of(&call); @@ -653,7 +655,7 @@ fn trigger_call_should_be_free_and_operational() { #[test] fn trigger_old_call_should_be_free_and_operational() { ExtBuilder::default().build().execute_with(|| { - let call = RuntimeCall::System(frame_system::Call::fill_block { + let call = RuntimeCall::RootTesting(pallet_root_testing::Call::fill_block { ratio: Perbill::from_percent(50), }); let hash = ::Hashing::hash_of(&call); @@ -691,3 +693,9 @@ fn trigger_old_call_should_be_free_and_operational() { ); }); } + +#[test] +fn origin_max_encoded_len_works() { + assert_eq!(DelayedOrigin::::max_encoded_len(), 22); + assert_eq!(OriginCaller::max_encoded_len(), 27); +} diff --git a/bencher/Cargo.toml b/bencher/Cargo.toml index 6797f18ee..e61bf3fc1 100644 --- a/bencher/Cargo.toml +++ b/bencher/Cargo.toml @@ -10,15 +10,15 @@ edition = "2021" [dependencies] paste = "1.0.7" build-helper = { version = "0.1.1", optional = true } -cargo_metadata = { version = "0.14.1", optional = true } +cargo_metadata = { version = "0.15.2", optional = true } tempfile = { version = "3.2.0", optional = true } toml = { version = "0.5.8", optional = true } walkdir = { version = "2.3.1", optional = true } ansi_term = { version = "0.12.1", optional = true } wasm-gc-api = { version = "0.1.11", optional = true } rand = {version = "0.8.3", optional = true } -linregress = { version = "0.4.4", optional = true } -parking_lot = { version = "0.12.0", optional = true } +linregress = { version = "0.5.0", optional = true } +parking_lot = { version = "0.12.1", optional = true } thiserror = { version = "1.0", optional = true } serde = { version = "1.0.136", optional = true, features = ['derive'] } serde_json = {version = "1.0.68", optional = true } @@ -26,18 +26,18 @@ hash-db = { version = "0.15.2", default-features = false, optional = true } bencher-procedural = { path = "bencher-procedural", default-features = false } codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive"], default-features = false } -sp-core = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-runtime-interface = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-state-machine = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true , branch = "polkadot-v0.9.31" } -sc-executor = { git = "https://github.com/paritytech/substrate", default-features = false, features = ["wasmtime"], optional = true , branch = "polkadot-v0.9.31" } -sc-executor-common = { git = "https://github.com/paritytech/substrate", optional = true , branch = "polkadot-v0.9.31" } -sc-client-db = { git = "https://github.com/paritytech/substrate", default-features = false, features = ["rocksdb"], optional = true , branch = "polkadot-v0.9.31" } -sp-maybe-compressed-blob = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true , branch = "polkadot-v0.9.31" } -frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-externalities = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-storage = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true , branch = "polkadot-v0.9.31" } +sp-core = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime-interface = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-state-machine = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true , branch = "polkadot-v0.9.36" } +sc-executor = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true , branch = "polkadot-v0.9.36" } +sc-executor-common = { git = "https://github.com/paritytech/substrate", optional = true , branch = "polkadot-v0.9.36" } +sc-client-db = { git = "https://github.com/paritytech/substrate", default-features = false, features = ["rocksdb"], optional = true , branch = "polkadot-v0.9.36" } +sp-maybe-compressed-blob = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true , branch = "polkadot-v0.9.36" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-externalities = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-storage = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true , branch = "polkadot-v0.9.36" } [features] default = ["std"] @@ -67,7 +67,7 @@ std = [ "sc-executor-common", "sc-client-db", "sp-maybe-compressed-blob", - "frame-benchmarking/std", + "frame-support/std", "sp-externalities/std", "sp-storage/std", ] diff --git a/bencher/src/bench_runner.rs b/bencher/src/bench_runner.rs index b48246515..1906c1494 100644 --- a/bencher/src/bench_runner.rs +++ b/bencher/src/bench_runner.rs @@ -2,18 +2,14 @@ use super::{ bench_ext::BenchExt, tracker::{BenchTracker, BenchTrackerExt}, }; -use frame_benchmarking::frame_support::sp_runtime::traits::Block; +use frame_support::sp_runtime::traits::Block; use sc_executor::{WasmExecutionMethod, WasmExecutor, WasmtimeInstantiationStrategy}; use sc_executor_common::runtime_blob::RuntimeBlob; use sp_externalities::Extensions; use sp_state_machine::{Ext, OverlayedChanges, StorageTransactionCache}; use sp_std::sync::Arc; -type ComposeHostFunctions = ( - sp_io::SubstrateHostFunctions, - frame_benchmarking::benchmarking::HostFunctions, - super::bench::HostFunctions, -); +type ComposeHostFunctions = (sp_io::SubstrateHostFunctions, super::bench::HostFunctions); /// Run benches pub fn run(wasm_code: Vec) -> std::result::Result, sc_executor_common::error::Error> { diff --git a/bencher/src/bencher.rs b/bencher/src/bencher.rs index bfbc210a4..3ac197f2b 100644 --- a/bencher/src/bencher.rs +++ b/bencher/src/bencher.rs @@ -40,8 +40,8 @@ impl Bencher { pub fn before_run(&self) { #[cfg(not(feature = "std"))] { - frame_benchmarking::benchmarking::commit_db(); - frame_benchmarking::benchmarking::wipe_db(); + crate::bench::commit_db(); + crate::bench::wipe_db(); } } @@ -56,8 +56,8 @@ impl Bencher { { #[cfg(not(feature = "std"))] { - frame_benchmarking::benchmarking::commit_db(); - frame_benchmarking::benchmarking::reset_read_write_count(); + crate::bench::commit_db(); + crate::bench::reset_read_write_count(); crate::bench::start_timer(); } @@ -68,7 +68,7 @@ impl Bencher { let elapsed = crate::bench::end_timer().saturating_sub(crate::bench::redundant_time()); self.current.elapses.push(elapsed); - frame_benchmarking::benchmarking::commit_db(); + crate::bench::commit_db(); // changed keys self.current.keys = crate::bench::read_written_keys(); diff --git a/bencher/src/build_wasm/prerequisites.rs b/bencher/src/build_wasm/prerequisites.rs index 3074480df..8377af327 100644 --- a/bencher/src/build_wasm/prerequisites.rs +++ b/bencher/src/build_wasm/prerequisites.rs @@ -77,11 +77,7 @@ fn get_rustup_nightly(selected: Option) -> Option { let version = match selected { Some(selected) => selected, None => { - let output = Command::new("rustup") - .args(&["toolchain", "list"]) - .output() - .ok()? - .stdout; + let output = Command::new("rustup").args(["toolchain", "list"]).output().ok()?.stdout; let lines = output.as_slice().lines(); let mut latest_nightly = None; @@ -194,7 +190,7 @@ fn create_check_toolchain_project(project_dir: &Path) { let manifest_path = project_dir.join("Cargo.toml"); write_file_if_changed( - &manifest_path, + manifest_path, r#" [package] name = "wasm-test" @@ -260,7 +256,7 @@ fn check_wasm_toolchain_installed(cargo_command: CargoCommand) -> Result Result, storage_infos: Vec) { comments.sort(); + let intercepted_value = model.parameters()[0] as u64; + println!( "{} {:<40} {:>20} storage: {:<20}", green_bold("Bench"), cyan(&name), - green_bold(&format!( - "{:?}", - Duration::from_nanos(model.parameters.intercept_value as u64) - )), + green_bold(&format!("{:?}", Duration::from_nanos(intercepted_value))), green_bold(&format!( "[r: {}, w: {}]", &total_reads.to_string(), @@ -83,7 +82,7 @@ pub fn handle(output: Vec, storage_infos: Vec) { BenchData { name, - weight: model.parameters.intercept_value as u64 * 1_000, + weight: intercepted_value * 1_000, reads: total_reads, writes: total_writes, comments, diff --git a/bencher/src/lib.rs b/bencher/src/lib.rs index e7c18d486..824248fa6 100644 --- a/bencher/src/lib.rs +++ b/bencher/src/lib.rs @@ -1,7 +1,7 @@ #![cfg_attr(not(feature = "std"), no_std)] #[doc(hidden)] -pub extern crate frame_benchmarking; +pub extern crate frame_support; #[doc(hidden)] pub extern crate paste; #[doc(hidden)] diff --git a/bencher/src/macros.rs b/bencher/src/macros.rs index f307e7617..4945b0046 100644 --- a/bencher/src/macros.rs +++ b/bencher/src/macros.rs @@ -125,7 +125,7 @@ macro_rules! run_benches { ) => { #[cfg(all(feature = "std", feature = "bench"))] pub fn main() -> std::io::Result<()> { - use $crate::frame_benchmarking::frame_support::traits::StorageInfoTrait; + use $crate::frame_support::traits::StorageInfoTrait; let wasm = $crate::build_wasm::build()?; let storage_info = $all_pallets_with_system::storage_info(); match $crate::bench_runner::run::<$block>(wasm) { diff --git a/bencher/src/utils.rs b/bencher/src/utils.rs index 4b0ee5379..f46f58e17 100644 --- a/bencher/src/utils.rs +++ b/bencher/src/utils.rs @@ -36,6 +36,18 @@ pub trait Bench { println!("{}", msg); } + fn commit_db(&mut self) { + self.commit() + } + + fn wipe_db(&mut self) { + self.wipe() + } + + fn reset_read_write_count(&mut self) { + self.reset_read_write_count() + } + fn start_timer(&mut self) { let tracker = &***self .extension::() diff --git a/bencher/test/Cargo.toml b/bencher/test/Cargo.toml index 0c0ab28e3..f4705f3b6 100644 --- a/bencher/test/Cargo.toml +++ b/bencher/test/Cargo.toml @@ -15,16 +15,16 @@ required-features = ["bench"] serde = { version = "1.0.136", optional = true } scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive"], default-features = false } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-core = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-core = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } orml-bencher = { path = "..", default-features = false } orml-weight-meter = { path = "../../weight-meter", default-features = false } [dev-dependencies] -sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } [features] default = ["std"] @@ -32,18 +32,15 @@ std = [ "serde", "scale-info/std", "codec/std", - "orml-bencher/std", "frame-support/std", "frame-system/std", "sp-runtime/std", - "sp-std/std", "sp-core/std", + "sp-std/std", + "orml-bencher/std", "orml-weight-meter/std", ] bench = [ "orml-bencher/bench", "orml-weight-meter/bench", - "frame-support/runtime-benchmarks", - "sp-runtime/runtime-benchmarks", - "frame-system/runtime-benchmarks", ] diff --git a/bencher/test/src/benches.rs b/bencher/test/src/benches.rs index dbd98cc7e..62ac88231 100644 --- a/bencher/test/src/benches.rs +++ b/bencher/test/src/benches.rs @@ -42,10 +42,4 @@ fn whitelist(b: &mut Bencher) { }); } -benches!( - whitelist, - set_value, - set_foo, - remove_all_bar, - remove_all_bar_with_limit -); +benches!(whitelist, set_value, set_foo, remove_all_bar, remove_all_bar_with_limit); diff --git a/bencher/test/src/lib.rs b/bencher/test/src/lib.rs index ed81c5f44..892e9231f 100644 --- a/bencher/test/src/lib.rs +++ b/bencher/test/src/lib.rs @@ -38,10 +38,11 @@ pub mod pallet { #[pallet::call] impl Pallet { + #[pallet::call_index(0)] #[pallet::weight(0)] - #[orml_weight_meter::start(ModuleWeights::::set_value())] + #[orml_weight_meter::start(ModuleWeights::::set_value().ref_time())] pub fn set_value(origin: OriginFor, n: u32) -> DispatchResultWithPostInfo { - let _sender = frame_system::ensure_signed(origin)?; + frame_system::ensure_signed(origin)?; Value::::get(); Value::::put(n); Value::::put(n + 1); @@ -49,16 +50,17 @@ pub mod pallet { Ok(Some(orml_weight_meter::used_weight()).into()) } + #[pallet::call_index(1)] #[pallet::weight(0)] pub fn dummy(origin: OriginFor, _n: u32) -> DispatchResult { - let _sender = frame_system::ensure_none(origin)?; + frame_system::ensure_none(origin)?; Foo::::put(1); Ok(()) } } impl Pallet { - #[orml_weight_meter::weight(ModuleWeights::::set_foo())] + #[orml_weight_meter::weight(ModuleWeights::::set_foo().ref_time())] pub(crate) fn set_foo() -> frame_support::dispatch::DispatchResult { Value::::put(2); diff --git a/bencher/test/src/mock.rs b/bencher/test/src/mock.rs index 54d84fcd2..af2ae2532 100644 --- a/bencher/test/src/mock.rs +++ b/bencher/test/src/mock.rs @@ -16,7 +16,7 @@ pub type Header = sp_runtime::generic::Header; pub type SignedExtra = (frame_system::CheckWeight,); -pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; +pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; pub type Block = sp_runtime::generic::Block; diff --git a/bencher/test/src/weights.rs b/bencher/test/src/weights.rs index bc946b082..8882be9cf 100644 --- a/bencher/test/src/weights.rs +++ b/bencher/test/src/weights.rs @@ -10,13 +10,21 @@ use sp_std::marker::PhantomData; pub struct ModuleWeights(PhantomData); impl ModuleWeights { + // Storage access info + // + // Test::Bar (r: 0, w: 1) + pub fn whitelist() -> Weight { + Weight::from_ref_time(5_356_000) + .saturating_add(T::DbWeight::get().writes(1)) + } // Storage access info // // Test::Value (r: 1, w: 1) + // Unknown 0x3a7472616e73616374696f6e5f6c6576656c3a (r: 1, w: 1) pub fn set_value() -> Weight { - (5_236_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(3_919_000) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) } // Storage access info // @@ -24,13 +32,20 @@ impl ModuleWeights { // Test::Foo (r: 0, w: 1) // Test::Value (r: 0, w: 1) pub fn set_foo() -> Weight { - (13_274_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) + Weight::from_ref_time(5_133_000) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(4)) } // Storage access info // pub fn remove_all_bar() -> Weight { - (3_449_000 as Weight) + Weight::from_ref_time(1_533_000) + } + // Storage access info + // + // Test::Bar (r: 0, w: 10) + pub fn remove_all_bar_with_limit() -> Weight { + Weight::from_ref_time(1_600_000) + .saturating_add(T::DbWeight::get().writes(10)) } } diff --git a/benchmarking/Cargo.toml b/benchmarking/Cargo.toml index 8298a3c56..30716e8e2 100644 --- a/benchmarking/Cargo.toml +++ b/benchmarking/Cargo.toml @@ -8,38 +8,43 @@ authors = ["Laminar Developers "] edition = "2021" [dependencies] -serde = { version = "1.0.136", optional = true } -paste = "1.0.7" codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } -scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } +paste = "1.0.7" +scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } +serde = { version = "1.0.136", optional = true } -sp-api = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-runtime-interface = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-storage = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-api = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime-interface = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-storage = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } [dev-dependencies] hex-literal = "0.3.4" -frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } + +frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } + [features] default = [ "std" ] std = [ "serde", + "codec/std", + "frame-benchmarking/std", + "frame-support/std", + "log/std", "scale-info/std", + "sp-api/std", + "sp-io/std", "sp-runtime-interface/std", "sp-runtime/std", - "sp-api/std", "sp-std/std", - "frame-support/std", - "frame-benchmarking/std", - "log/std", + "sp-storage/std", ] try-runtime = [ diff --git a/benchmarking/src/lib.rs b/benchmarking/src/lib.rs index 4a4d8ec98..f165cb682 100644 --- a/benchmarking/src/lib.rs +++ b/benchmarking/src/lib.rs @@ -1180,6 +1180,14 @@ macro_rules! impl_benchmark_test_suite { $crate::str::from_utf8(benchmark_name) .expect("benchmark name is always a valid string!"), ); + }, + $crate::BenchmarkError::Weightless => { + // This is considered a success condition. + $crate::log::error!( + "WARNING: benchmark error weightless skipped - {}", + $crate::str::from_utf8(benchmark_name) + .expect("benchmark name is always a valid string!"), + ); } } }, @@ -1314,6 +1322,17 @@ macro_rules! add_benchmark { .expect("benchmark name is always a valid string!") ); None + }, + Err($crate::BenchmarkError::Weightless) => { + $crate::log::error!( + "WARNING: benchmark weightless skipped - {}", + $crate::str::from_utf8(benchmark) + .expect("benchmark name is always a valid string!") + ); + Some(vec![$crate::BenchmarkResult { + components: selected_components.clone(), + .. Default::default() + }]) } }; diff --git a/benchmarking/src/tests.rs b/benchmarking/src/tests.rs index 15c827918..89ee0e7ff 100644 --- a/benchmarking/src/tests.rs +++ b/benchmarking/src/tests.rs @@ -34,6 +34,7 @@ pub mod test { #[pallet::call] impl Pallet { + #[pallet::call_index(0)] #[pallet::weight(0)] pub fn set_value(origin: OriginFor, n: u32) -> DispatchResult { let _sender = frame_system::ensure_signed(origin)?; @@ -41,6 +42,7 @@ pub mod test { Ok(()) } + #[pallet::call_index(1)] #[pallet::weight(0)] pub fn dummy(origin: OriginFor, _n: u32) -> DispatchResult { let _sender = frame_system::ensure_none(origin)?; diff --git a/currencies/Cargo.toml b/currencies/Cargo.toml index ab319d554..b5263b85c 100644 --- a/currencies/Cargo.toml +++ b/currencies/Cargo.toml @@ -8,22 +8,22 @@ authors = ["Laminar Developers "] edition = "2021" [dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } serde = { version = "1.0.136", optional = true } -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false } orml-utilities = { path = "../utilities", version = "0.4.1-dev", default-features = false } [dev-dependencies] -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } orml_tokens = { package = "orml-tokens", path = "../tokens", version = "0.4.1-dev" } @@ -31,17 +31,18 @@ orml_tokens = { package = "orml-tokens", path = "../tokens", version = "0.4.1-de default = ["std"] std = [ "serde", + "codec/std", - "scale-info/std", - "sp-runtime/std", - "sp-std/std", - "sp-io/std", "frame-support/std", "frame-system/std", "orml-traits/std", "orml-utilities/std", + "scale-info/std", + "sp-io/std", + "sp-runtime/std", + "sp-std/std", ] try-runtime = [ - "frame-system/try-runtime", "frame-support/try-runtime", + "frame-system/try-runtime", ] diff --git a/currencies/src/lib.rs b/currencies/src/lib.rs index b60c2573f..a7594f9c4 100644 --- a/currencies/src/lib.rs +++ b/currencies/src/lib.rs @@ -126,6 +126,7 @@ pub mod module { /// /// The dispatch origin for this call must be `Signed` by the /// transactor. + #[pallet::call_index(0)] #[pallet::weight(T::WeightInfo::transfer_non_native_currency())] pub fn transfer( origin: OriginFor, @@ -142,6 +143,7 @@ pub mod module { /// /// The dispatch origin for this call must be `Signed` by the /// transactor. + #[pallet::call_index(1)] #[pallet::weight(T::WeightInfo::transfer_native_currency())] pub fn transfer_native_currency( origin: OriginFor, @@ -156,6 +158,7 @@ pub mod module { /// update amount of account `who` under `currency_id`. /// /// The dispatch origin of this call must be _Root_. + #[pallet::call_index(2)] #[pallet::weight(T::WeightInfo::update_balance_non_native_currency())] pub fn update_balance( origin: OriginFor, diff --git a/currencies/src/mock.rs b/currencies/src/mock.rs index 488329d1a..469c1c14d 100644 --- a/currencies/src/mock.rs +++ b/currencies/src/mock.rs @@ -8,7 +8,7 @@ use frame_support::{ traits::{ConstU128, ConstU32, ConstU64, Everything, Nothing}, PalletId, }; -use orml_traits::parameter_type_with_key; +use orml_traits::{currency::MutationHooks, parameter_type_with_key}; use sp_core::H256; use sp_runtime::{ testing::Header, @@ -73,6 +73,21 @@ parameter_types! { pub DustAccount: AccountId = PalletId(*b"orml/dst").into_account_truncating(); } +pub struct CurrencyHooks(marker::PhantomData); +impl MutationHooks for CurrencyHooks +where + T::AccountId: From, +{ + type OnDust = orml_tokens::TransferDust; + type OnSlash = (); + type PreDeposit = (); + type PostDeposit = (); + type PreTransfer = (); + type PostTransfer = (); + type OnNewTokenAccount = (); + type OnKilledTokenAccount = (); +} + impl orml_tokens::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; @@ -80,16 +95,11 @@ impl orml_tokens::Config for Runtime { type CurrencyId = CurrencyId; type WeightInfo = (); type ExistentialDeposits = ExistentialDeposits; - type OnDust = orml_tokens::TransferDust; - type OnSlash = (); - type OnDeposit = (); - type OnTransfer = (); + type CurrencyHooks = CurrencyHooks; type MaxLocks = ConstU32<100_000>; type MaxReserves = ConstU32<100_000>; type ReserveIdentifier = ReserveIdentifier; type DustRemovalWhitelist = Nothing; - type OnNewTokenAccount = (); - type OnKilledTokenAccount = (); } pub const NATIVE_CURRENCY_ID: CurrencyId = 99; @@ -131,6 +141,7 @@ pub const ID_1: LockIdentifier = *b"1 "; pub const RID_1: ReserveIdentifier = [1u8; 8]; pub const RID_2: ReserveIdentifier = [2u8; 8]; +#[derive(Default)] pub struct ExtBuilder { balances: Vec<(AccountId, CurrencyId, Balance)>, tokens_endowment: Vec<(AccountId, CurrencyId, Balance)>, @@ -148,6 +159,7 @@ impl Default for ExtBuilder { } } } + impl ExtBuilder { pub fn balances(mut self, balances: Vec<(AccountId, CurrencyId, Balance)>) -> Self { self.balances = balances; diff --git a/gradually-update/Cargo.toml b/gradually-update/Cargo.toml index 93591c3e8..5a91690bd 100644 --- a/gradually-update/Cargo.toml +++ b/gradually-update/Cargo.toml @@ -8,28 +8,32 @@ authors = ["Laminar Developers "] edition = "2021" [dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["max-encoded-len"] } scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } serde = { version = "1.0.136", optional = true } -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["max-encoded-len"] } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-core = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-core = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } [features] default = ["std"] std = [ "serde", + "codec/std", - "scale-info/std", "frame-support/std", "frame-system/std", - "sp-io/std", - "sp-std/std", + "scale-info/std", "sp-core/std", + "sp-io/std", "sp-runtime/std", + "sp-std/std", +] +try-runtime = [ + "frame-support/try-runtime", + "frame-system/try-runtime", ] -try-runtime = ["frame-support/try-runtime"] diff --git a/gradually-update/src/lib.rs b/gradually-update/src/lib.rs index ff34cea19..0371b0fa2 100644 --- a/gradually-update/src/lib.rs +++ b/gradually-update/src/lib.rs @@ -162,6 +162,7 @@ pub mod module { #[pallet::call] impl Pallet { /// Add gradually_update to adjust numeric parameter. + #[pallet::call_index(0)] #[pallet::weight(T::WeightInfo::gradually_update())] pub fn gradually_update(origin: OriginFor, update: GraduallyUpdateOf) -> DispatchResult { T::DispatchOrigin::try_origin(origin).map(|_| ()).or_else(ensure_root)?; @@ -202,6 +203,7 @@ pub mod module { } /// Cancel gradually_update to adjust numeric parameter. + #[pallet::call_index(1)] #[pallet::weight(T::WeightInfo::cancel_gradually_update())] pub fn cancel_gradually_update(origin: OriginFor, key: StorageKeyBytes) -> DispatchResult { T::DispatchOrigin::try_origin(origin).map(|_| ()).or_else(ensure_root)?; diff --git a/nft/Cargo.toml b/nft/Cargo.toml index 1da8b8f6a..5c24f821d 100644 --- a/nft/Cargo.toml +++ b/nft/Cargo.toml @@ -8,31 +8,32 @@ authors = ["Acala Developers"] edition = "2021" [dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["max-encoded-len"] } scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } serde = { version = "1.0.136", optional = true } -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["max-encoded-len"] } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } [dev-dependencies] -sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } [features] default = ["std"] std = [ "serde", + "codec/std", - "scale-info/std", - "sp-std/std", - "sp-runtime/std", "frame-support/std", "frame-system/std", + "scale-info/std", + "sp-runtime/std", + "sp-std/std", ] try-runtime = [ - "frame-system/try-runtime", "frame-support/try-runtime", + "frame-system/try-runtime", ] diff --git a/oracle/Cargo.toml b/oracle/Cargo.toml index a5c51f564..9edb37cec 100644 --- a/oracle/Cargo.toml +++ b/oracle/Cargo.toml @@ -8,36 +8,40 @@ authors = ["Laminar Developers "] edition = "2021" [dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } serde = { version = "1.0.136", optional = true } -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } -sp-application-crypto = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-application-crypto = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false } orml-utilities = { path = "../utilities", version = "0.4.1-dev", default-features = false } [dev-dependencies] -sp-core = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +sp-core = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } [features] default = ["std"] std = [ "serde", + "codec/std", + "frame-support/std", + "frame-system/std", + "orml-traits/std", + "orml-utilities/std", "scale-info/std", "sp-application-crypto/std", "sp-io/std", "sp-runtime/std", "sp-std/std", - "frame-support/std", - "frame-system/std", - "orml-traits/std", - "orml-utilities/std", ] -try-runtime = ["frame-support/try-runtime"] +try-runtime = [ + "frame-support/try-runtime", + "frame-system/try-runtime", +] diff --git a/oracle/rpc/Cargo.toml b/oracle/rpc/Cargo.toml index 2508a5c3a..32d66dabd 100644 --- a/oracle/rpc/Cargo.toml +++ b/oracle/rpc/Cargo.toml @@ -8,12 +8,12 @@ description = "RPC module for orml-oracle." [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0" } -jsonrpsee = { version = "0.15.1", features = ["server", "macros"] } +jsonrpsee = { version = "0.16.2", features = ["client", "server", "macros"] } tracing = { version = "0.1.29" } tracing-core = { version = "0.1.28" } -sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } orml-oracle-rpc-runtime-api = { path = "runtime-api", version = "0.4.1-dev" } diff --git a/oracle/rpc/runtime-api/Cargo.toml b/oracle/rpc/runtime-api/Cargo.toml index d3d7f6a0a..183a8a10c 100644 --- a/oracle/rpc/runtime-api/Cargo.toml +++ b/oracle/rpc/runtime-api/Cargo.toml @@ -8,8 +8,8 @@ description = "Runtime API module for orml-oracle-rpc." [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } -sp-api = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +sp-api = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } [features] default = ["std"] diff --git a/oracle/src/lib.rs b/oracle/src/lib.rs index a44ba200d..1ee385602 100644 --- a/oracle/src/lib.rs +++ b/oracle/src/lib.rs @@ -155,6 +155,7 @@ pub mod module { /// Feed the external value. /// /// Require authorized operator. + #[pallet::call_index(0)] #[pallet::weight(T::WeightInfo::feed_values(values.len() as u32))] pub fn feed_values( origin: OriginFor, @@ -214,7 +215,7 @@ impl, I: 'static> Pallet { value: value.clone(), timestamp: now, }; - RawValues::::insert(&who, &key, timestamped); + RawValues::::insert(&who, key, timestamped); // Update `Values` storage if `combined` yielded result. if let Some(combined) = Self::combined(key) { diff --git a/payments/Cargo.toml b/payments/Cargo.toml index 8a960f19f..1a6e07778 100644 --- a/payments/Cargo.toml +++ b/payments/Cargo.toml @@ -12,37 +12,41 @@ description = "Allows users to post escrow payment on-chain" readme = "README.md" [dependencies] -parity-scale-codec = { version = "3.1.5", default-features = false, features = ["max-encoded-len"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } orml-traits = {path = "../traits", version = "0.4.1-dev", default-features = false } [dev-dependencies] serde = { version = "1.0.136" } -sp-core = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +sp-core = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } orml-tokens = { path = "../tokens", version = "0.4.1-dev", default-features = false } [features] default = ['std'] std = [ - 'parity-scale-codec/std', + 'codec/std', 'frame-support/std', 'frame-system/std', 'log/std', + 'orml-tokens/std', + 'orml-traits/std', + 'scale-info/std', 'sp-runtime/std', 'sp-std/std', - 'scale-info/std', - 'orml-traits/std', - 'orml-tokens/std' +] +try-runtime = [ + "frame-support/try-runtime", + "frame-system/try-runtime", ] try-runtime = [ diff --git a/payments/src/lib.rs b/payments/src/lib.rs index 810839d30..9f14d1927 100644 --- a/payments/src/lib.rs +++ b/payments/src/lib.rs @@ -214,16 +214,17 @@ pub mod pallet { /// Hook that execute when there is leftover space in a block /// This function will look for any pending scheduled tasks that can /// be executed and will process them. - fn on_idle(now: T::BlockNumber, mut remaining_weight: Weight) -> Weight { + fn on_idle(now: T::BlockNumber, remaining_weight: Weight) -> Weight { const MAX_TASKS_TO_PROCESS: usize = 5; - // reduce the weight used to read the task list - remaining_weight = remaining_weight.saturating_sub(T::WeightInfo::remove_task()); + // used to read the task list + let mut used_weight = T::WeightInfo::remove_task(); let cancel_weight = T::WeightInfo::cancel(); // calculate count of tasks that can be processed with remaining weight let possible_task_count: usize = remaining_weight - .ref_time() + .saturating_sub(used_weight) .saturating_div(cancel_weight.ref_time()) + .ref_time() .try_into() .unwrap_or(MAX_TASKS_TO_PROCESS); @@ -239,9 +240,9 @@ pub mod pallet { // order by oldest task to process task_list.sort_by(|(_, t), (_, x)| x.when.cmp(&t.when)); - while !task_list.is_empty() && remaining_weight.all_gte(cancel_weight) { + while !task_list.is_empty() && used_weight.all_lte(remaining_weight) { if let Some((account_pair, _)) = task_list.pop() { - remaining_weight = remaining_weight.saturating_sub(cancel_weight); + used_weight = used_weight.saturating_add(cancel_weight); // remove the task form the tasks storage tasks.remove(&account_pair); @@ -268,7 +269,7 @@ pub mod pallet { } } }); - remaining_weight + used_weight } } @@ -280,6 +281,7 @@ pub mod pallet { /// the option to add a remark, this remark can then be used to run /// custom logic and trigger alternate payment flows. the specified /// amount. + #[pallet::call_index(0)] #[pallet::weight(T::WeightInfo::pay(T::MaxRemarkLength::get()))] pub fn pay( origin: OriginFor, @@ -314,6 +316,7 @@ pub mod pallet { /// Release any created payment, this will transfer the reserved amount /// from the creator of the payment to the assigned recipient + #[pallet::call_index(1)] #[pallet::weight(T::WeightInfo::release())] pub fn release(origin: OriginFor, to: T::AccountId) -> DispatchResultWithPostInfo { let from = ensure_signed(origin)?; @@ -332,6 +335,7 @@ pub mod pallet { /// Cancel a payment in created state, this will release the reserved /// back to creator of the payment. This extrinsic can only be called by /// the recipient of the payment + #[pallet::call_index(2)] #[pallet::weight(T::WeightInfo::cancel())] pub fn cancel(origin: OriginFor, creator: T::AccountId) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; @@ -354,6 +358,7 @@ pub mod pallet { /// recipient of the payment. /// This extrinsic allows the assigned judge to /// cancel/release/partial_release the payment. + #[pallet::call_index(3)] #[pallet::weight(T::WeightInfo::resolve_payment())] pub fn resolve_payment( origin: OriginFor, @@ -389,6 +394,7 @@ pub mod pallet { /// Allow the creator of a payment to initiate a refund that will return /// the funds after a configured amount of time that the reveiver has to /// react and opose the request + #[pallet::call_index(4)] #[pallet::weight(T::WeightInfo::request_refund())] pub fn request_refund(origin: OriginFor, recipient: T::AccountId) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; @@ -436,6 +442,7 @@ pub mod pallet { /// payment creator This does not cancel the request, instead sends the /// payment to a NeedsReview state The assigned resolver account can /// then change the state of the payment after review. + #[pallet::call_index(5)] #[pallet::weight(T::WeightInfo::dispute_refund())] pub fn dispute_refund(origin: OriginFor, creator: T::AccountId) -> DispatchResultWithPostInfo { use PaymentState::*; @@ -482,6 +489,7 @@ pub mod pallet { // using the `accept_and_pay` extrinsic. The payment will be in // PaymentRequested State and can only be modified by the `accept_and_pay` // extrinsic. + #[pallet::call_index(6)] #[pallet::weight(T::WeightInfo::request_payment())] pub fn request_payment( origin: OriginFor, @@ -510,6 +518,7 @@ pub mod pallet { // This extrinsic allows the sender to fulfill a payment request created by a // recipient. The amount will be transferred to the recipient and payment // removed from storage + #[pallet::call_index(7)] #[pallet::weight(T::WeightInfo::accept_and_pay())] pub fn accept_and_pay(origin: OriginFor, to: T::AccountId) -> DispatchResultWithPostInfo { let from = ensure_signed(origin)?; diff --git a/payments/src/mock.rs b/payments/src/mock.rs index ac32214ba..53bc87e3c 100644 --- a/payments/src/mock.rs +++ b/payments/src/mock.rs @@ -98,17 +98,12 @@ impl orml_tokens::Config for Test { type CurrencyId = u32; type RuntimeEvent = RuntimeEvent; type ExistentialDeposits = ExistentialDeposits; - type OnDust = (); - type OnSlash = (); - type OnDeposit = (); - type OnTransfer = (); + type CurrencyHooks = (); type WeightInfo = (); type MaxLocks = MaxLocks; type DustRemovalWhitelist = MockDustRemovalWhitelist; type MaxReserves = ConstU32<2>; type ReserveIdentifier = ReserveIdentifier; - type OnNewTokenAccount = (); - type OnKilledTokenAccount = (); } pub struct MockDisputeResolver; diff --git a/payments/src/tests.rs b/payments/src/tests.rs index ddcc3fa79..ddd2bf7ab 100644 --- a/payments/src/tests.rs +++ b/payments/src/tests.rs @@ -1,9 +1,10 @@ use crate::{ mock::*, types::{PaymentDetail, PaymentState}, + weights::WeightInfo, Payment as PaymentStore, PaymentHandler, ScheduledTask, ScheduledTasks, Task, }; -use frame_support::{assert_noop, assert_ok, storage::with_transaction}; +use frame_support::{assert_noop, assert_ok, storage::with_transaction, traits::OnIdle, weights::Weight}; use orml_traits::MultiCurrency; use sp_runtime::{Percent, TransactionOutcome}; @@ -1398,3 +1399,52 @@ fn test_automatic_refund_works_for_multiple_payments() { assert_eq!(Tokens::free_balance(CURRENCY_ID, &PAYMENT_RECIPENT_TWO), 0); }); } + +#[test] +fn on_idle_works() { + new_test_ext().execute_with(|| { + assert_eq!( + Payment::on_idle(System::block_number(), Weight::MAX), + <()>::remove_task() + ); + + let payment_amount = 20; + let expected_cancel_block = CANCEL_BLOCK_BUFFER + 1; + + assert_ok!(Payment::pay( + RuntimeOrigin::signed(PAYMENT_CREATOR), + PAYMENT_RECIPENT, + CURRENCY_ID, + payment_amount, + None + )); + + // creator requests a refund + assert_ok!(Payment::request_refund( + RuntimeOrigin::signed(PAYMENT_CREATOR), + PAYMENT_RECIPENT + )); + // ensure the request is added to the refund queue + let scheduled_tasks_list = ScheduledTasks::::get(); + assert_eq!(scheduled_tasks_list.len(), 1); + assert_eq!( + scheduled_tasks_list.get(&(PAYMENT_CREATOR, PAYMENT_RECIPENT)).unwrap(), + &ScheduledTask { + task: Task::Cancel, + when: expected_cancel_block + } + ); + + assert_eq!(run_n_blocks(CANCEL_BLOCK_BUFFER - 1), 600); + assert_eq!( + Payment::on_idle(System::block_number(), Weight::MAX), + <()>::remove_task() + ); + + assert_eq!(run_n_blocks(1), 601); + assert_eq!( + Payment::on_idle(System::block_number(), Weight::MAX), + <()>::remove_task() + <()>::cancel() + ); + }); +} diff --git a/payments/src/types.rs b/payments/src/types.rs index a4e5058d4..acb694db2 100644 --- a/payments/src/types.rs +++ b/payments/src/types.rs @@ -1,6 +1,6 @@ #![allow(unused_qualifications)] use crate::{pallet, AssetIdOf, BalanceOf}; -use parity_scale_codec::{Decode, Encode, HasCompact, MaxEncodedLen}; +use codec::{Decode, Encode, HasCompact, MaxEncodedLen}; use scale_info::TypeInfo; use sp_runtime::{DispatchResult, Percent}; diff --git a/rewards/Cargo.toml b/rewards/Cargo.toml index 5bda5aeab..dad1b52c5 100644 --- a/rewards/Cargo.toml +++ b/rewards/Cargo.toml @@ -8,37 +8,38 @@ authors = ["Acala Developers"] edition = "2021" [dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["max-encoded-len"] } scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } serde = { version = "1.0.136", optional = true } -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["max-encoded-len"] } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-core = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-core = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false } [dev-dependencies] -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } [features] default = ["std"] std = [ "serde", + "codec/std", - "scale-info/std", - "sp-runtime/std", - "sp-io/std", - "sp-std/std", - "sp-core/std", "frame-support/std", "frame-system/std", "orml-traits/std", + "scale-info/std", + "sp-core/std", + "sp-io/std", + "sp-runtime/std", + "sp-std/std", ] try-runtime = [ - "frame-system/try-runtime", "frame-support/try-runtime", + "frame-system/try-runtime", ] diff --git a/rewards/src/lib.rs b/rewards/src/lib.rs index 0ef94ade5..f395f9506 100644 --- a/rewards/src/lib.rs +++ b/rewards/src/lib.rs @@ -274,22 +274,24 @@ impl Pallet { return; } - PoolInfos::::mutate(pool, |pool_info| { - let total_shares = U256::from(pool_info.total_shares.to_owned().saturated_into::()); - pool_info.rewards.iter_mut().for_each( - |(reward_currency, (total_reward, total_withdrawn_reward))| { - Self::claim_one( - withdrawn_rewards, - *reward_currency, - share.to_owned(), - total_reward.to_owned(), - total_shares, - total_withdrawn_reward, - who, - pool, - ); - }, - ); + PoolInfos::::mutate_exists(pool, |maybe_pool_info| { + if let Some(pool_info) = maybe_pool_info { + let total_shares = U256::from(pool_info.total_shares.to_owned().saturated_into::()); + pool_info.rewards.iter_mut().for_each( + |(reward_currency, (total_reward, total_withdrawn_reward))| { + Self::claim_one( + withdrawn_rewards, + *reward_currency, + share.to_owned(), + total_reward.to_owned(), + total_shares, + total_withdrawn_reward, + who, + pool, + ); + }, + ); + } }); } }); diff --git a/rewards/src/tests.rs b/rewards/src/tests.rs index f0c05bd25..fb80a28bb 100644 --- a/rewards/src/tests.rs +++ b/rewards/src/tests.rs @@ -121,6 +121,32 @@ fn claim_rewards_should_not_create_empty_records() { SharesAndWithdrawnRewards::::contains_key(&DOT_POOL, &ALICE), false ); + + PoolInfos::::mutate(DOT_POOL, |pool_info| { + pool_info.rewards.insert(NATIVE_COIN, (10_000, 0)); + }); + RewardsModule::add_share(&ALICE, &DOT_POOL, 100); + assert_eq!( + RewardsModule::pool_infos(DOT_POOL), + PoolInfo { + total_shares: 100, + rewards: vec![(NATIVE_COIN, (10_000, 0))].into_iter().collect() + } + ); + assert_eq!( + RewardsModule::shares_and_withdrawn_rewards(DOT_POOL, ALICE), + (100, vec![(NATIVE_COIN, 0)].into_iter().collect()) + ); + + PoolInfos::::remove(DOT_POOL); + assert_eq!(PoolInfos::::contains_key(DOT_POOL), false); + + RewardsModule::claim_rewards(&ALICE, &DOT_POOL); + assert_eq!(PoolInfos::::contains_key(&DOT_POOL), false); + assert_eq!( + RewardsModule::shares_and_withdrawn_rewards(DOT_POOL, ALICE), + (100, vec![(NATIVE_COIN, 0)].into_iter().collect()) + ); }) } diff --git a/tokens/Cargo.toml b/tokens/Cargo.toml index 893dc433d..b451ab41c 100644 --- a/tokens/Cargo.toml +++ b/tokens/Cargo.toml @@ -8,38 +8,39 @@ authors = ["Laminar Developers "] edition = "2021" [dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["max-encoded-len"] } scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } serde = { version = "1.0.136", optional = true } -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["max-encoded-len"] } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false } mangata-types = { git="https://github.com/mangata-finance/substrate", branch = "mangata-dev", default-features = false, version = '0.1.0' } frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31", default-features = false, optional = true } [dev-dependencies] -sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -pallet-treasury = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -pallet-elections-phragmen = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +pallet-elections-phragmen = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +pallet-treasury = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } [features] default = ["std"] std = [ "serde", + "codec/std", - "scale-info/std", - "sp-runtime/std", - "sp-std/std", "frame-support/std", "frame-system/std", "orml-traits/std", "frame-benchmarking/std", - "mangata-types/std" + "mangata-types/std", + "scale-info/std", + "sp-runtime/std", + "sp-std/std", ] runtime-benchmarks = [ "frame-support/runtime-benchmarks", @@ -49,4 +50,5 @@ runtime-benchmarks = [ try-runtime = [ "frame-system/try-runtime", "frame-support/try-runtime", + "sp-runtime/runtime-benchmarks", ] diff --git a/tokens/rpc/Cargo.toml b/tokens/rpc/Cargo.toml index 758ccb05c..b873b2ebc 100644 --- a/tokens/rpc/Cargo.toml +++ b/tokens/rpc/Cargo.toml @@ -8,15 +8,15 @@ edition = "2021" [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0" } -jsonrpsee = { version = "0.15.1", features = ["server", "macros"] } +jsonrpsee = { version = "0.16.2", features = ["client", "server", "macros"] } tracing = { version = "0.1.29" } tracing-core = { version = "0.1.28" } -frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } orml-tokens-rpc-runtime-api = { version = "0.4.1-dev", path = "./runtime-api" } diff --git a/tokens/rpc/runtime-api/Cargo.toml b/tokens/rpc/runtime-api/Cargo.toml index 5440d6b6e..3d8491ce8 100644 --- a/tokens/rpc/runtime-api/Cargo.toml +++ b/tokens/rpc/runtime-api/Cargo.toml @@ -8,9 +8,9 @@ edition = "2021" [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-api = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-api = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } orml-tokens = { default-features = false, path = "../../../tokens" } [features] diff --git a/tokens/src/impls.rs b/tokens/src/impls.rs index f5a53d52e..ff8c16f2a 100644 --- a/tokens/src/impls.rs +++ b/tokens/src/impls.rs @@ -67,6 +67,14 @@ where B::can_withdraw(asset, who, amount) } } + + fn asset_exists(asset: Self::AssetId) -> bool { + if TestKey::contains(&asset) { + true + } else { + B::asset_exists(asset) + } + } } impl fungibles::Transfer for Combiner diff --git a/tokens/src/lib.rs b/tokens/src/lib.rs index c9474f620..dcf8f4808 100644 --- a/tokens/src/lib.rs +++ b/tokens/src/lib.rs @@ -65,9 +65,9 @@ use sp_std::{cmp, convert::Infallible, marker, prelude::*, vec::Vec}; use orml_traits::{ arithmetic::{self, Signed}, - currency::{TransferAll, OnDeposit, OnSlash, OnTransfer}, + currency::{MutationHooks, OnDeposit, OnDust, OnSlash, OnTransfer, TransferAll}, BalanceStatus, GetByKey, Happened, LockIdentifier, MultiCurrency, MultiCurrencyExtended, MultiLockableCurrency, - MultiReservableCurrency, NamedMultiReservableCurrency, OnDust, + MultiReservableCurrency, NamedMultiReservableCurrency, }; use codec::{Decode, Encode, FullCodec}; @@ -183,7 +183,7 @@ pub use module::*; #[frame_support::pallet] pub mod module { - use orml_traits::currency::{OnDeposit, OnSlash, OnTransfer}; + use orml_traits::currency::MutationHooks; use super::*; @@ -243,23 +243,9 @@ pub mod module { /// System::AccountInfo, zero ED may cause some problems. type ExistentialDeposits: GetByKey; - /// Handler to burn or transfer account's dust - type OnDust: OnDust; - - /// Hook to run before slashing an account. - type OnSlash: OnSlash; - - /// Hook to run before depositing into an account. - type OnDeposit: OnDeposit; - - /// Hook to run before transferring from an account to another. - type OnTransfer: OnTransfer; - - /// Handler for when an account was created - type OnNewTokenAccount: Happened<(Self::AccountId, Self::CurrencyId)>; - - /// Handler for when an account was created - type OnKilledTokenAccount: Happened<(Self::AccountId, Self::CurrencyId)>; + /// Hooks are actions that are executed on certain events. + /// For example: OnDust, OnNewTokenAccount + type CurrencyHooks: MutationHooks; #[pallet::constant] type MaxLocks: Get; @@ -524,6 +510,7 @@ pub mod module { /// - `dest`: The recipient of the transfer. /// - `currency_id`: currency type. /// - `amount`: free balance amount to tranfer. + #[pallet::call_index(0)] #[pallet::weight(T::WeightInfo::transfer())] pub fn transfer( origin: OriginFor, @@ -555,6 +542,7 @@ pub mod module { /// the sender account to be killed (false), or transfer everything /// except at least the existential deposit, which will guarantee to /// keep the sender account alive (true). + #[pallet::call_index(1)] #[pallet::weight(T::WeightInfo::transfer_all())] pub fn transfer_all( origin: OriginFor, @@ -581,6 +569,7 @@ pub mod module { /// - `dest`: The recipient of the transfer. /// - `currency_id`: currency type. /// - `amount`: free balance amount to tranfer. + #[pallet::call_index(2)] #[pallet::weight(T::WeightInfo::transfer_keep_alive())] pub fn transfer_keep_alive( origin: OriginFor, @@ -603,6 +592,7 @@ pub mod module { /// - `dest`: The recipient of the transfer. /// - `currency_id`: currency type. /// - `amount`: free balance amount to tranfer. + #[pallet::call_index(3)] #[pallet::weight(T::WeightInfo::force_transfer())] pub fn force_transfer( origin: OriginFor, @@ -625,6 +615,7 @@ pub mod module { /// existential deposit, it will reap the `AccountInfo`. /// /// The dispatch origin for this call is `root`. + #[pallet::call_index(4)] #[pallet::weight(T::WeightInfo::set_balance())] pub fn set_balance( origin: OriginFor, @@ -675,6 +666,7 @@ pub mod module { }) } + #[pallet::call_index(5)] #[pallet::weight(T::WeightInfo::create())] pub fn create( origin: OriginFor, @@ -688,6 +680,7 @@ pub mod module { Ok(().into()) } + #[pallet::call_index(6)] #[pallet::weight(T::WeightInfo::mint())] pub fn mint( origin: OriginFor, @@ -840,11 +833,11 @@ impl Pallet { // Ignore the result, because if it failed then there are remaining consumers, // and the account storage in frame_system shouldn't be reaped. let _ = frame_system::Pallet::::dec_providers(who); - T::OnKilledTokenAccount::happened(&(who.clone(), currency_id)); + >::OnKilledTokenAccount::happened(&(who.clone(), currency_id)); } else if !existed && exists { // if new, increase account provider frame_system::Pallet::::inc_providers(who); - T::OnNewTokenAccount::happened(&(who.clone(), currency_id)); + >::OnNewTokenAccount::happened(&(who.clone(), currency_id)); } if let Some(endowed) = maybe_endowed { @@ -858,7 +851,7 @@ impl Pallet { if let Some(dust_amount) = maybe_dust { // `OnDust` maybe get/set storage `Accounts` of `who`, trigger handler here // to avoid some unexpected errors. - T::OnDust::on_dust(who, currency_id, dust_amount); + >::OnDust::on_dust(who, currency_id, dust_amount); Self::deposit_event(Event::DustLost { currency_id, @@ -981,7 +974,12 @@ impl Pallet { return Ok(()); } - T::OnTransfer::on_transfer(currency_id, from, to, amount)?; + >::PreTransfer::on_transfer( + currency_id, + from, + to, + amount, + )?; Self::try_mutate_account(to, currency_id, |to_account, _existed| -> DispatchResult { Self::try_mutate_account(from, currency_id, |from_account, _existed| -> DispatchResult { from_account.free = from_account @@ -1021,6 +1019,12 @@ impl Pallet { Ok(()) })?; + >::PostTransfer::on_transfer( + currency_id, + from, + to, + amount, + )?; Self::deposit_event(Event::Transfer { currency_id, from: from.clone(), @@ -1107,7 +1111,11 @@ impl Pallet { return Ok(()); } - T::OnDeposit::on_deposit(currency_id, who, amount)?; + >::PreDeposit::on_deposit( + currency_id, + who, + amount, + )?; Self::try_mutate_account(who, currency_id, |account, existed| -> DispatchResult { if require_existed { ensure!(existed, Error::::DeadAccount); @@ -1128,14 +1136,19 @@ impl Pallet { TotalIssuance::::mutate(currency_id, |v| *v = new_total_issuance); } account.free = account.free.defensive_saturating_add(amount); - - Self::deposit_event(Event::Deposited { - currency_id, - who: who.clone(), - amount, - }); Ok(()) - }) + })?; + >::PostDeposit::on_deposit( + currency_id, + who, + amount, + )?; + Self::deposit_event(Event::Deposited { + currency_id, + who: who.clone(), + amount, + }); + Ok(()) } } @@ -1203,7 +1216,11 @@ impl MultiCurrency for Pallet { return amount; } - T::OnSlash::on_slash(currency_id, who, amount); + >::OnSlash::on_slash( + currency_id, + who, + amount, + ); let account = Self::accounts(who, currency_id); let free_slashed_amount = account.free.min(amount); // Cannot underflow because free_slashed_amount can never be greater than amount @@ -1381,7 +1398,11 @@ impl MultiReservableCurrency for Pallet { return value; } - T::OnSlash::on_slash(currency_id, who, value); + >::OnSlash::on_slash( + currency_id, + who, + value, + ); let reserved_balance = Self::reserved_balance(currency_id, who); let actual = reserved_balance.min(value); Self::mutate_account(who, currency_id, |account, _| { @@ -1805,6 +1826,10 @@ impl fungibles::Inspect for Pallet { ) -> WithdrawConsequence { Self::withdraw_consequence(who, asset_id, amount, &Self::accounts(who, asset_id)) } + + fn asset_exists(asset: Self::AssetId) -> bool { + TotalIssuance::::contains_key(asset) + } } impl fungibles::Mutate for Pallet { diff --git a/tokens/src/mock.rs b/tokens/src/mock.rs index c994f3928..feb85e898 100644 --- a/tokens/src/mock.rs +++ b/tokens/src/mock.rs @@ -226,10 +226,18 @@ thread_local! { pub static KILLED: RefCell> = RefCell::new(vec![]); } -pub struct TrackCreatedAccounts; -impl TrackCreatedAccounts { - pub fn accounts() -> Vec<(AccountId, CurrencyId)> { - CREATED.with(|accounts| accounts.borrow().clone()) +pub struct TrackCreatedAccounts(marker::PhantomData); +impl TrackCreatedAccounts +where + T::AccountId: From + Into, + T::CurrencyId: From + Into, +{ + pub fn accounts() -> Vec<(T::AccountId, T::CurrencyId)> { + CREATED + .with(|accounts| accounts.borrow().clone()) + .iter() + .map(|account| (account.0.clone().into(), account.1.clone().into())) + .collect() } pub fn reset() { @@ -238,18 +246,30 @@ impl TrackCreatedAccounts { }); } } -impl Happened<(AccountId, CurrencyId)> for TrackCreatedAccounts { - fn happened((who, currency): &(AccountId, CurrencyId)) { +impl Happened<(T::AccountId, T::CurrencyId)> for TrackCreatedAccounts +where + T::AccountId: From + Into, + T::CurrencyId: From + Into, +{ + fn happened((who, currency): &(T::AccountId, T::CurrencyId)) { CREATED.with(|accounts| { - accounts.borrow_mut().push((who.clone(), *currency)); + accounts.borrow_mut().push((who.clone().into(), (*currency).into())); }); } } -pub struct TrackKilledAccounts; -impl TrackKilledAccounts { - pub fn accounts() -> Vec<(AccountId, CurrencyId)> { - KILLED.with(|accounts| accounts.borrow().clone()) +pub struct TrackKilledAccounts(marker::PhantomData); +impl TrackKilledAccounts +where + T::AccountId: From + Into, + T::CurrencyId: From + Into, +{ + pub fn accounts() -> Vec<(T::AccountId, T::CurrencyId)> { + KILLED + .with(|accounts| accounts.borrow().clone()) + .iter() + .map(|account| (account.0.clone().into(), account.1.clone().into())) + .collect() } pub fn reset() { @@ -258,23 +278,29 @@ impl TrackKilledAccounts { }); } } -impl Happened<(AccountId, CurrencyId)> for TrackKilledAccounts { - fn happened((who, currency): &(AccountId, CurrencyId)) { +impl Happened<(T::AccountId, T::CurrencyId)> for TrackKilledAccounts +where + T::AccountId: From + Into, + T::CurrencyId: From + Into, +{ + fn happened((who, currency): &(T::AccountId, T::CurrencyId)) { KILLED.with(|accounts| { - accounts.borrow_mut().push((who.clone(), *currency)); + accounts.borrow_mut().push((who.clone().into(), (*currency).into())); }); } } thread_local! { pub static ON_SLASH_CALLS: RefCell = RefCell::new(0); - pub static ON_DEPOSIT_CALLS: RefCell = RefCell::new(0); - pub static ON_TRANSFER_CALLS: RefCell = RefCell::new(0); + pub static ON_DEPOSIT_PREHOOK_CALLS: RefCell = RefCell::new(0); + pub static ON_DEPOSIT_POSTHOOK_CALLS: RefCell = RefCell::new(0); + pub static ON_TRANSFER_PREHOOK_CALLS: RefCell = RefCell::new(0); + pub static ON_TRANSFER_POSTHOOK_CALLS: RefCell = RefCell::new(0); } pub struct OnSlashHook(marker::PhantomData); -impl OnSlash for OnSlashHook { - fn on_slash(_currency_id: CurrencyId, _account_id: &T::AccountId, _amount: Balance) { +impl OnSlash for OnSlashHook { + fn on_slash(_currency_id: T::CurrencyId, _account_id: &T::AccountId, _amount: T::Balance) { ON_SLASH_CALLS.with(|cell| *cell.borrow_mut() += 1); } } @@ -284,34 +310,77 @@ impl OnSlashHook { } } -pub struct OnDepositHook(marker::PhantomData); -impl OnDeposit for OnDepositHook { - fn on_deposit(_currency_id: CurrencyId, _account_id: &T::AccountId, _amount: Balance) -> DispatchResult { - ON_DEPOSIT_CALLS.with(|cell| *cell.borrow_mut() += 1); +pub struct PreDeposit(marker::PhantomData); +impl OnDeposit for PreDeposit { + fn on_deposit(_currency_id: T::CurrencyId, _account_id: &T::AccountId, _amount: T::Balance) -> DispatchResult { + ON_DEPOSIT_PREHOOK_CALLS.with(|cell| *cell.borrow_mut() += 1); Ok(()) } } -impl OnDepositHook { +impl PreDeposit { pub fn calls() -> u32 { - ON_DEPOSIT_CALLS.with(|accounts| *accounts.borrow()) + ON_DEPOSIT_PREHOOK_CALLS.with(|accounts| accounts.borrow().clone()) } } -pub struct OnTransferHook(marker::PhantomData); -impl OnTransfer for OnTransferHook { +pub struct PostDeposit(marker::PhantomData); +impl OnDeposit for PostDeposit { + fn on_deposit(currency_id: T::CurrencyId, account_id: &T::AccountId, amount: T::Balance) -> DispatchResult { + ON_DEPOSIT_POSTHOOK_CALLS.with(|cell| *cell.borrow_mut() += 1); + let account_balance: AccountData = + tokens::Pallet::::accounts::(account_id.clone(), currency_id); + assert!( + account_balance.free.ge(&amount), + "Posthook must run after the account balance is updated." + ); + Ok(()) + } +} +impl PostDeposit { + pub fn calls() -> u32 { + ON_DEPOSIT_POSTHOOK_CALLS.with(|accounts| accounts.borrow().clone()) + } +} + +pub struct PreTransfer(marker::PhantomData); +impl OnTransfer for PreTransfer { fn on_transfer( - _currency_id: CurrencyId, + _currency_id: T::CurrencyId, _from: &T::AccountId, _to: &T::AccountId, - _amount: Balance, + _amount: T::Balance, + ) -> DispatchResult { + ON_TRANSFER_PREHOOK_CALLS.with(|cell| *cell.borrow_mut() += 1); + Ok(()) + } +} +impl PreTransfer { + pub fn calls() -> u32 { + ON_TRANSFER_PREHOOK_CALLS.with(|accounts| accounts.borrow().clone()) + } +} + +pub struct PostTransfer(marker::PhantomData); +impl OnTransfer for PostTransfer { + fn on_transfer( + currency_id: T::CurrencyId, + _from: &T::AccountId, + to: &T::AccountId, + amount: T::Balance, ) -> DispatchResult { - ON_TRANSFER_CALLS.with(|cell| *cell.borrow_mut() += 1); + ON_TRANSFER_POSTHOOK_CALLS.with(|cell| *cell.borrow_mut() += 1); + let account_balance: AccountData = + tokens::Pallet::::accounts::(to.clone(), currency_id); + assert!( + account_balance.free.ge(&amount), + "Posthook must run after the account balance is updated." + ); Ok(()) } } -impl OnTransferHook { +impl PostTransfer { pub fn calls() -> u32 { - ON_TRANSFER_CALLS.with(|accounts| *accounts.borrow()) + ON_TRANSFER_POSTHOOK_CALLS.with(|accounts| accounts.borrow().clone()) } } @@ -319,6 +388,22 @@ parameter_types! { pub DustReceiver: AccountId = PalletId(*b"orml/dst").into_account_truncating(); } +pub struct CurrencyHooks(marker::PhantomData); +impl MutationHooks for CurrencyHooks +where + T::AccountId: From + Into, + T::CurrencyId: From + Into, +{ + type OnDust = TransferDust; + type OnSlash = OnSlashHook; + type PreDeposit = PreDeposit; + type PostDeposit = PostDeposit; + type PreTransfer = PreTransfer; + type PostTransfer = PostTransfer; + type OnNewTokenAccount = TrackCreatedAccounts; + type OnKilledTokenAccount = TrackKilledAccounts; +} + impl Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; @@ -326,12 +411,7 @@ impl Config for Runtime { type CurrencyId = CurrencyId; type WeightInfo = (); type ExistentialDeposits = ExistentialDeposits; - type OnDust = TransferDust; - type OnSlash = OnSlashHook; - type OnDeposit = OnDepositHook; - type OnTransfer = OnTransferHook; - type OnNewTokenAccount = TrackCreatedAccounts; - type OnKilledTokenAccount = TrackKilledAccounts; + type CurrencyHooks = CurrencyHooks; type MaxLocks = ConstU32<2>; type MaxReserves = ConstU32<2>; type ReserveIdentifier = ReserveIdentifier; @@ -355,13 +435,13 @@ construct_runtime!( } ); - pub struct ExtBuilder { tokens_endowment: Vec<(AccountId, CurrencyId, Balance)>, created_tokens_for_staking: Vec<(AccountId, CurrencyId, Balance)>, treasury_genesis: bool, } + impl Default for ExtBuilder { fn default() -> Self { Self { @@ -372,6 +452,7 @@ impl Default for ExtBuilder { } } + impl ExtBuilder { #[allow(unused_mut)] pub fn balances(mut self, mut tokens_endowment: Vec<(AccountId, CurrencyId, Balance)>) -> Self { @@ -401,8 +482,8 @@ impl ExtBuilder { .unwrap(); } - TrackCreatedAccounts::reset(); - TrackKilledAccounts::reset(); + TrackCreatedAccounts::::reset(); + TrackKilledAccounts::::reset(); let mut ext = sp_io::TestExternalities::new(t); ext.execute_with(|| System::set_block_number(1)); diff --git a/tokens/src/tests.rs b/tokens/src/tests.rs index 596144767..3eea3daa5 100644 --- a/tokens/src/tests.rs +++ b/tokens/src/tests.rs @@ -55,7 +55,7 @@ fn transfer_should_work() { Error::::ExistentialDeposit, ); assert_ok!(Tokens::transfer(Some(ALICE).into(), CHARLIE, DOT, 2)); - assert_eq!(TrackCreatedAccounts::accounts(), vec![(CHARLIE, DOT)]); + assert_eq!(TrackCreatedAccounts::::accounts(), vec![(CHARLIE, DOT)]); // imply AllowDeath assert!(Accounts::::contains_key(ALICE, DOT)); @@ -132,7 +132,7 @@ fn transfer_all_allow_death_should_work() { assert!(Accounts::::contains_key(ALICE, DOT)); assert_eq!(Tokens::free_balance(DOT, &ALICE), 100); assert_ok!(Tokens::transfer_all(Some(ALICE).into(), CHARLIE, DOT, false)); - assert_eq!(TrackCreatedAccounts::accounts(), vec![(CHARLIE, DOT)]); + assert_eq!(TrackCreatedAccounts::::accounts(), vec![(CHARLIE, DOT)]); System::assert_last_event(RuntimeEvent::Tokens(crate::Event::Transfer { currency_id: DOT, from: ALICE, @@ -141,7 +141,7 @@ fn transfer_all_allow_death_should_work() { })); assert!(!Accounts::::contains_key(ALICE, DOT)); assert_eq!(Tokens::free_balance(DOT, &ALICE), 0); - assert_eq!(TrackKilledAccounts::accounts(), vec![(ALICE, DOT)]); + assert_eq!(TrackKilledAccounts::::accounts(), vec![(ALICE, DOT)]); assert_ok!(Tokens::set_lock(ID_1, DOT, &BOB, 50)); assert_eq!(Tokens::accounts(&BOB, DOT).frozen, 50); @@ -179,7 +179,7 @@ fn force_transfer_should_work() { amount: 100, })); assert!(!Accounts::::contains_key(ALICE, DOT)); - assert_eq!(TrackKilledAccounts::accounts(), vec![(ALICE, DOT)]); + assert_eq!(TrackKilledAccounts::::accounts(), vec![(ALICE, DOT)]); assert_eq!(Tokens::free_balance(DOT, &ALICE), 0); assert_eq!(Tokens::free_balance(DOT, &BOB), 200); }); @@ -2594,17 +2594,20 @@ fn exceeding_max_reserves_should_fail() { fn lifecycle_callbacks_are_activated() { ExtBuilder::default().build().execute_with(|| { assert_ok!(Tokens::set_balance(RawOrigin::Root.into(), ALICE, DOT, 200, 0)); - assert_eq!(TrackCreatedAccounts::accounts(), vec![(ALICE, DOT)]); + assert_eq!(TrackCreatedAccounts::::accounts(), vec![(ALICE, DOT)]); assert_ok!(Tokens::set_balance(RawOrigin::Root.into(), ALICE, BTC, 200, 0)); - assert_eq!(TrackCreatedAccounts::accounts(), vec![(ALICE, DOT), (ALICE, BTC)]); + assert_eq!( + TrackCreatedAccounts::::accounts(), + vec![(ALICE, DOT), (ALICE, BTC)] + ); assert_ok!(Tokens::transfer_all(Some(ALICE).into(), CHARLIE, BTC, false)); assert_eq!( - TrackCreatedAccounts::accounts(), + TrackCreatedAccounts::::accounts(), vec![(ALICE, DOT), (ALICE, BTC), (CHARLIE, BTC)] ); - assert_eq!(TrackKilledAccounts::accounts(), vec![(ALICE, BTC)]); + assert_eq!(TrackKilledAccounts::::accounts(), vec![(ALICE, BTC)]); }) } @@ -2614,31 +2617,48 @@ fn lifecycle_callbacks_are_activated() { // ************************************************* #[test] -fn deposit_hook_works() { +fn deposit_hooks_work() { ExtBuilder::default().build().execute_with(|| { - let initial_hook_calls = OnDepositHook::::calls(); + let initial_prehook_calls = PreDeposit::::calls(); + let initial_posthook_calls = PostDeposit::::calls(); assert_ok!(Tokens::do_deposit(DOT, &CHARLIE, 0, false, true),); - assert_eq!(OnDepositHook::::calls(), initial_hook_calls); + assert_eq!(PreDeposit::::calls(), initial_prehook_calls); + assert_eq!(PostDeposit::::calls(), initial_posthook_calls); assert_ok!(Tokens::do_deposit(DOT, &CHARLIE, 100, false, true),); - assert_eq!(OnDepositHook::::calls(), initial_hook_calls + 1); + assert_eq!(PreDeposit::::calls(), initial_prehook_calls + 1); + assert_eq!(PostDeposit::::calls(), initial_posthook_calls + 1); - // The hook must be called even if the actual deposit ends up failing assert_noop!( Tokens::do_deposit(DOT, &BOB, 1, false, true), Error::::ExistentialDeposit ); - assert_eq!(OnDepositHook::::calls(), initial_hook_calls + 2); + // The prehook is called + assert_eq!(PreDeposit::::calls(), initial_prehook_calls + 2); + // The posthook is not called + assert_eq!(PostDeposit::::calls(), initial_posthook_calls + 1); }); } #[test] -fn transfer_hook_works() { +fn post_deposit_can_use_new_balance() { + ExtBuilder::default().build().execute_with(|| { + let initial_balance = Tokens::free_balance(DOT, &CHARLIE); + // The following will fail unless Charlie's new balance can be used by the hook, + // because `initial_balance + 100` is higher than Charlie's initial balance. + // If this fails, the posthook is called too soon. + assert_ok!(Tokens::do_deposit(DOT, &CHARLIE, initial_balance + 100, false, true),); + }); +} + +#[test] +fn transfer_hooks_work() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100)]) .build() .execute_with(|| { - let initial_hook_calls = OnTransferHook::::calls(); + let initial_prehook_calls = PreTransfer::::calls(); + let initial_posthook_calls = PostTransfer::::calls(); assert_ok!(Tokens::do_transfer( DOT, &ALICE, @@ -2646,7 +2666,8 @@ fn transfer_hook_works() { 0, ExistenceRequirement::AllowDeath ),); - assert_eq!(OnTransferHook::::calls(), initial_hook_calls); + assert_eq!(PreTransfer::::calls(), initial_prehook_calls); + assert_eq!(PostTransfer::::calls(), initial_posthook_calls); assert_ok!(Tokens::do_transfer( DOT, @@ -2655,13 +2676,36 @@ fn transfer_hook_works() { 10, ExistenceRequirement::AllowDeath )); - assert_eq!(OnTransferHook::::calls(), initial_hook_calls + 1); + assert_eq!(PreTransfer::::calls(), initial_prehook_calls + 1); + assert_eq!(PostTransfer::::calls(), initial_posthook_calls + 1); - // The hook must be called even if the actual transfer ends up failing assert_noop!( Tokens::do_transfer(DOT, &ALICE, &BOB, 1, ExistenceRequirement::AllowDeath), Error::::ExistentialDeposit ); - assert_eq!(OnTransferHook::::calls(), initial_hook_calls + 2); + // The prehook is called + assert_eq!(PreTransfer::::calls(), initial_prehook_calls + 2); + // The posthook is not called + assert_eq!(PostTransfer::::calls(), initial_posthook_calls + 1); + }); +} + +#[test] +fn post_transfer_can_use_new_balance() { + ExtBuilder::default() + .balances(vec![(ALICE, DOT, 100)]) + .build() + .execute_with(|| { + let initial_balance = Tokens::free_balance(DOT, &CHARLIE); + // The following will fail unless Charlie's new balance can be used by the hook, + // because `initial_balance + 100` is higher than Charlie's initial balance. + // If this fails, the posthook is called too soon. + assert_ok!(Tokens::do_transfer( + DOT, + &ALICE, + &CHARLIE, + initial_balance + 100, + ExistenceRequirement::AllowDeath + )); }); } diff --git a/tokens/src/tests_fungibles.rs b/tokens/src/tests_fungibles.rs index c424b3127..600897fe2 100644 --- a/tokens/src/tests_fungibles.rs +++ b/tokens/src/tests_fungibles.rs @@ -22,6 +22,9 @@ fn fungibles_inspect_trait_should_work() { ); assert_ok!(>::can_deposit(DOT, &ALICE, 1, false).into_result()); assert_ok!(>::can_withdraw(DOT, &ALICE, 1).into_result()); + + assert!(>::asset_exists(DOT)); + assert!(!>::asset_exists(BTC)); }); } @@ -87,7 +90,7 @@ fn fungibles_unbalanced_trait_should_work() { assert_ok!(>::reserve(DOT, &ALICE, 50)); assert_noop!( >::decrease_balance(DOT, &ALICE, 60), - ArithmeticError::Underflow + TokenError::NoFunds ); assert_eq!( >::decrease_balance(DOT, &ALICE, 50), @@ -124,11 +127,7 @@ fn fungibles_unbalanced_trait_should_work() { assert_ok!(>::reserve(DOT, &ALICE, 50)); assert_eq!( >::decrease_balance_at_most(DOT, &ALICE, 60), - 0 - ); - assert_eq!( - >::decrease_balance_at_most(DOT, &ALICE, 50), - 50 + 50, ); assert_eq!(>::balance(DOT, &ALICE), 50); assert_eq!( @@ -287,7 +286,7 @@ fn fungibles_inspect_convert_should_work() { >; ExtBuilder::default() - .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)]) + .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100), (BOB, BTC, 100)]) .build() .execute_with(|| { assert_eq!( @@ -298,6 +297,10 @@ fn fungibles_inspect_convert_should_work() { >::total_issuance(DOT), 20000 ); + + assert!(>::asset_exists(DOT)); + assert!(>::asset_exists(BTC)); + assert!(!>::asset_exists(ETH)); }); } diff --git a/traits/Cargo.toml b/traits/Cargo.toml index 6acc8c615..7a7fa01d0 100644 --- a/traits/Cargo.toml +++ b/traits/Cargo.toml @@ -14,12 +14,12 @@ codec = { package = "parity-scale-codec", version = "3.0.0", default-features = num-traits = { version = "0.2.14", default-features = false } impl-trait-for-tuples = "0.2.2" -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } -xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.31" } +xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.36" } orml-utilities = { path = "../utilities", version = "0.4.1-dev", default-features = false } diff --git a/traits/src/currency.rs b/traits/src/currency.rs index eaaf5b4d1..8c391f604 100644 --- a/traits/src/currency.rs +++ b/traits/src/currency.rs @@ -1,4 +1,4 @@ -use crate::arithmetic; +use crate::{arithmetic, Happened}; use codec::{Codec, FullCodec, MaxEncodedLen}; pub use frame_support::{ traits::{BalanceStatus, DefensiveSaturating, LockIdentifier}, @@ -690,3 +690,40 @@ impl OnTransfer Ok(()) } } + +pub trait MutationHooks { + /// Handler to burn or transfer account's dust + type OnDust: OnDust; + + /// Hook to run before slashing an account. + type OnSlash: OnSlash; + + /// Hook to run before depositing into an account. + type PreDeposit: OnDeposit; + + /// Hook to run after depositing into an account. + type PostDeposit: OnDeposit; + + /// Hook to run before transferring from an account to another. + type PreTransfer: OnTransfer; + + /// Hook to run after transferring from an account to another. + type PostTransfer: OnTransfer; + + /// Handler for when an account was created + type OnNewTokenAccount: Happened<(AccountId, CurrencyId)>; + + /// Handler for when an account was created + type OnKilledTokenAccount: Happened<(AccountId, CurrencyId)>; +} + +impl MutationHooks for () { + type OnDust = (); + type OnSlash = (); + type PreDeposit = (); + type PostDeposit = (); + type PreTransfer = (); + type PostTransfer = (); + type OnNewTokenAccount = (); + type OnKilledTokenAccount = (); +} diff --git a/traits/src/lib.rs b/traits/src/lib.rs index 818d51251..ea5231dd9 100644 --- a/traits/src/lib.rs +++ b/traits/src/lib.rs @@ -1,6 +1,6 @@ #![cfg_attr(not(feature = "std"), no_std)] -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; use impl_trait_for_tuples::impl_for_tuples; use sp_runtime::{DispatchResult, RuntimeDebug}; use sp_std::{ @@ -8,15 +8,12 @@ use sp_std::{ prelude::Vec, }; -#[cfg(feature = "std")] -use serde::{Deserialize, Serialize}; - pub use asset_registry::{FixedConversionRateProvider, WeightToFeeConverter}; pub use auction::{Auction, AuctionHandler, AuctionInfo, OnNewBidResult}; pub use currency::{ BalanceStatus, BasicCurrency, BasicCurrencyExtended, BasicLockableCurrency, BasicReservableCurrency, LockIdentifier, MultiCurrency, MultiCurrencyExtended, MultiLockableCurrency, MultiReservableCurrency, - NamedBasicReservableCurrency, NamedMultiReservableCurrency, OnDust, + NamedBasicReservableCurrency, NamedMultiReservableCurrency, }; pub use data_provider::{DataFeeder, DataProvider, DataProviderExtended}; pub use get_by_key::GetByKey; @@ -25,6 +22,8 @@ pub use nft::InspectExtended; pub use price::{DefaultPriceProvider, PriceProvider}; pub use rewards::RewardHandler; use scale_info::TypeInfo; +#[cfg(feature = "std")] +use serde::{Deserialize, Serialize}; pub use xcm_transfer::XcmTransfer; pub mod arithmetic; @@ -58,7 +57,7 @@ pub trait CombineData { } /// Indicate if should change a value -#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub enum Change { /// No change. NoChange, diff --git a/traits/src/xcm_transfer.rs b/traits/src/xcm_transfer.rs index cd671f5e6..c4dacb116 100644 --- a/traits/src/xcm_transfer.rs +++ b/traits/src/xcm_transfer.rs @@ -19,4 +19,13 @@ pub trait XcmTransfer { dest: MultiLocation, dest_weight_limit: WeightLimit, ) -> DispatchResult; + + /// Transfer `MultiAssetWithFee` + fn transfer_multiasset_with_fee( + who: AccountId, + asset: MultiAsset, + fee: MultiAsset, + dest: MultiLocation, + dest_weight_limit: WeightLimit, + ) -> DispatchResult; } diff --git a/unknown-tokens/Cargo.toml b/unknown-tokens/Cargo.toml index 6dc5bef90..e8a10eaaa 100644 --- a/unknown-tokens/Cargo.toml +++ b/unknown-tokens/Cargo.toml @@ -8,36 +8,37 @@ authors = ["Acala Developers"] edition = "2021" [dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } serde = { version = "1.0.136", optional = true } -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } -xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.31" } +xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.36" } orml-xcm-support = { path = "../xcm-support", default-features = false } [dev-dependencies] -sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } [features] default = ["std"] std = [ "serde", + "codec/std", - "scale-info/std", - "sp-std/std", "frame-support/std", "frame-system/std", - "xcm/std", "orml-xcm-support/std", + "scale-info/std", + "sp-std/std", + "xcm/std", ] try-runtime = [ - "frame-system/try-runtime", "frame-support/try-runtime", + "frame-system/try-runtime", ] diff --git a/utilities/Cargo.toml b/utilities/Cargo.toml index 4f4175652..be4e2dae5 100644 --- a/utilities/Cargo.toml +++ b/utilities/Cargo.toml @@ -12,15 +12,15 @@ scale-info = { version = "2.1.2", default-features = false, features = ["derive" serde = { version = "1.0.136", optional = true, features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } [dev-dependencies] serde_json = "1.0.64" -frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } [features] default = ["std"] diff --git a/vesting/Cargo.toml b/vesting/Cargo.toml index 5e1d781eb..f5f8115e5 100644 --- a/vesting/Cargo.toml +++ b/vesting/Cargo.toml @@ -8,37 +8,40 @@ authors = ["Laminar Developers "] edition = "2021" [dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["max-encoded-len"] } scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } serde = { version = "1.0.136", optional = true } -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["max-encoded-len"] } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } [dev-dependencies] -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } [features] default = ["std"] std = [ "serde", + "codec/std", + "frame-support/std", + "frame-system/std", "scale-info/std", + "sp-io/std", "sp-runtime/std", "sp-std/std", - "sp-io/std", - "frame-support/std", - "frame-system/std", ] runtime-benchmarks = [ "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", ] try-runtime = [ - "frame-system/try-runtime", "frame-support/try-runtime", + "frame-system/try-runtime", ] + diff --git a/vesting/src/lib.rs b/vesting/src/lib.rs index c206d6473..5fd926bfe 100644 --- a/vesting/src/lib.rs +++ b/vesting/src/lib.rs @@ -245,7 +245,8 @@ pub mod module { #[pallet::call] impl Pallet { - #[pallet::weight(T::WeightInfo::claim((::MaxVestingSchedules::get() / 2) as u32))] + #[pallet::call_index(0)] + #[pallet::weight(T::WeightInfo::claim(::MaxVestingSchedules::get() / 2))] pub fn claim(origin: OriginFor) -> DispatchResult { let who = ensure_signed(origin)?; let locked_amount = Self::do_claim(&who); @@ -257,6 +258,7 @@ pub mod module { Ok(()) } + #[pallet::call_index(1)] #[pallet::weight(T::WeightInfo::vested_transfer())] pub fn vested_transfer( origin: OriginFor, @@ -265,6 +267,14 @@ pub mod module { ) -> DispatchResult { let from = T::VestedTransferOrigin::ensure_origin(origin)?; let to = T::Lookup::lookup(dest)?; + + if to == from { + ensure!( + T::Currency::free_balance(&from) >= schedule.total_amount().ok_or(ArithmeticError::Overflow)?, + Error::::InsufficientBalanceToLock, + ); + } + Self::do_vested_transfer(&from, &to, schedule.clone())?; Self::deposit_event(Event::VestingScheduleAdded { @@ -275,6 +285,7 @@ pub mod module { Ok(()) } + #[pallet::call_index(2)] #[pallet::weight(T::WeightInfo::update_vesting_schedules(vesting_schedules.len() as u32))] pub fn update_vesting_schedules( origin: OriginFor, @@ -290,7 +301,8 @@ pub mod module { Ok(()) } - #[pallet::weight(T::WeightInfo::claim((::MaxVestingSchedules::get() / 2) as u32))] + #[pallet::call_index(3)] + #[pallet::weight(T::WeightInfo::claim(::MaxVestingSchedules::get() / 2))] pub fn claim_for(origin: OriginFor, dest: ::Source) -> DispatchResult { let _ = ensure_signed(origin)?; let who = T::Lookup::lookup(dest)?; diff --git a/vesting/src/mock.rs b/vesting/src/mock.rs index 75024a63f..9a2a871fa 100644 --- a/vesting/src/mock.rs +++ b/vesting/src/mock.rs @@ -116,6 +116,9 @@ pub const ALICE: AccountId = 1; pub const BOB: AccountId = 2; pub const CHARLIE: AccountId = 3; +pub const ALICE_BALANCE: u64 = 100; +pub const CHARLIE_BALANCE: u64 = 50; + #[derive(Default)] pub struct ExtBuilder; @@ -126,7 +129,7 @@ impl ExtBuilder { .unwrap(); pallet_balances::GenesisConfig:: { - balances: vec![(ALICE, 100), (CHARLIE, 50)], + balances: vec![(ALICE, ALICE_BALANCE), (CHARLIE, CHARLIE_BALANCE)], } .assimilate_storage(&mut t) .unwrap(); diff --git a/vesting/src/tests.rs b/vesting/src/tests.rs index 97371ffac..2419d6680 100644 --- a/vesting/src/tests.rs +++ b/vesting/src/tests.rs @@ -87,6 +87,45 @@ fn vested_transfer_works() { }); } +#[test] +fn self_vesting() { + ExtBuilder::build().execute_with(|| { + System::set_block_number(1); + + let schedule = VestingSchedule { + start: 0u64, + period: 10u64, + period_count: 1u32, + per_period: ALICE_BALANCE, + }; + + let bad_schedule = VestingSchedule { + start: 0u64, + period: 10u64, + period_count: 1u32, + per_period: 10 * ALICE_BALANCE, + }; + + assert_noop!( + Vesting::vested_transfer(RuntimeOrigin::signed(ALICE), ALICE, bad_schedule), + crate::Error::::InsufficientBalanceToLock + ); + + assert_ok!(Vesting::vested_transfer( + RuntimeOrigin::signed(ALICE), + ALICE, + schedule.clone() + )); + + assert_eq!(Vesting::vesting_schedules(&ALICE), vec![schedule.clone()]); + System::assert_last_event(RuntimeEvent::Vesting(crate::Event::VestingScheduleAdded { + from: ALICE, + to: ALICE, + vesting_schedule: schedule, + })); + }); +} + #[test] fn add_new_vesting_schedule_merges_with_current_locked_balance_and_until() { ExtBuilder::build().execute_with(|| { diff --git a/weight-gen/src/main.rs b/weight-gen/src/main.rs index 7fdf90211..b8f521ca5 100644 --- a/weight-gen/src/main.rs +++ b/weight-gen/src/main.rs @@ -162,7 +162,7 @@ fn main() { // Use empty header if a header path is not given. let header = { if let Some(path) = matches.get_one::("header") { - ::std::fs::read_to_string(&path).expect("Header file not found") + ::std::fs::read_to_string(path).expect("Header file not found") } else { String::from("") } @@ -175,7 +175,7 @@ fn main() { // Use default template if template path is not given. let template = { if let Some(path) = matches.get_one::("template") { - ::std::fs::read_to_string(&path).expect("Template file not found") + ::std::fs::read_to_string(path).expect("Template file not found") } else { String::from(DEFAULT_TEMPLATE) } @@ -183,7 +183,7 @@ fn main() { // Write benchmark to file or print to terminal if output path is not given. if let Some(path) = matches.get_one::("output") { - let mut output_file = ::std::fs::File::create(&path).expect("Could not create output file"); + let mut output_file = ::std::fs::File::create(path).expect("Could not create output file"); handlebars .render_template_to_write(&template, &hbs_data, &mut output_file) diff --git a/weight-gen/src/template.hbs b/weight-gen/src/template.hbs index 20003b1a4..0f4233ebc 100644 --- a/weight-gen/src/template.hbs +++ b/weight-gen/src/template.hbs @@ -13,16 +13,16 @@ impl ModuleWeights { {{#each benchmarks as |benchmark|}} // Storage access info // - {{#each benchmark.comments as |c|}} - // {{c}} + {{#each benchmark.comments as |comment|}} + // {{comment}} {{/each}} pub fn {{benchmark.name~}} () -> Weight { - ({{underscore benchmark.weight}} as Weight) + Weight::from_ref_time({{underscore benchmark.weight}}) {{#if (ne benchmark.reads 0)}} - .saturating_add(T::DbWeight::get().reads({{benchmark.reads}} as Weight)) + .saturating_add(T::DbWeight::get().reads({{benchmark.reads}})) {{/if}} {{#if (ne benchmark.writes 0)}} - .saturating_add(T::DbWeight::get().writes({{benchmark.writes}} as Weight)) + .saturating_add(T::DbWeight::get().writes({{benchmark.writes}})) {{/if}} } {{/each}} diff --git a/weight-meter/Cargo.toml b/weight-meter/Cargo.toml index 922db6c53..7f9d38ca7 100644 --- a/weight-meter/Cargo.toml +++ b/weight-meter/Cargo.toml @@ -10,19 +10,21 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } weight-meter-procedural = { path = "weight-meter-procedural", default-features = false } [dev-dependencies] serde = { version = "1.0.136" } codec = { package = "parity-scale-codec", version = "3.0.0" } -sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } -frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } + +orml-bencher = { path = "../bencher" } [features] default = ["std"] diff --git a/weight-meter/src/mock.rs b/weight-meter/src/mock.rs index dee781d26..8126a377f 100644 --- a/weight-meter/src/mock.rs +++ b/weight-meter/src/mock.rs @@ -19,6 +19,7 @@ pub mod test_module { #[pallet::call] impl Pallet { + #[pallet::call_index(0)] #[pallet::weight(50_000)] #[orml_weight_meter::start] pub fn expect_100(origin: OriginFor) -> DispatchResultWithPostInfo { @@ -29,6 +30,7 @@ pub mod test_module { Ok(Some(orml_weight_meter::used_weight()).into()) } + #[pallet::call_index(1)] #[pallet::weight(50_000)] #[orml_weight_meter::start] pub fn expect_500(origin: OriginFor) -> DispatchResultWithPostInfo { @@ -43,6 +45,7 @@ pub mod test_module { Ok(Some(orml_weight_meter::used_weight()).into()) } + #[pallet::call_index(2)] #[pallet::weight(50_000)] #[orml_weight_meter::start] pub fn expect_max_weight(origin: OriginFor) -> DispatchResultWithPostInfo { @@ -54,6 +57,7 @@ pub mod test_module { Ok(Some(orml_weight_meter::used_weight()).into()) } + #[pallet::call_index(3)] #[pallet::weight(50_000)] #[orml_weight_meter::start] pub fn expect_100_or_200(origin: OriginFor, branch: bool) -> DispatchResultWithPostInfo { @@ -68,6 +72,7 @@ pub mod test_module { Ok(Some(orml_weight_meter::used_weight()).into()) } + #[pallet::call_index(4)] #[pallet::weight(50_000)] #[orml_weight_meter::start] pub fn nested_inner_methods(origin: OriginFor) -> DispatchResultWithPostInfo { @@ -78,6 +83,7 @@ pub mod test_module { Ok(Some(orml_weight_meter::used_weight()).into()) } + #[pallet::call_index(5)] #[pallet::weight(50_000)] #[orml_weight_meter::start] pub fn nested_extrinsic(origin: OriginFor) -> DispatchResultWithPostInfo { diff --git a/xcm-support/Cargo.toml b/xcm-support/Cargo.toml index d3e1e0b51..c2ef881a0 100644 --- a/xcm-support/Cargo.toml +++ b/xcm-support/Cargo.toml @@ -10,22 +10,23 @@ edition = "2021" [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } -xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.31" } -xcm-executor = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.31" } +xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.36" } +xcm-executor = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.36" } orml-traits = { path = "../traits", version = "0.4.1-dev", default-features = false } [features] default = ["std"] std = [ - "sp-std/std", - "sp-runtime/std", + "codec/std", "frame-support/std", - "xcm/std", - "xcm-executor/std", "orml-traits/std", + "sp-runtime/std", + "sp-std/std", + "xcm-executor/std", + "xcm/std", ] diff --git a/xcm/Cargo.toml b/xcm/Cargo.toml index 027b49572..0008292dc 100644 --- a/xcm/Cargo.toml +++ b/xcm/Cargo.toml @@ -11,28 +11,30 @@ edition = "2021" codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } -xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.31" } -pallet-xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.31" } +pallet-xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.36" } +xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.36" } [dev-dependencies] -xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.31" } +xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.36" } + [features] default = ["std"] std = [ "codec/std", - "scale-info/std", - "sp-std/std", "frame-support/std", "frame-system/std", - "xcm/std", "pallet-xcm/std", + "scale-info/std", + "sp-std/std", + "xcm/std", ] try-runtime = [ - "frame-system/try-runtime", "frame-support/try-runtime", + "frame-system/try-runtime", + "pallet-xcm/try-runtime", ] diff --git a/xcm/src/lib.rs b/xcm/src/lib.rs index 61607a5b4..40057f889 100644 --- a/xcm/src/lib.rs +++ b/xcm/src/lib.rs @@ -50,6 +50,7 @@ pub mod module { #[pallet::call] impl Pallet { /// Send an XCM message as parachain sovereign. + #[pallet::call_index(0)] #[pallet::weight(100_000_000)] pub fn send_as_sovereign( origin: OriginFor, diff --git a/xtokens/Cargo.toml b/xtokens/Cargo.toml index c26f3a1b2..8de34d5c1 100644 --- a/xtokens/Cargo.toml +++ b/xtokens/Cargo.toml @@ -8,46 +8,46 @@ authors = ["Acala Developers"] edition = "2021" [dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } scale-info = { version = "2.1.2", default-features = false, features = ["derive"] } serde = { version = "1.0.136", optional = true } -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } # substrate -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } -frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.31" } +frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-io = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.36" } # cumulus -cumulus-primitives-core = { git = "https://github.com/paritytech/cumulus", default-features = false , branch = "polkadot-v0.9.31" } +cumulus-primitives-core = { git = "https://github.com/paritytech/cumulus", default-features = false , branch = "polkadot-v0.9.36" } # polkadot -pallet-xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.31" } -xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.31" } -xcm-executor = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.31" } +pallet-xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.36" } +xcm = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.36" } +xcm-executor = { git = "https://github.com/paritytech/polkadot", default-features = false , branch = "release-v0.9.36" } # orml -orml-xcm-support = { path = "../xcm-support", default-features = false } orml-traits = { path = "../traits", default-features = false} +orml-xcm-support = { path = "../xcm-support", default-features = false } [dev-dependencies] # substrate -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } -pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.31" } +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.36" } # cumulus -cumulus-primitives-core = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.31" } -cumulus-pallet-dmp-queue = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.31" } -cumulus-pallet-xcmp-queue = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.31" } -cumulus-pallet-xcm = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.31" } -parachain-info = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.31" } +cumulus-pallet-dmp-queue = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.36" } +cumulus-pallet-xcm = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.36" } +cumulus-pallet-xcmp-queue = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.36" } +cumulus-primitives-core = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.36" } +parachain-info = { git = "https://github.com/paritytech/cumulus", branch = "polkadot-v0.9.36" } # polkadot -polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.31" } -polkadot-runtime-parachains = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.31" } -xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.31" } -xcm-simulator = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.31" } +polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.36" } +polkadot-runtime-parachains = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.36" } +xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.36" } +xcm-simulator = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.36" } # orml orml-tokens = { path = "../tokens" } @@ -57,24 +57,31 @@ orml-xcm = { path = "../xcm" } default = ["std"] std = [ "serde", + "codec/std", + "cumulus-primitives-core/std", + "frame-support/std", + "frame-system/std", + "orml-traits/std", + "orml-xcm-support/std", + "pallet-xcm/std", "scale-info/std", + "sp-io/std", "sp-runtime/std", "sp-std/std", - "sp-io/std", - "frame-support/std", - "frame-system/std", - "cumulus-primitives-core/std", - "xcm/std", "xcm-executor/std", - "orml-xcm-support/std", - "orml-traits/std", + "xcm/std", ] runtime-benchmarks = [ + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", "pallet-xcm/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", + "xcm-executor/runtime-benchmarks", ] try-runtime = [ - "frame-system/try-runtime", "frame-support/try-runtime", + "frame-system/try-runtime", + "pallet-xcm/try-runtime", ] diff --git a/xtokens/README.md b/xtokens/README.md index da33a75a7..ab0138ef4 100644 --- a/xtokens/README.md +++ b/xtokens/README.md @@ -2,18 +2,18 @@ ## Overview -The xtokens module provides cross-chain token transfer functionality, by cross-consensus messages(XCM). +The `xtokens` module provides cross-chain token transfer functionality, by cross-consensus messages(XCM). -The xtokens module provides functions for +The `xtokens` module provides functions for - Token transfer from parachains to relay chain. - Token transfer between parachains, including relay chain tokens like DOT, - KSM, and parachain tokens like ACA, aUSD. + KSM, and parachain tokens like ACA, aUSD, USDT. ## Notes #### Integration tests -Integration tests could be done manually after integrating orml-xtokens into runtime. To cover the full features, set up at least 4 relay chain validators and 3 collators of different parachains, and use dispatchable calls to include all these scenarios: +Integration tests could be done manually after integrating `xtokens` into a runtime. To cover the full features, set up at least 4 relay chain validators and 3 collators of different parachains, and use dispatchable calls to include all these scenarios: - Transfer relay chain tokens to relay chain. - Transfer tokens issued by parachain A, from parachain A to parachain B. @@ -34,24 +34,24 @@ Integration tests could be done manually after integrating orml-xtokens into run - Transfer relay chain tokens to relay chain, and use relay chain token as fee - Transfer relay chain tokens to parachain, and use relay chain token as fee -- Transfer tokens issued by parachain A, from parachain A to parachain B, and use parachain A token as fee -- Transfer tokens issued by parachain B, from parachain A to parachain B, and use parachain B token as fee -- Transfer tokens issued by parachain C, from parachain A to parachain B, and use parachain C token as fee +- Transfer tokens issued by parachain A, from parachain A to parachain B, and use parachain A token as a fee +- Transfer tokens issued by parachain B, from parachain A to parachain B, and use parachain B token as a fee +- Transfer tokens issued by parachain C, from parachain A to parachain B, and use parachain C token as a fee - Transfer tokens issued by parachain B, from parachain A to parachain B, and use relay chain token as fee -Notice, in the case of parachain A transfer parachain B token to parachain B, and use relay chain token as fee. Because fee asset is relaychain token, and non fee asset is parachain B token, this is two different chain. We call chain of fee asset as fee_reserve, and chain of non fee asset as non_fee_reserve. And in this case fee_reserve location is also refer to destination parachain. +Notice, in the case of parachain A transfer parachain B token to parachain B, and use relay chain token as fee. Because fee asset is relaychain token, and non fee asset is parachain B token, this is two different chain. We call chain of fee asset as `fee_reserve`, and chain of non fee asset as `non_fee_reserve`. And in this case `fee_reserve` location is also refer to destination parachain. -The current implementation is sent two xcm from sender parachain. first xcm sent to fee reserve chain which will also route xcm message to destination parachain. second xcm directly sent to destination parachain. +The current implementation sends two XCM from a sender parachain. First XCM is sent to the fee reserve chain which will also route the XCM message to the destination parachain. Second XCM directly sent to destination parachain. -the fee amount in fee asset is split into two parts. -1. fee asset sent to fee reserve chain = fee_amount - min_xcm_fee -2. fee asset sent to dest reserve chain = min_xcm_fee +The fee amount in fee asset is split into two parts: +1. Fee asset sent to fee reserve chain = fee_amount - min_xcm_fee +2. Fee asset sent to dest reserve chain = min_xcm_fee -Parachains should implements config `MinXcmFee` in `xtokens` module config: +Parachains should implement config `MinXcmFee` in `xtokens` module config: ```rust parameter_type_with_key! { - pub ParachainMinFee: |location: MultiLocation| -> Option { + pub MinXcmReserveFee: |location: MultiLocation| -> Option { #[allow(clippy::match_ref_pats)] // false positive match (location.parents, location.first_interior()) { (1, Some(Parachain(parachains::statemine::ID))) => Some(4_000_000_000), @@ -71,6 +71,6 @@ parameter_type_with_key! { } ``` -Notice the implementation for now also relies on `SelfLocation` which is already in `xtokens` config. The `SelfLocation` is currently set to absolute view `(1, Parachain(id))` and refers to the sender parachain. However `SelfLocation` set to relative view `(0, Here)` will also work. +Notice the implementation for now also relies on `SelfLocation` which is already in `xtokens` config. The `SelfLocation` can be set to the absolute view `(1, Parachain(THIS_PARACHAIN_ID))` and refers to the sender parachain. The alternative is to set `SelfLocation` to relative view `(0, Here)` to adhere to Polkadot guidelines. -We use `SelfLocation` to fund fee to sender's parachain sovereign account on destination parachain, which asset is originated from sender account on sender parachain. This means if user setup too much fee, the fee will not returned to user, instead deposit to sibling parachain sovereign account on destination parachain. \ No newline at end of file +We use `SelfLocation` to fund fee to sender's parachain sovereign account on destination parachain, which asset is originated from sender account on sender parachain. This means if user setup too much fee, the fee will not returned to user, instead deposit to sibling parachain sovereign account on destination parachain. diff --git a/xtokens/src/lib.rs b/xtokens/src/lib.rs index b21d44a89..17470c9ec 100644 --- a/xtokens/src/lib.rs +++ b/xtokens/src/lib.rs @@ -200,6 +200,7 @@ pub mod module { /// received. Receiving depends on if the XCM message could be delivered /// by the network, and if the receiving chain would handle /// messages correctly. + #[pallet::call_index(0)] #[pallet::weight(Pallet::::fixed_weight_of_transfer())] pub fn transfer( origin: OriginFor, @@ -225,6 +226,7 @@ pub mod module { /// received. Receiving depends on if the XCM message could be delivered /// by the network, and if the receiving chain would handle /// messages correctly. + #[pallet::call_index(1)] #[pallet::weight(Pallet::::weight_of_transfer_multiasset(asset, dest))] pub fn transfer_multiasset( origin: OriginFor, @@ -259,6 +261,7 @@ pub mod module { /// received. Receiving depends on if the XCM message could be delivered /// by the network, and if the receiving chain would handle /// messages correctly. + #[pallet::call_index(2)] #[pallet::weight(Pallet::::fixed_weight_of_transfer())] pub fn transfer_with_fee( origin: OriginFor, @@ -295,6 +298,7 @@ pub mod module { /// received. Receiving depends on if the XCM message could be delivered /// by the network, and if the receiving chain would handle /// messages correctly. + #[pallet::call_index(3)] #[pallet::weight(Pallet::::weight_of_transfer_multiasset(asset, dest))] pub fn transfer_multiasset_with_fee( origin: OriginFor, @@ -326,6 +330,7 @@ pub mod module { /// received. Receiving depends on if the XCM message could be delivered /// by the network, and if the receiving chain would handle /// messages correctly. + #[pallet::call_index(4)] #[pallet::weight(Pallet::::fixed_weight_of_transfer())] pub fn transfer_multicurrencies( origin: OriginFor, @@ -355,6 +360,7 @@ pub mod module { /// received. Receiving depends on if the XCM message could be delivered /// by the network, and if the receiving chain would handle /// messages correctly. + #[pallet::call_index(5)] #[pallet::weight(Pallet::::weight_of_transfer_multiassets(assets, fee_item, dest))] pub fn transfer_multiassets( origin: OriginFor, @@ -922,10 +928,8 @@ pub mod module { fn get_reserve_location(assets: &MultiAssets, fee_item: &u32) -> Option { let reserve_idx = if assets.len() == 1 { 0 - } else if *fee_item == 0 { - 1 } else { - 0 + (*fee_item == 0) as usize }; let asset = assets.get(reserve_idx); asset.and_then(T::ReserveProvider::reserve) @@ -953,6 +957,17 @@ pub mod module { ) -> DispatchResult { Self::do_transfer_multiasset(who, asset, dest, dest_weight_limit) } + + #[require_transactional] + fn transfer_multiasset_with_fee( + who: T::AccountId, + asset: MultiAsset, + fee: MultiAsset, + dest: MultiLocation, + dest_weight_limit: WeightLimit, + ) -> DispatchResult { + Self::do_transfer_multiasset_with_fee(who, asset, fee, dest, dest_weight_limit) + } } } diff --git a/xtokens/src/mock/para.rs b/xtokens/src/mock/para.rs index 830ad48f4..19f38d690 100644 --- a/xtokens/src/mock/para.rs +++ b/xtokens/src/mock/para.rs @@ -4,7 +4,7 @@ use crate as orml_xtokens; use frame_support::{ construct_runtime, match_types, parameter_types, traits::{ConstU128, ConstU32, ConstU64, Everything, Get, Nothing}, - weights::constants::WEIGHT_PER_SECOND, + weights::constants::WEIGHT_REF_TIME_PER_SECOND, }; use frame_system::EnsureRoot; use sp_core::H256; @@ -83,21 +83,16 @@ impl orml_tokens::Config for Runtime { type CurrencyId = CurrencyId; type WeightInfo = (); type ExistentialDeposits = ExistentialDeposits; - type OnDust = (); - type OnSlash = (); - type OnDeposit = (); - type OnTransfer = (); + type CurrencyHooks = (); type MaxLocks = ConstU32<50>; type MaxReserves = ConstU32<50>; type ReserveIdentifier = [u8; 8]; type DustRemovalWhitelist = Everything; - type OnNewTokenAccount = (); - type OnKilledTokenAccount = (); } parameter_types! { - pub const ReservedXcmpWeight: Weight = WEIGHT_PER_SECOND.ref_time() / 4; - pub const ReservedDmpWeight: Weight = WEIGHT_PER_SECOND.ref_time() / 4; + pub const ReservedXcmpWeight: Weight = WEIGHT_REF_TIME_PER_SECOND / 4; + pub const ReservedDmpWeight: Weight = WEIGHT_REF_TIME_PER_SECOND / 4; } impl parachain_info::Config for Runtime {} diff --git a/xtokens/src/mock/para_relative_view.rs b/xtokens/src/mock/para_relative_view.rs index 064cdb0db..a44283438 100644 --- a/xtokens/src/mock/para_relative_view.rs +++ b/xtokens/src/mock/para_relative_view.rs @@ -4,7 +4,7 @@ use crate as orml_xtokens; use frame_support::{ construct_runtime, match_types, parameter_types, traits::{ConstU128, ConstU32, ConstU64, Everything, Nothing}, - weights::constants::WEIGHT_PER_SECOND, + weights::constants::WEIGHT_REF_TIME_PER_SECOND, }; use frame_system::EnsureRoot; use sp_core::H256; @@ -86,21 +86,16 @@ impl orml_tokens::Config for Runtime { type CurrencyId = CurrencyId; type WeightInfo = (); type ExistentialDeposits = ExistentialDeposits; - type OnDust = (); - type OnSlash = (); - type OnDeposit = (); - type OnTransfer = (); + type CurrencyHooks = (); type MaxLocks = ConstU32<50>; type MaxReserves = ConstU32<50>; type ReserveIdentifier = [u8; 8]; type DustRemovalWhitelist = Everything; - type OnNewTokenAccount = (); - type OnKilledTokenAccount = (); } parameter_types! { - pub const ReservedXcmpWeight: Weight = WEIGHT_PER_SECOND.ref_time() / 4; - pub const ReservedDmpWeight: Weight = WEIGHT_PER_SECOND.ref_time() / 4; + pub const ReservedXcmpWeight: Weight = WEIGHT_REF_TIME_PER_SECOND / 4; + pub const ReservedDmpWeight: Weight = WEIGHT_REF_TIME_PER_SECOND / 4; } impl parachain_info::Config for Runtime {} diff --git a/xtokens/src/mock/para_teleport.rs b/xtokens/src/mock/para_teleport.rs index a9660e07f..75fbd509c 100644 --- a/xtokens/src/mock/para_teleport.rs +++ b/xtokens/src/mock/para_teleport.rs @@ -4,7 +4,7 @@ use crate as orml_xtokens; use frame_support::{ construct_runtime, match_types, parameter_types, traits::{ConstU128, ConstU32, ConstU64, Everything, Get, Nothing}, - weights::constants::WEIGHT_PER_SECOND, + weights::constants::WEIGHT_REF_TIME_PER_SECOND, }; use frame_system::EnsureRoot; use sp_core::H256; @@ -84,21 +84,16 @@ impl orml_tokens::Config for Runtime { type CurrencyId = CurrencyId; type WeightInfo = (); type ExistentialDeposits = ExistentialDeposits; - type OnDust = (); - type OnSlash = (); - type OnDeposit = (); - type OnTransfer = (); + type CurrencyHooks = (); type MaxLocks = ConstU32<50>; type MaxReserves = ConstU32<50>; type ReserveIdentifier = [u8; 8]; type DustRemovalWhitelist = Everything; - type OnNewTokenAccount = (); - type OnKilledTokenAccount = (); } parameter_types! { - pub const ReservedXcmpWeight: Weight = WEIGHT_PER_SECOND.ref_time() / 4; - pub const ReservedDmpWeight: Weight = WEIGHT_PER_SECOND.ref_time() / 4; + pub const ReservedXcmpWeight: Weight = WEIGHT_REF_TIME_PER_SECOND / 4; + pub const ReservedDmpWeight: Weight = WEIGHT_REF_TIME_PER_SECOND / 4; } impl parachain_info::Config for Runtime {}