From 4c6d8c7b447228040783df44d9959d035f4af6ff Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Tue, 31 Aug 2021 18:33:29 +0800 Subject: [PATCH 01/22] remove setheum_democracy and setheum_staking --- lib-serml/democracy/Cargo.toml | 63 - lib-serml/democracy/README.md | 135 - lib-serml/democracy/src/benchmarking.rs | 781 --- lib-serml/democracy/src/conviction.rs | 118 - lib-serml/democracy/src/lib.rs | 1939 -------- lib-serml/democracy/src/tests.rs | 347 -- lib-serml/democracy/src/tests/cancellation.rs | 92 - lib-serml/democracy/src/tests/decoders.rs | 85 - lib-serml/democracy/src/tests/delegation.rs | 179 - .../democracy/src/tests/external_proposing.rs | 303 -- .../democracy/src/tests/fast_tracking.rs | 98 - lib-serml/democracy/src/tests/lock_voting.rs | 378 -- lib-serml/democracy/src/tests/preimage.rs | 219 - .../democracy/src/tests/public_proposals.rs | 149 - lib-serml/democracy/src/tests/scheduling.rs | 112 - lib-serml/democracy/src/tests/voting.rs | 169 - lib-serml/democracy/src/types.rs | 205 - lib-serml/democracy/src/vote.rs | 186 - lib-serml/democracy/src/vote_threshold.rs | 118 - lib-serml/democracy/src/weights.rs | 404 -- lib-serml/serp/serp-staking/Cargo.toml | 83 - lib-serml/serp/serp-staking/README.md | 246 - .../serp/serp-staking/reward-curve/Cargo.toml | 19 - .../serp/serp-staking/reward-curve/src/lib.rs | 446 -- .../serp/serp-staking/reward-curve/src/log.rs | 127 - .../serp-staking/reward-curve/tests/test.rs | 45 - .../serp/serp-staking/reward-fn/Cargo.toml | 20 - .../serp/serp-staking/reward-fn/src/lib.rs | 233 - .../serp/serp-staking/reward-fn/tests/test.rs | 101 - .../serp/serp-staking/src/benchmarking.rs | 757 --- lib-serml/serp/serp-staking/src/inflation.rs | 108 - lib-serml/serp/serp-staking/src/lib.rs | 3489 ------------- lib-serml/serp/serp-staking/src/mock.rs | 839 ---- lib-serml/serp/serp-staking/src/slashing.rs | 810 --- .../serp/serp-staking/src/testing_utils.rs | 188 - lib-serml/serp/serp-staking/src/tests.rs | 4332 ----------------- lib-serml/serp/serp-staking/src/weights.rs | 453 -- 37 files changed, 18376 deletions(-) delete mode 100644 lib-serml/democracy/Cargo.toml delete mode 100644 lib-serml/democracy/README.md delete mode 100644 lib-serml/democracy/src/benchmarking.rs delete mode 100644 lib-serml/democracy/src/conviction.rs delete mode 100644 lib-serml/democracy/src/lib.rs delete mode 100644 lib-serml/democracy/src/tests.rs delete mode 100644 lib-serml/democracy/src/tests/cancellation.rs delete mode 100644 lib-serml/democracy/src/tests/decoders.rs delete mode 100644 lib-serml/democracy/src/tests/delegation.rs delete mode 100644 lib-serml/democracy/src/tests/external_proposing.rs delete mode 100644 lib-serml/democracy/src/tests/fast_tracking.rs delete mode 100644 lib-serml/democracy/src/tests/lock_voting.rs delete mode 100644 lib-serml/democracy/src/tests/preimage.rs delete mode 100644 lib-serml/democracy/src/tests/public_proposals.rs delete mode 100644 lib-serml/democracy/src/tests/scheduling.rs delete mode 100644 lib-serml/democracy/src/tests/voting.rs delete mode 100644 lib-serml/democracy/src/types.rs delete mode 100644 lib-serml/democracy/src/vote.rs delete mode 100644 lib-serml/democracy/src/vote_threshold.rs delete mode 100644 lib-serml/democracy/src/weights.rs delete mode 100644 lib-serml/serp/serp-staking/Cargo.toml delete mode 100644 lib-serml/serp/serp-staking/README.md delete mode 100644 lib-serml/serp/serp-staking/reward-curve/Cargo.toml delete mode 100644 lib-serml/serp/serp-staking/reward-curve/src/lib.rs delete mode 100644 lib-serml/serp/serp-staking/reward-curve/src/log.rs delete mode 100644 lib-serml/serp/serp-staking/reward-curve/tests/test.rs delete mode 100644 lib-serml/serp/serp-staking/reward-fn/Cargo.toml delete mode 100644 lib-serml/serp/serp-staking/reward-fn/src/lib.rs delete mode 100644 lib-serml/serp/serp-staking/reward-fn/tests/test.rs delete mode 100644 lib-serml/serp/serp-staking/src/benchmarking.rs delete mode 100644 lib-serml/serp/serp-staking/src/inflation.rs delete mode 100644 lib-serml/serp/serp-staking/src/lib.rs delete mode 100644 lib-serml/serp/serp-staking/src/mock.rs delete mode 100644 lib-serml/serp/serp-staking/src/slashing.rs delete mode 100644 lib-serml/serp/serp-staking/src/testing_utils.rs delete mode 100644 lib-serml/serp/serp-staking/src/tests.rs delete mode 100644 lib-serml/serp/serp-staking/src/weights.rs diff --git a/lib-serml/democracy/Cargo.toml b/lib-serml/democracy/Cargo.toml deleted file mode 100644 index 90946460d..000000000 --- a/lib-serml/democracy/Cargo.toml +++ /dev/null @@ -1,63 +0,0 @@ -[package] -name = "setheum-democracy" -version = "0.8.0" -authors = ["Setheum Labs"] -edition = "2018" - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -# external dependencies -serde = { version = "1.0.101", optional = true, features = ["derive"] } -codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } - -# Substrate dependencies -sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } -sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } -sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } -frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false, optional = true } -frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } -frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } - -# orml dependencies -orml-traits = { path = "../../lib-openrml/traits", default-features = false } -orml-utilities = { path = "../../lib-openrml/utilities", default-features = false } - -# local dependencies -primitives = { package = "setheum-primitives", path = "../../primitives", default-features = false } -support = { package = "setheum-support", path = "../support", default-features = false } - -[dev-dependencies] -orml-tokens = { path = "../../lib-openrml/tokens" } -orml-currencies = { path = "../../lib-openrml/currencies" } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -pallet-scheduler = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -pallet-democracy = { git = "https://github.com/paritytech//substrate", branch = "polkadot-v0.9.8" } -sp-storage = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -substrate-test-utils = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -hex-literal = "0.3.1" - -[features] -default = ["std"] -std = [ - "serde", - "codec/std", - "sp-std/std", - "sp-io/std", - "frame-benchmarking/std", - "frame-support/std", - "sp-runtime/std", - "frame-system/std", - "orml-traits/std", - "orml-utilities/std", - "support/std", - "primitives/std", -] -runtime-benchmarks = [ - "frame-benchmarking", - "frame-system/runtime-benchmarks", - "frame-support/runtime-benchmarks", - "sp-runtime/runtime-benchmarks", -] \ No newline at end of file diff --git a/lib-serml/democracy/README.md b/lib-serml/democracy/README.md deleted file mode 100644 index 6a390cc04..000000000 --- a/lib-serml/democracy/README.md +++ /dev/null @@ -1,135 +0,0 @@ -# Democracy Pallet - -- [`democracy::Trait`](https://docs.rs/pallet-democracy/latest/pallet_democracy/trait.Trait.html) -- [`Call`](https://docs.rs/pallet-democracy/latest/pallet_democracy/enum.Call.html) - -## Overview - -The Democracy pallet handles the administration of general stakeholder voting. - -There are two different queues that a proposal can be added to before it -becomes a referendum, 1) the proposal queue consisting of all public proposals -and 2) the external queue consisting of a single proposal that originates -from one of the _external_ origins (such as a collective group). - -Every launch period - a length defined in the runtime - the Democracy pallet -launches a referendum from a proposal that it takes from either the proposal -queue or the external queue in turn. Any token holder in the system can vote -on referenda. The voting system -uses time-lock voting by allowing the token holder to set their _conviction_ -behind a vote. The conviction will dictate the length of time the tokens -will be locked, as well as the multiplier that scales the vote power. - -### Terminology - -- **Enactment Period:** The minimum period of locking and the period between a proposal being -approved and enacted. -- **Lock Period:** A period of time after proposal enactment that the tokens of _winning_ voters -will be locked. -- **Conviction:** An indication of a voter's strength of belief in their vote. An increase -of one in conviction indicates that a token holder is willing to lock their tokens for twice -as many lock periods after enactment. -- **Vote:** A value that can either be in approval ("Aye") or rejection ("Nay") - of a particular referendum. -- **Proposal:** A submission to the chain that represents an action that a proposer (either an -account or an external origin) suggests that the system adopt. -- **Referendum:** A proposal that is in the process of being voted on for - either acceptance or rejection as a change to the system. -- **Delegation:** The act of granting your voting power to the decisions of another account for - up to a certain conviction. - -### Adaptive Quorum Biasing - -A _referendum_ can be either simple majority-carries in which 50%+1 of the -votes decide the outcome or _adaptive quorum biased_. Adaptive quorum biasing -makes the threshold for passing or rejecting a referendum higher or lower -depending on how the referendum was originally proposed. There are two types of -adaptive quorum biasing: 1) _positive turnout bias_ makes a referendum -require a super-majority to pass that decreases as turnout increases and -2) _negative turnout bias_ makes a referendum require a super-majority to -reject that decreases as turnout increases. Another way to think about the -quorum biasing is that _positive bias_ referendums will be rejected by -default and _negative bias_ referendums get passed by default. - -## Interface - -### Dispatchable Functions - -#### Public - -These calls can be made from any externally held account capable of creating -a signed extrinsic. - -Basic actions: -- `propose` - Submits a sensitive action, represented as a hash. Requires a deposit. -- `second` - Signals agreement with a proposal, moves it higher on the proposal queue, and - requires a matching deposit to the original. -- `vote` - Votes in a referendum, either the vote is "Aye" to enact the proposal or "Nay" to - keep the status quo. -- `unvote` - Cancel a previous vote, this must be done by the voter before the vote ends. -- `delegate` - Delegates the voting power (tokens * conviction) to another account. -- `undelegate` - Stops the delegation of voting power to another account. - -Administration actions that can be done to any account: -- `reap_vote` - Remove some account's expired votes. -- `unlock` - Redetermine the account's balance lock, potentially making tokens available. - -Preimage actions: -- `note_preimage` - Registers the preimage for an upcoming proposal, requires - a deposit that is returned once the proposal is enacted. -- `note_preimage_operational` - same but provided by `T::OperationalPreimageOrigin`. -- `note_imminent_preimage` - Registers the preimage for an upcoming proposal. - Does not require a deposit, but the proposal must be in the dispatch queue. -- `note_imminent_preimage_operational` - same but provided by `T::OperationalPreimageOrigin`. -- `reap_preimage` - Removes the preimage for an expired proposal. Will only - work under the condition that it's the same account that noted it and - after the voting period, OR it's a different account after the enactment period. - -#### Cancellation Origin - -This call can only be made by the `CancellationOrigin`. - -- `emergency_cancel` - Schedules an emergency cancellation of a referendum. - Can only happen once to a specific referendum. - -#### ExternalOrigin - -This call can only be made by the `ExternalOrigin`. - -- `external_propose` - Schedules a proposal to become a referendum once it is is legal - for an externally proposed referendum. - -#### External Majority Origin - -This call can only be made by the `ExternalMajorityOrigin`. - -- `external_propose_majority` - Schedules a proposal to become a majority-carries - referendum once it is legal for an externally proposed referendum. - -#### External Default Origin - -This call can only be made by the `ExternalDefaultOrigin`. - -- `external_propose_default` - Schedules a proposal to become a negative-turnout-bias - referendum once it is legal for an externally proposed referendum. - -#### Fast Track Origin - -This call can only be made by the `FastTrackOrigin`. - -- `fast_track` - Schedules the current externally proposed proposal that - is "majority-carries" to become a referendum immediately. - -#### Veto Origin - -This call can only be made by the `VetoOrigin`. - -- `veto_external` - Vetoes and blacklists the external proposal hash. - -#### Root - -- `cancel_referendum` - Removes a referendum. -- `cancel_queued` - Cancels a proposal that is queued for enactment. -- `clear_public_proposal` - Removes all public proposals. - -License: Apache-2.0 diff --git a/lib-serml/democracy/src/benchmarking.rs b/lib-serml/democracy/src/benchmarking.rs deleted file mode 100644 index ddc3de590..000000000 --- a/lib-serml/democracy/src/benchmarking.rs +++ /dev/null @@ -1,781 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Democracy pallet benchmarking. - -use super::*; - -use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite, whitelist_account}; -use frame_support::{ - assert_noop, assert_ok, - traits::{ - schedule::DispatchTime, Currency, EnsureOrigin, Get, OnInitialize, UnfilteredDispatchable, - }, -}; -use frame_system::{Pallet as System, RawOrigin}; -use sp_runtime::traits::{BadOrigin, Bounded, One}; - -use crate::Pallet as Democracy; - -const SEED: u32 = 0; -const MAX_REFERENDUMS: u32 = 99; -const MAX_SECONDERS: u32 = 100; -const MAX_BYTES: u32 = 16_384; - -fn assert_last_event(generic_event: ::Event) { - frame_system::Pallet::::assert_last_event(generic_event.into()); -} - -fn funded_account(name: &'static str, index: u32) -> T::AccountId { - let caller: T::AccountId = account(name, index, SEED); - T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); - caller -} - -fn add_proposal(n: u32) -> Result { - let other = funded_account::("proposer", n); - let value = T::MinimumDeposit::get(); - let proposal_hash: T::Hash = T::Hashing::hash_of(&n); - - Democracy::::propose(RawOrigin::Signed(other).into(), proposal_hash, value.into())?; - - Ok(proposal_hash) -} - -fn add_referendum(n: u32) -> Result { - let proposal_hash: T::Hash = T::Hashing::hash_of(&n); - let vote_threshold = VoteThreshold::SimpleMajority; - - Democracy::::inject_referendum( - T::LaunchPeriod::get(), - proposal_hash, - vote_threshold, - 0u32.into(), - ); - let referendum_index: ReferendumIndex = ReferendumCount::::get() - 1; - T::Scheduler::schedule_named( - (DEMOCRACY_ID, referendum_index).encode(), - DispatchTime::At(1u32.into()), - None, - 63, - frame_system::RawOrigin::Root.into(), - Call::enact_proposal(proposal_hash, referendum_index).into(), - ) - .map_err(|_| "failed to schedule named")?; - Ok(referendum_index) -} - -fn account_vote(b: BalanceOf) -> AccountVote> { - let v = Vote { aye: true, conviction: Conviction::Locked1x }; - - AccountVote::Standard { vote: v, balance: b } -} - -benchmarks! { - propose { - let p = T::MaxProposals::get(); - - for i in 0 .. (p - 1) { - add_proposal::(i)?; - } - - let caller = funded_account::("caller", 0); - let proposal_hash: T::Hash = T::Hashing::hash_of(&0); - let value = T::MinimumDeposit::get(); - whitelist_account!(caller); - }: _(RawOrigin::Signed(caller), proposal_hash, value.into()) - verify { - assert_eq!(Democracy::::public_props().len(), p as usize, "Proposals not created."); - } - - second { - let s in 0 .. MAX_SECONDERS; - - let caller = funded_account::("caller", 0); - let proposal_hash = add_proposal::(s)?; - - // Create s existing "seconds" - for i in 0 .. s { - let seconder = funded_account::("seconder", i); - Democracy::::second(RawOrigin::Signed(seconder).into(), 0, u32::MAX)?; - } - - let deposits = Democracy::::deposit_of(0).ok_or("Proposal not created")?; - assert_eq!(deposits.0.len(), (s + 1) as usize, "Seconds not recorded"); - whitelist_account!(caller); - }: _(RawOrigin::Signed(caller), 0, u32::MAX) - verify { - let deposits = Democracy::::deposit_of(0).ok_or("Proposal not created")?; - assert_eq!(deposits.0.len(), (s + 2) as usize, "`second` benchmark did not work"); - } - - vote_new { - let r in 1 .. MAX_REFERENDUMS; - - let caller = funded_account::("caller", 0); - let account_vote = account_vote::(100u32.into()); - - // We need to create existing direct votes - for i in 0 .. r { - let ref_idx = add_referendum::(i)?; - Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote.clone())?; - } - let votes = match VotingOf::::get(&caller) { - Voting::Direct { votes, .. } => votes, - _ => return Err("Votes are not direct"), - }; - assert_eq!(votes.len(), r as usize, "Votes were not recorded."); - - let referendum_index = add_referendum::(r)?; - whitelist_account!(caller); - }: vote(RawOrigin::Signed(caller.clone()), referendum_index, account_vote) - verify { - let votes = match VotingOf::::get(&caller) { - Voting::Direct { votes, .. } => votes, - _ => return Err("Votes are not direct"), - }; - assert_eq!(votes.len(), (r + 1) as usize, "Vote was not recorded."); - } - - vote_existing { - let r in 1 .. MAX_REFERENDUMS; - - let caller = funded_account::("caller", 0); - let account_vote = account_vote::(100u32.into()); - - // We need to create existing direct votes - for i in 0 ..=r { - let ref_idx = add_referendum::(i)?; - Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote.clone())?; - } - let votes = match VotingOf::::get(&caller) { - Voting::Direct { votes, .. } => votes, - _ => return Err("Votes are not direct"), - }; - assert_eq!(votes.len(), (r + 1) as usize, "Votes were not recorded."); - - // Change vote from aye to nay - let nay = Vote { aye: false, conviction: Conviction::Locked1x }; - let new_vote = AccountVote::Standard { vote: nay, balance: 1000u32.into() }; - let referendum_index = Democracy::::referendum_count() - 1; - - // This tests when a user changes a vote - whitelist_account!(caller); - }: vote(RawOrigin::Signed(caller.clone()), referendum_index, new_vote) - verify { - let votes = match VotingOf::::get(&caller) { - Voting::Direct { votes, .. } => votes, - _ => return Err("Votes are not direct"), - }; - assert_eq!(votes.len(), (r + 1) as usize, "Vote was incorrectly added"); - let referendum_info = Democracy::::referendum_info(referendum_index) - .ok_or("referendum doesn't exist")?; - let tally = match referendum_info { - ReferendumInfo::Ongoing(r) => r.tally, - _ => return Err("referendum not ongoing"), - }; - assert_eq!(tally.nays, 1000u32.into(), "changed vote was not recorded"); - } - - emergency_cancel { - let origin = T::CancellationOrigin::successful_origin(); - let referendum_index = add_referendum::(0)?; - let call = Call::::emergency_cancel(referendum_index); - assert_ok!(Democracy::::referendum_status(referendum_index)); - }: { call.dispatch_bypass_filter(origin)? } - verify { - // Referendum has been canceled - assert_noop!( - Democracy::::referendum_status(referendum_index), - Error::::ReferendumInvalid, - ); - } - - blacklist { - let p in 1 .. T::MaxProposals::get(); - - // Place our proposal at the end to make sure it's worst case. - for i in 0 .. p - 1 { - add_proposal::(i)?; - } - // We should really add a lot of seconds here, but we're not doing it elsewhere. - - // Place our proposal in the external queue, too. - let hash = T::Hashing::hash_of(&0); - assert_ok!( - Democracy::::external_propose(T::ExternalOrigin::successful_origin(), hash.clone()) - ); - - // Add a referendum of our proposal. - let referendum_index = add_referendum::(0)?; - assert_ok!(Democracy::::referendum_status(referendum_index)); - - let call = Call::::blacklist(hash, Some(referendum_index)); - let origin = T::BlacklistOrigin::successful_origin(); - }: { call.dispatch_bypass_filter(origin)? } - verify { - // Referendum has been canceled - assert_noop!( - Democracy::::referendum_status(referendum_index), - Error::::ReferendumInvalid - ); - } - - // Worst case scenario, we external propose a previously blacklisted proposal - external_propose { - let v in 1 .. MAX_VETOERS as u32; - - let origin = T::ExternalOrigin::successful_origin(); - let proposal_hash = T::Hashing::hash_of(&0); - // Add proposal to blacklist with block number 0 - Blacklist::::insert( - proposal_hash, - (T::BlockNumber::zero(), vec![T::AccountId::default(); v as usize]) - ); - - let call = Call::::external_propose(proposal_hash); - }: { call.dispatch_bypass_filter(origin)? } - verify { - // External proposal created - ensure!(>::exists(), "External proposal didn't work"); - } - - external_propose_majority { - let origin = T::ExternalMajorityOrigin::successful_origin(); - let proposal_hash = T::Hashing::hash_of(&0); - let call = Call::::external_propose_majority(proposal_hash); - }: { call.dispatch_bypass_filter(origin)? } - verify { - // External proposal created - ensure!(>::exists(), "External proposal didn't work"); - } - - external_propose_default { - let origin = T::ExternalDefaultOrigin::successful_origin(); - let proposal_hash = T::Hashing::hash_of(&0); - let call = Call::::external_propose_default(proposal_hash); - }: { call.dispatch_bypass_filter(origin)? } - verify { - // External proposal created - ensure!(>::exists(), "External proposal didn't work"); - } - - fast_track { - let origin_propose = T::ExternalDefaultOrigin::successful_origin(); - let proposal_hash: T::Hash = T::Hashing::hash_of(&0); - Democracy::::external_propose_default(origin_propose, proposal_hash.clone())?; - - // NOTE: Instant origin may invoke a little bit more logic, but may not always succeed. - let origin_fast_track = T::FastTrackOrigin::successful_origin(); - let voting_period = T::FastTrackVotingPeriod::get(); - let delay = 0u32; - let call = Call::::fast_track(proposal_hash, voting_period.into(), delay.into()); - - }: { call.dispatch_bypass_filter(origin_fast_track)? } - verify { - assert_eq!(Democracy::::referendum_count(), 1, "referendum not created") - } - - veto_external { - // Existing veto-ers - let v in 0 .. MAX_VETOERS as u32; - - let proposal_hash: T::Hash = T::Hashing::hash_of(&v); - - let origin_propose = T::ExternalDefaultOrigin::successful_origin(); - Democracy::::external_propose_default(origin_propose, proposal_hash.clone())?; - - let mut vetoers: Vec = Vec::new(); - for i in 0 .. v { - vetoers.push(account("vetoer", i, SEED)); - } - vetoers.sort(); - Blacklist::::insert(proposal_hash, (T::BlockNumber::zero(), vetoers)); - - let call = Call::::veto_external(proposal_hash); - let origin = T::VetoOrigin::successful_origin(); - ensure!(NextExternal::::get().is_some(), "no external proposal"); - }: { call.dispatch_bypass_filter(origin)? } - verify { - assert!(NextExternal::::get().is_none()); - let (_, new_vetoers) = >::get(&proposal_hash).ok_or("no blacklist")?; - assert_eq!(new_vetoers.len(), (v + 1) as usize, "vetoers not added"); - } - - cancel_proposal { - let p in 1 .. T::MaxProposals::get(); - - // Place our proposal at the end to make sure it's worst case. - for i in 0 .. p { - add_proposal::(i)?; - } - }: _(RawOrigin::Root, 0) - - cancel_referendum { - let referendum_index = add_referendum::(0)?; - }: _(RawOrigin::Root, referendum_index) - - cancel_queued { - let r in 1 .. MAX_REFERENDUMS; - - for i in 0..r { - add_referendum::(i)?; // This add one element in the scheduler - } - - let referendum_index = add_referendum::(r)?; - }: _(RawOrigin::Root, referendum_index) - - // This measures the path of `launch_next` external. Not currently used as we simply - // assume the weight is `MaxBlockWeight` when executing. - #[extra] - on_initialize_external { - let r in 0 .. MAX_REFERENDUMS; - - for i in 0..r { - add_referendum::(i)?; - } - - assert_eq!(Democracy::::referendum_count(), r, "referenda not created"); - - // Launch external - LastTabledWasExternal::::put(false); - - let origin = T::ExternalMajorityOrigin::successful_origin(); - let proposal_hash = T::Hashing::hash_of(&r); - let call = Call::::external_propose_majority(proposal_hash); - call.dispatch_bypass_filter(origin)?; - // External proposal created - ensure!(>::exists(), "External proposal didn't work"); - - let block_number = T::LaunchPeriod::get(); - - }: { Democracy::::on_initialize(block_number) } - verify { - // One extra because of next external - assert_eq!(Democracy::::referendum_count(), r + 1, "referenda not created"); - ensure!(!>::exists(), "External wasn't taken"); - - // All but the new next external should be finished - for i in 0 .. r { - if let Some(value) = ReferendumInfoOf::::get(i) { - match value { - ReferendumInfo::Finished { .. } => (), - ReferendumInfo::Ongoing(_) => return Err("Referendum was not finished"), - } - } - } - } - - // This measures the path of `launch_next` public. Not currently used as we simply - // assume the weight is `MaxBlockWeight` when executing. - #[extra] - on_initialize_public { - let r in 1 .. MAX_REFERENDUMS; - - for i in 0..r { - add_referendum::(i)?; - } - - assert_eq!(Democracy::::referendum_count(), r, "referenda not created"); - - // Launch public - assert!(add_proposal::(r).is_ok(), "proposal not created"); - LastTabledWasExternal::::put(true); - - let block_number = T::LaunchPeriod::get(); - - }: { Democracy::::on_initialize(block_number) } - verify { - // One extra because of next public - assert_eq!(Democracy::::referendum_count(), r + 1, "proposal not accepted"); - - // All should be finished - for i in 0 .. r { - if let Some(value) = ReferendumInfoOf::::get(i) { - match value { - ReferendumInfo::Finished { .. } => (), - ReferendumInfo::Ongoing(_) => return Err("Referendum was not finished"), - } - } - } - } - - // No launch no maturing referenda. - on_initialize_base { - let r in 1 .. MAX_REFERENDUMS; - - for i in 0..r { - add_referendum::(i)?; - } - - for (key, mut info) in ReferendumInfoOf::::iter() { - if let ReferendumInfo::Ongoing(ref mut status) = info { - status.end += 100u32.into(); - } - ReferendumInfoOf::::insert(key, info); - } - - assert_eq!(Democracy::::referendum_count(), r, "referenda not created"); - assert_eq!(Democracy::::lowest_unbaked(), 0, "invalid referenda init"); - - }: { Democracy::::on_initialize(0u32.into()) } - verify { - // All should be on going - for i in 0 .. r { - if let Some(value) = ReferendumInfoOf::::get(i) { - match value { - ReferendumInfo::Finished { .. } => return Err("Referendum has been finished"), - ReferendumInfo::Ongoing(_) => (), - } - } - } - } - - delegate { - let r in 1 .. MAX_REFERENDUMS; - - let initial_balance: BalanceOf = 100u32.into(); - let delegated_balance: BalanceOf = 1000u32.into(); - - let caller = funded_account::("caller", 0); - // Caller will initially delegate to `old_delegate` - let old_delegate: T::AccountId = funded_account::("old_delegate", r); - Democracy::::delegate( - RawOrigin::Signed(caller.clone()).into(), - old_delegate.clone(), - Conviction::Locked1x, - delegated_balance, - )?; - let (target, balance) = match VotingOf::::get(&caller) { - Voting::Delegating { target, balance, .. } => (target, balance), - _ => return Err("Votes are not direct"), - }; - assert_eq!(target, old_delegate, "delegation target didn't work"); - assert_eq!(balance, delegated_balance, "delegation balance didn't work"); - // Caller will now switch to `new_delegate` - let new_delegate: T::AccountId = funded_account::("new_delegate", r); - let account_vote = account_vote::(initial_balance); - // We need to create existing direct votes for the `new_delegate` - for i in 0..r { - let ref_idx = add_referendum::(i)?; - Democracy::::vote(RawOrigin::Signed(new_delegate.clone()).into(), ref_idx, account_vote.clone())?; - } - let votes = match VotingOf::::get(&new_delegate) { - Voting::Direct { votes, .. } => votes, - _ => return Err("Votes are not direct"), - }; - assert_eq!(votes.len(), r as usize, "Votes were not recorded."); - whitelist_account!(caller); - }: _(RawOrigin::Signed(caller.clone()), new_delegate.clone(), Conviction::Locked1x, delegated_balance) - verify { - let (target, balance) = match VotingOf::::get(&caller) { - Voting::Delegating { target, balance, .. } => (target, balance), - _ => return Err("Votes are not direct"), - }; - assert_eq!(target, new_delegate, "delegation target didn't work"); - assert_eq!(balance, delegated_balance, "delegation balance didn't work"); - let delegations = match VotingOf::::get(&new_delegate) { - Voting::Direct { delegations, .. } => delegations, - _ => return Err("Votes are not direct"), - }; - assert_eq!(delegations.capital, delegated_balance, "delegation was not recorded."); - } - - undelegate { - let r in 1 .. MAX_REFERENDUMS; - - let initial_balance: BalanceOf = 100u32.into(); - let delegated_balance: BalanceOf = 1000u32.into(); - - let caller = funded_account::("caller", 0); - // Caller will delegate - let the_delegate: T::AccountId = funded_account::("delegate", r); - Democracy::::delegate( - RawOrigin::Signed(caller.clone()).into(), - the_delegate.clone(), - Conviction::Locked1x, - delegated_balance, - )?; - let (target, balance) = match VotingOf::::get(&caller) { - Voting::Delegating { target, balance, .. } => (target, balance), - _ => return Err("Votes are not direct"), - }; - assert_eq!(target, the_delegate, "delegation target didn't work"); - assert_eq!(balance, delegated_balance, "delegation balance didn't work"); - // We need to create votes direct votes for the `delegate` - let account_vote = account_vote::(initial_balance); - for i in 0..r { - let ref_idx = add_referendum::(i)?; - Democracy::::vote( - RawOrigin::Signed(the_delegate.clone()).into(), - ref_idx, - account_vote.clone() - )?; - } - let votes = match VotingOf::::get(&the_delegate) { - Voting::Direct { votes, .. } => votes, - _ => return Err("Votes are not direct"), - }; - assert_eq!(votes.len(), r as usize, "Votes were not recorded."); - whitelist_account!(caller); - }: _(RawOrigin::Signed(caller.clone())) - verify { - // Voting should now be direct - match VotingOf::::get(&caller) { - Voting::Direct { .. } => (), - _ => return Err("undelegation failed"), - } - } - - clear_public_proposals { - add_proposal::(0)?; - - }: _(RawOrigin::Root) - - note_preimage { - // Num of bytes in encoded proposal - let b in 0 .. MAX_BYTES; - - let caller = funded_account::("caller", 0); - let encoded_proposal = vec![1; b as usize]; - whitelist_account!(caller); - }: _(RawOrigin::Signed(caller), encoded_proposal.clone()) - verify { - let proposal_hash = T::Hashing::hash(&encoded_proposal[..]); - match Preimages::::get(proposal_hash) { - Some(PreimageStatus::Available { .. }) => (), - _ => return Err("preimage not available") - } - } - - note_imminent_preimage { - // Num of bytes in encoded proposal - let b in 0 .. MAX_BYTES; - - // d + 1 to include the one we are testing - let encoded_proposal = vec![1; b as usize]; - let proposal_hash = T::Hashing::hash(&encoded_proposal[..]); - let block_number = T::BlockNumber::one(); - Preimages::::insert(&proposal_hash, PreimageStatus::Missing(block_number)); - - let caller = funded_account::("caller", 0); - let encoded_proposal = vec![1; b as usize]; - whitelist_account!(caller); - }: _(RawOrigin::Signed(caller), encoded_proposal.clone()) - verify { - let proposal_hash = T::Hashing::hash(&encoded_proposal[..]); - match Preimages::::get(proposal_hash) { - Some(PreimageStatus::Available { .. }) => (), - _ => return Err("preimage not available") - } - } - - reap_preimage { - // Num of bytes in encoded proposal - let b in 0 .. MAX_BYTES; - - let encoded_proposal = vec![1; b as usize]; - let proposal_hash = T::Hashing::hash(&encoded_proposal[..]); - - let submitter = funded_account::("submitter", b); - Democracy::::note_preimage(RawOrigin::Signed(submitter.clone()).into(), encoded_proposal.clone())?; - - // We need to set this otherwise we get `Early` error. - let block_number = T::VotingPeriod::get() + T::EnactmentPeriod::get() + T::BlockNumber::one(); - System::::set_block_number(block_number.into()); - - assert!(Preimages::::contains_key(proposal_hash)); - - let caller = funded_account::("caller", 0); - whitelist_account!(caller); - }: _(RawOrigin::Signed(caller), proposal_hash.clone(), u32::MAX) - verify { - let proposal_hash = T::Hashing::hash(&encoded_proposal[..]); - assert!(!Preimages::::contains_key(proposal_hash)); - } - - // Test when unlock will remove locks - unlock_remove { - let r in 1 .. MAX_REFERENDUMS; - - let locker = funded_account::("locker", 0); - // Populate votes so things are locked - let base_balance: BalanceOf = 100u32.into(); - let small_vote = account_vote::(base_balance); - // Vote and immediately unvote - for i in 0 .. r { - let ref_idx = add_referendum::(i)?; - Democracy::::vote(RawOrigin::Signed(locker.clone()).into(), ref_idx, small_vote.clone())?; - Democracy::::remove_vote(RawOrigin::Signed(locker.clone()).into(), ref_idx)?; - } - - let caller = funded_account::("caller", 0); - whitelist_account!(caller); - }: unlock(RawOrigin::Signed(caller), locker.clone()) - verify { - // Note that we may want to add a `get_lock` api to actually verify - let voting = VotingOf::::get(&locker); - assert_eq!(voting.locked_balance(), BalanceOf::::zero()); - } - - // Test when unlock will set a new value - unlock_set { - let r in 1 .. MAX_REFERENDUMS; - - let locker = funded_account::("locker", 0); - // Populate votes so things are locked - let base_balance: BalanceOf = 100u32.into(); - let small_vote = account_vote::(base_balance); - for i in 0 .. r { - let ref_idx = add_referendum::(i)?; - Democracy::::vote(RawOrigin::Signed(locker.clone()).into(), ref_idx, small_vote.clone())?; - } - - // Create a big vote so lock increases - let big_vote = account_vote::(base_balance * 10u32.into()); - let referendum_index = add_referendum::(r)?; - Democracy::::vote(RawOrigin::Signed(locker.clone()).into(), referendum_index, big_vote)?; - - let votes = match VotingOf::::get(&locker) { - Voting::Direct { votes, .. } => votes, - _ => return Err("Votes are not direct"), - }; - assert_eq!(votes.len(), (r + 1) as usize, "Votes were not recorded."); - - let voting = VotingOf::::get(&locker); - assert_eq!(voting.locked_balance(), base_balance * 10u32.into()); - - Democracy::::remove_vote(RawOrigin::Signed(locker.clone()).into(), referendum_index)?; - - let caller = funded_account::("caller", 0); - whitelist_account!(caller); - }: unlock(RawOrigin::Signed(caller), locker.clone()) - verify { - let votes = match VotingOf::::get(&locker) { - Voting::Direct { votes, .. } => votes, - _ => return Err("Votes are not direct"), - }; - assert_eq!(votes.len(), r as usize, "Vote was not removed"); - - let voting = VotingOf::::get(&locker); - // Note that we may want to add a `get_lock` api to actually verify - assert_eq!(voting.locked_balance(), base_balance); - } - - remove_vote { - let r in 1 .. MAX_REFERENDUMS; - - let caller = funded_account::("caller", 0); - let account_vote = account_vote::(100u32.into()); - - for i in 0 .. r { - let ref_idx = add_referendum::(i)?; - Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote.clone())?; - } - - let votes = match VotingOf::::get(&caller) { - Voting::Direct { votes, .. } => votes, - _ => return Err("Votes are not direct"), - }; - assert_eq!(votes.len(), r as usize, "Votes not created"); - - let referendum_index = r - 1; - whitelist_account!(caller); - }: _(RawOrigin::Signed(caller.clone()), referendum_index) - verify { - let votes = match VotingOf::::get(&caller) { - Voting::Direct { votes, .. } => votes, - _ => return Err("Votes are not direct"), - }; - assert_eq!(votes.len(), (r - 1) as usize, "Vote was not removed"); - } - - // Worst case is when target == caller and referendum is ongoing - remove_other_vote { - let r in 1 .. MAX_REFERENDUMS; - - let caller = funded_account::("caller", r); - let account_vote = account_vote::(100u32.into()); - - for i in 0 .. r { - let ref_idx = add_referendum::(i)?; - Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote.clone())?; - } - - let votes = match VotingOf::::get(&caller) { - Voting::Direct { votes, .. } => votes, - _ => return Err("Votes are not direct"), - }; - assert_eq!(votes.len(), r as usize, "Votes not created"); - - let referendum_index = r - 1; - whitelist_account!(caller); - }: _(RawOrigin::Signed(caller.clone()), caller.clone(), referendum_index) - verify { - let votes = match VotingOf::::get(&caller) { - Voting::Direct { votes, .. } => votes, - _ => return Err("Votes are not direct"), - }; - assert_eq!(votes.len(), (r - 1) as usize, "Vote was not removed"); - } - - #[extra] - enact_proposal_execute { - // Num of bytes in encoded proposal - let b in 0 .. MAX_BYTES; - - let proposer = funded_account::("proposer", 0); - let raw_call = Call::note_preimage(vec![1; b as usize]); - let generic_call: T::Proposal = raw_call.into(); - let encoded_proposal = generic_call.encode(); - let proposal_hash = T::Hashing::hash(&encoded_proposal[..]); - Democracy::::note_preimage(RawOrigin::Signed(proposer).into(), encoded_proposal)?; - - match Preimages::::get(proposal_hash) { - Some(PreimageStatus::Available { .. }) => (), - _ => return Err("preimage not available") - } - }: enact_proposal(RawOrigin::Root, proposal_hash, 0) - verify { - // Fails due to mismatched origin - assert_last_event::(Event::::Executed(0, Err(BadOrigin.into())).into()); - } - - #[extra] - enact_proposal_slash { - // Num of bytes in encoded proposal - let b in 0 .. MAX_BYTES; - - let proposer = funded_account::("proposer", 0); - // Random invalid bytes - let encoded_proposal = vec![200; b as usize]; - let proposal_hash = T::Hashing::hash(&encoded_proposal[..]); - Democracy::::note_preimage(RawOrigin::Signed(proposer).into(), encoded_proposal)?; - - match Preimages::::get(proposal_hash) { - Some(PreimageStatus::Available { .. }) => (), - _ => return Err("preimage not available") - } - }: { - assert_eq!( - Democracy::::enact_proposal(RawOrigin::Root.into(), proposal_hash, 0), - Err(Error::::PreimageInvalid.into()) - ); - } -} - -impl_benchmark_test_suite!(Democracy, crate::tests::new_test_ext(), crate::tests::Test); diff --git a/lib-serml/democracy/src/conviction.rs b/lib-serml/democracy/src/conviction.rs deleted file mode 100644 index 6b77acfab..000000000 --- a/lib-serml/democracy/src/conviction.rs +++ /dev/null @@ -1,118 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! The conviction datatype. - -use crate::types::Delegations; -use codec::{Decode, Encode}; -use sp_runtime::{ - traits::{Bounded, CheckedDiv, CheckedMul, Zero}, - RuntimeDebug, -}; -use sp_std::{convert::TryFrom, result::Result}; - -/// A value denoting the strength of conviction of a vote. -#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, RuntimeDebug)] -pub enum Conviction { - /// 0.1x votes, unlocked. - None, - /// 1x votes, locked for an enactment period following a successful vote. - Locked1x, - /// 2x votes, locked for 2x enactment periods following a successful vote. - Locked2x, - /// 3x votes, locked for 4x... - Locked3x, - /// 4x votes, locked for 8x... - Locked4x, - /// 5x votes, locked for 16x... - Locked5x, - /// 6x votes, locked for 32x... - Locked6x, -} - -impl Default for Conviction { - fn default() -> Self { - Conviction::None - } -} - -impl From for u8 { - fn from(c: Conviction) -> u8 { - match c { - Conviction::None => 0, - Conviction::Locked1x => 1, - Conviction::Locked2x => 2, - Conviction::Locked3x => 3, - Conviction::Locked4x => 4, - Conviction::Locked5x => 5, - Conviction::Locked6x => 6, - } - } -} - -impl TryFrom for Conviction { - type Error = (); - fn try_from(i: u8) -> Result { - Ok(match i { - 0 => Conviction::None, - 1 => Conviction::Locked1x, - 2 => Conviction::Locked2x, - 3 => Conviction::Locked3x, - 4 => Conviction::Locked4x, - 5 => Conviction::Locked5x, - 6 => Conviction::Locked6x, - _ => return Err(()), - }) - } -} - -impl Conviction { - /// The amount of time (in number of periods) that our conviction implies a successful voter's - /// balance should be locked for. - pub fn lock_periods(self) -> u32 { - match self { - Conviction::None => 0, - Conviction::Locked1x => 1, - Conviction::Locked2x => 2, - Conviction::Locked3x => 4, - Conviction::Locked4x => 8, - Conviction::Locked5x => 16, - Conviction::Locked6x => 32, - } - } - - /// The votes of a voter of the given `balance` with our conviction. - pub fn votes + Zero + Copy + CheckedMul + CheckedDiv + Bounded>( - self, - capital: B, - ) -> Delegations { - let votes = match self { - Conviction::None => capital.checked_div(&10u8.into()).unwrap_or_else(Zero::zero), - x => capital.checked_mul(&u8::from(x).into()).unwrap_or_else(B::max_value), - }; - Delegations { votes, capital } - } -} - -impl Bounded for Conviction { - fn min_value() -> Self { - Conviction::None - } - fn max_value() -> Self { - Conviction::Locked6x - } -} diff --git a/lib-serml/democracy/src/lib.rs b/lib-serml/democracy/src/lib.rs deleted file mode 100644 index 654118537..000000000 --- a/lib-serml/democracy/src/lib.rs +++ /dev/null @@ -1,1939 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! # Democracy Pallet -//! -//! - [`Config`] -//! - [`Call`] -//! -//! ## Overview -//! -//! The Democracy pallet handles the administration of general stakeholder voting. -//! -//! There are two different queues that a proposal can be added to before it -//! becomes a referendum, 1) the proposal queue consisting of all public proposals -//! and 2) the external queue consisting of a single proposal that originates -//! from one of the _external_ origins (such as a collective group). -//! -//! Every launch period - a length defined in the runtime - the Democracy pallet -//! launches a referendum from a proposal that it takes from either the proposal -//! queue or the external queue in turn. Any token holder in the system can vote -//! on referenda. The voting system -//! uses time-lock voting by allowing the token holder to set their _conviction_ -//! behind a vote. The conviction will dictate the length of time the tokens -//! will be locked, as well as the multiplier that scales the vote power. -//! -//! ### Terminology -//! -//! - **Enactment Period:** The minimum period of locking and the period between a proposal being -//! approved and enacted. -//! - **Lock Period:** A period of time after proposal enactment that the tokens of _winning_ voters -//! will be locked. -//! - **Conviction:** An indication of a voter's strength of belief in their vote. An increase -//! of one in conviction indicates that a token holder is willing to lock their tokens for twice -//! as many lock periods after enactment. -//! - **Vote:** A value that can either be in approval ("Aye") or rejection ("Nay") -//! of a particular referendum. -//! - **Proposal:** A submission to the chain that represents an action that a proposer (either an -//! account or an external origin) suggests that the system adopt. -//! - **Referendum:** A proposal that is in the process of being voted on for -//! either acceptance or rejection as a change to the system. -//! - **Delegation:** The act of granting your voting power to the decisions of another account for -//! up to a certain conviction. -//! -//! ### Adaptive Quorum Biasing -//! -//! A _referendum_ can be either simple majority-carries in which 50%+1 of the -//! votes decide the outcome or _adaptive quorum biased_. Adaptive quorum biasing -//! makes the threshold for passing or rejecting a referendum higher or lower -//! depending on how the referendum was originally proposed. There are two types of -//! adaptive quorum biasing: 1) _positive turnout bias_ makes a referendum -//! require a super-majority to pass that decreases as turnout increases and -//! 2) _negative turnout bias_ makes a referendum require a super-majority to -//! reject that decreases as turnout increases. Another way to think about the -//! quorum biasing is that _positive bias_ referendums will be rejected by -//! default and _negative bias_ referendums get passed by default. -//! -//! ## Interface -//! -//! ### Dispatchable Functions -//! -//! #### Public -//! -//! These calls can be made from any externally held account capable of creating -//! a signed extrinsic. -//! -//! Basic actions: -//! - `propose` - Submits a sensitive action, represented as a hash. Requires a deposit. -//! - `second` - Signals agreement with a proposal, moves it higher on the proposal queue, and -//! requires a matching deposit to the original. -//! - `vote` - Votes in a referendum, either the vote is "Aye" to enact the proposal or "Nay" to -//! keep the status quo. -//! - `unvote` - Cancel a previous vote, this must be done by the voter before the vote ends. -//! - `delegate` - Delegates the voting power (tokens * conviction) to another account. -//! - `undelegate` - Stops the delegation of voting power to another account. -//! -//! Administration actions that can be done to any account: -//! - `reap_vote` - Remove some account's expired votes. -//! - `unlock` - Redetermine the account's balance lock, potentially making tokens available. -//! -//! Preimage actions: -//! - `note_preimage` - Registers the preimage for an upcoming proposal, requires -//! a deposit that is returned once the proposal is enacted. -//! - `note_preimage_operational` - same but provided by `T::OperationalPreimageOrigin`. -//! - `note_imminent_preimage` - Registers the preimage for an upcoming proposal. -//! Does not require a deposit, but the proposal must be in the dispatch queue. -//! - `note_imminent_preimage_operational` - same but provided by `T::OperationalPreimageOrigin`. -//! - `reap_preimage` - Removes the preimage for an expired proposal. Will only -//! work under the condition that it's the same account that noted it and -//! after the voting period, OR it's a different account after the enactment period. -//! -//! #### Cancellation Origin -//! -//! This call can only be made by the `CancellationOrigin`. -//! -//! - `emergency_cancel` - Schedules an emergency cancellation of a referendum. -//! Can only happen once to a specific referendum. -//! -//! #### ExternalOrigin -//! -//! This call can only be made by the `ExternalOrigin`. -//! -//! - `external_propose` - Schedules a proposal to become a referendum once it is is legal -//! for an externally proposed referendum. -//! -//! #### External Majority Origin -//! -//! This call can only be made by the `ExternalMajorityOrigin`. -//! -//! - `external_propose_majority` - Schedules a proposal to become a majority-carries -//! referendum once it is legal for an externally proposed referendum. -//! -//! #### External Default Origin -//! -//! This call can only be made by the `ExternalDefaultOrigin`. -//! -//! - `external_propose_default` - Schedules a proposal to become a negative-turnout-bias -//! referendum once it is legal for an externally proposed referendum. -//! -//! #### Fast Track Origin -//! -//! This call can only be made by the `FastTrackOrigin`. -//! -//! - `fast_track` - Schedules the current externally proposed proposal that -//! is "majority-carries" to become a referendum immediately. -//! -//! #### Veto Origin -//! -//! This call can only be made by the `VetoOrigin`. -//! -//! - `veto_external` - Vetoes and blacklists the external proposal hash. -//! -//! #### Root -//! -//! - `cancel_referendum` - Removes a referendum. -//! - `cancel_queued` - Cancels a proposal that is queued for enactment. -//! - `clear_public_proposal` - Removes all public proposals. - -#![recursion_limit = "128"] -#![cfg_attr(not(feature = "std"), no_std)] - -use codec::{Decode, Encode, Input}; -use frame_support::{ - ensure, - traits::{ - schedule::{DispatchTime, Named as ScheduleNamed}, - Get, - }, - weights::Weight, -}; -use sp_runtime::{ - traits::{Bounded, Dispatchable, Hash, Saturating, Zero}, - ArithmeticError, DispatchError, DispatchResult, RuntimeDebug, -}; -use sp_std::prelude::*; -use orml_traits::{ - BalanceStatus, LockIdentifier, MultiCurrency, MultiLockableCurrency, MultiReservableCurrency, -}; -use primitives::{CurrencyId}; -mod conviction; -mod types; -mod vote; -mod vote_threshold; -pub mod weights; -pub use conviction::Conviction; -pub use pallet::*; -pub use types::{Delegations, ReferendumInfo, ReferendumStatus, Tally, UnvoteScope}; -pub use vote::{AccountVote, Vote, Voting}; -pub use vote_threshold::{Approved, VoteThreshold}; -pub use weights::WeightInfo; - -#[cfg(test)] -mod tests; - -#[cfg(feature = "runtime-benchmarks")] -pub mod benchmarking; - -const DEMOCRACY_ID: LockIdentifier = *b"democrac"; - -/// The maximum number of vetoers on a single proposal used to compute Weight. -/// -/// NOTE: This is not enforced by any logic. -pub const MAX_VETOERS: u32 = 100; - -/// A proposal index. -pub type PropIndex = u32; - -/// A referendum index. -pub type ReferendumIndex = u32; - -type BalanceOf = <::Currency as MultiCurrency<::AccountId>>::Balance; -type CurrencyIdOf = - <::Currency as MultiCurrency<::AccountId>>::CurrencyId; - -#[derive(Clone, Encode, Decode, RuntimeDebug)] -pub enum PreimageStatus { - /// The preimage is imminently needed at the argument. - Missing(BlockNumber), - /// The preimage is available. - Available { - data: Vec, - provider: AccountId, - deposit: Balance, - since: BlockNumber, - /// None if it's not imminent. - expiry: Option, - }, -} - -impl PreimageStatus { - fn to_missing_expiry(self) -> Option { - match self { - PreimageStatus::Missing(expiry) => Some(expiry), - _ => None, - } - } -} - -// A value placed in storage that represents the current version of the Democracy storage. -// This value is used by the `on_runtime_upgrade` logic to determine whether we run -// storage migration logic. -#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug)] -enum Releases { - V1, -} - -#[frame_support::pallet] -pub mod pallet { - use super::*; - use frame_support::{ - dispatch::DispatchResultWithPostInfo, - pallet_prelude::*, - traits::EnsureOrigin, - weights::{DispatchClass, Pays}, - Parameter, - }; - use frame_system::{ensure_root, ensure_signed, pallet_prelude::*}; - use sp_runtime::DispatchResult; - - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - pub struct Pallet(_); - - #[pallet::config] - pub trait Config: frame_system::Config + Sized { - type Proposal: Parameter + Dispatchable + From>; - type Event: From> + IsType<::Event>; - - /// Currency type for this pallet. - type Currency: MultiReservableCurrency - + MultiLockableCurrency; - - /// The native currency id - #[pallet::constant] - type GovernanceCurrencyId: Get; - - /// The minimum period of locking and the period between a proposal being approved and enacted. - /// - /// It should generally be a little more than the unstake period to ensure that - /// voting stakers have an opportunity to remove themselves from the system in the case where - /// they are on the losing side of a vote. - #[pallet::constant] - type EnactmentPeriod: Get; - - /// How often (in blocks) new public referenda are launched. - #[pallet::constant] - type LaunchPeriod: Get; - - /// How often (in blocks) to check for new votes. - #[pallet::constant] - type VotingPeriod: Get; - - /// The minimum amount to be used as a deposit for a public referendum proposal. - #[pallet::constant] - type MinimumDeposit: Get>; - - /// Origin from which the next tabled referendum may be forced. This is a normal - /// "super-majority-required" referendum. - type ExternalOrigin: EnsureOrigin; - - /// Origin from which the next tabled referendum may be forced; this allows for the tabling of - /// a majority-carries referendum. - type ExternalMajorityOrigin: EnsureOrigin; - - /// Origin from which the next tabled referendum may be forced; this allows for the tabling of - /// a negative-turnout-bias (default-carries) referendum. - type ExternalDefaultOrigin: EnsureOrigin; - - /// Origin from which the next majority-carries (or more permissive) referendum may be tabled to - /// vote according to the `FastTrackVotingPeriod` asynchronously in a similar manner to the - /// emergency origin. It retains its threshold method. - type FastTrackOrigin: EnsureOrigin; - - /// Origin from which the next majority-carries (or more permissive) referendum may be tabled to - /// vote immediately and asynchronously in a similar manner to the emergency origin. It retains - /// its threshold method. - type InstantOrigin: EnsureOrigin; - - /// Indicator for whether an emergency origin is even allowed to happen. Some chains may want - /// to set this permanently to `false`, others may want to condition it on things such as - /// an upgrade having happened recently. - #[pallet::constant] - type InstantAllowed: Get; - - /// Minimum voting period allowed for a fast-track referendum. - #[pallet::constant] - type FastTrackVotingPeriod: Get; - - /// Origin from which any referendum may be cancelled in an emergency. - type CancellationOrigin: EnsureOrigin; - - /// Origin from which proposals may be blacklisted. - type BlacklistOrigin: EnsureOrigin; - - /// Origin from which a proposal may be cancelled and its backers slashed. - type CancelProposalOrigin: EnsureOrigin; - - /// Origin for anyone able to veto proposals. - /// - /// # Warning - /// - /// The number of Vetoers for a proposal must be small, extrinsics are weighted according to - /// [MAX_VETOERS](./const.MAX_VETOERS.html) - type VetoOrigin: EnsureOrigin; - - /// Period in blocks where an external proposal may not be re-submitted after being vetoed. - #[pallet::constant] - type CooloffPeriod: Get; - - /// The amount of balance that must be deposited per byte of preimage stored. - #[pallet::constant] - type PreimageByteDeposit: Get>; - - /// An origin that can provide a preimage using operational extrinsics. - type OperationalPreimageOrigin: EnsureOrigin; - - /// The Scheduler. - type Scheduler: ScheduleNamed; - - /// Overarching type of all pallets origins. - type PalletsOrigin: From>; - - /// The maximum number of votes for an account. - /// - /// Also used to compute weight, an overly big value can - /// lead to extrinsic with very big weight: see `delegate` for instance. - #[pallet::constant] - type MaxVotes: Get; - - /// Weight information for extrinsics in this pallet. - type WeightInfo: WeightInfo; - - /// The maximum number of public proposals that can exist at any time. - #[pallet::constant] - type MaxProposals: Get; - } - - // TODO: Refactor public proposal queue into its own pallet. - // https://github.com/paritytech/substrate/issues/5322 - /// The number of (public) proposals that have been made so far. - #[pallet::storage] - #[pallet::getter(fn public_prop_count)] - pub type PublicPropCount = StorageValue<_, PropIndex, ValueQuery>; - - /// The public proposals. Unsorted. The second item is the proposal's hash. - #[pallet::storage] - #[pallet::getter(fn public_props)] - pub type PublicProps = - StorageValue<_, Vec<(PropIndex, T::Hash, T::AccountId)>, ValueQuery>; - - /// Those who have locked a deposit. - /// - /// TWOX-NOTE: Safe, as increasing integer keys are safe. - #[pallet::storage] - #[pallet::getter(fn deposit_of)] - pub type DepositOf = - StorageMap<_, Twox64Concat, PropIndex, (Vec, BalanceOf)>; - - /// Map of hashes to the proposal preimage, along with who registered it and their deposit. - /// The block number is the block at which it was deposited. - // TODO: Refactor Preimages into its own pallet. - // https://github.com/paritytech/substrate/issues/5322 - #[pallet::storage] - pub type Preimages = StorageMap< - _, - Identity, - T::Hash, - PreimageStatus, T::BlockNumber>, - >; - - /// The next free referendum index, aka the number of referenda started so far. - #[pallet::storage] - #[pallet::getter(fn referendum_count)] - pub type ReferendumCount = StorageValue<_, ReferendumIndex, ValueQuery>; - - /// The lowest referendum index representing an unbaked referendum. Equal to - /// `ReferendumCount` if there isn't a unbaked referendum. - #[pallet::storage] - #[pallet::getter(fn lowest_unbaked)] - pub type LowestUnbaked = StorageValue<_, ReferendumIndex, ValueQuery>; - - /// Information concerning any given referendum. - /// - /// TWOX-NOTE: SAFE as indexes are not under an attacker’s control. - #[pallet::storage] - #[pallet::getter(fn referendum_info)] - pub type ReferendumInfoOf = StorageMap< - _, - Twox64Concat, - ReferendumIndex, - ReferendumInfo>, - >; - - /// All votes for a particular voter. We store the balance for the number of votes that we - /// have recorded. The second item is the total amount of delegations, that will be added. - /// - /// TWOX-NOTE: SAFE as `AccountId`s are crypto hashes anyway. - #[pallet::storage] - pub type VotingOf = StorageMap< - _, - Twox64Concat, - T::AccountId, - Voting, T::AccountId, T::BlockNumber>, - ValueQuery, - >; - - /// Accounts for which there are locks in action which may be removed at some point in the - /// future. The value is the block number at which the lock expires and may be removed. - /// - /// TWOX-NOTE: OK ― `AccountId` is a secure hash. - #[pallet::storage] - #[pallet::getter(fn locks)] - pub type Locks = StorageMap<_, Twox64Concat, T::AccountId, T::BlockNumber>; - - /// True if the last referendum tabled was submitted externally. False if it was a public - /// proposal. - // TODO: There should be any number of tabling origins, not just public and "external" (council). - // https://github.com/paritytech/substrate/issues/5322 - #[pallet::storage] - pub type LastTabledWasExternal = StorageValue<_, bool, ValueQuery>; - - /// The referendum to be tabled whenever it would be valid to table an external proposal. - /// This happens when a referendum needs to be tabled and one of two conditions are met: - /// - `LastTabledWasExternal` is `false`; or - /// - `PublicProps` is empty. - #[pallet::storage] - pub type NextExternal = StorageValue<_, (T::Hash, VoteThreshold)>; - - /// A record of who vetoed what. Maps proposal hash to a possible existent block number - /// (until when it may not be resubmitted) and who vetoed it. - #[pallet::storage] - pub type Blacklist = - StorageMap<_, Identity, T::Hash, (T::BlockNumber, Vec)>; - - /// Record of all proposals that have been subject to emergency cancellation. - #[pallet::storage] - pub type Cancellations = StorageMap<_, Identity, T::Hash, bool, ValueQuery>; - - /// Storage version of the pallet. - /// - /// New networks start with last version. - #[pallet::storage] - pub(crate) type StorageVersion = StorageValue<_, Releases>; - - #[pallet::genesis_config] - pub struct GenesisConfig { - _phantom: sp_std::marker::PhantomData, - } - - #[cfg(feature = "std")] - impl Default for GenesisConfig { - fn default() -> Self { - GenesisConfig { _phantom: Default::default() } - } - } - - #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { - fn build(&self) { - PublicPropCount::::put(0 as PropIndex); - ReferendumCount::::put(0 as ReferendumIndex); - LowestUnbaked::::put(0 as ReferendumIndex); - StorageVersion::::put(Releases::V1); - } - } - - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - #[pallet::metadata( - T::AccountId = "AccountId", - Vec = "Vec", - BalanceOf = "Balance", - T::BlockNumber = "BlockNumber", - T::Hash = "Hash", - )] - pub enum Event { - /// A motion has been proposed by a public account. \[proposal_index, deposit\] - Proposed(PropIndex, BalanceOf), - /// A public proposal has been tabled for referendum vote. \[proposal_index, deposit, depositors\] - Tabled(PropIndex, BalanceOf, Vec), - /// An external proposal has been tabled. - ExternalTabled, - /// A referendum has begun. \[ref_index, threshold\] - Started(ReferendumIndex, VoteThreshold), - /// A proposal has been approved by referendum. \[ref_index\] - Passed(ReferendumIndex), - /// A proposal has been rejected by referendum. \[ref_index\] - NotPassed(ReferendumIndex), - /// A referendum has been cancelled. \[ref_index\] - Cancelled(ReferendumIndex), - /// A proposal has been enacted. \[ref_index, result\] - Executed(ReferendumIndex, DispatchResult), - /// An account has delegated their vote to another account. \[who, target\] - Delegated(T::AccountId, T::AccountId), - /// An \[account\] has cancelled a previous delegation operation. - Undelegated(T::AccountId), - /// An external proposal has been vetoed. \[who, proposal_hash, until\] - Vetoed(T::AccountId, T::Hash, T::BlockNumber), - /// A proposal's preimage was noted, and the deposit taken. \[proposal_hash, who, deposit\] - PreimageNoted(T::Hash, T::AccountId, BalanceOf), - /// A proposal preimage was removed and used (the deposit was returned). - /// \[proposal_hash, provider, deposit\] - PreimageUsed(T::Hash, T::AccountId, BalanceOf), - /// A proposal could not be executed because its preimage was invalid. - /// \[proposal_hash, ref_index\] - PreimageInvalid(T::Hash, ReferendumIndex), - /// A proposal could not be executed because its preimage was missing. - /// \[proposal_hash, ref_index\] - PreimageMissing(T::Hash, ReferendumIndex), - /// A registered preimage was removed and the deposit collected by the reaper. - /// \[proposal_hash, provider, deposit, reaper\] - PreimageReaped(T::Hash, T::AccountId, BalanceOf, T::AccountId), - /// An \[account\] has been unlocked successfully. - Unlocked(T::AccountId), - /// A proposal \[hash\] has been blacklisted permanently. - Blacklisted(T::Hash), - } - - #[pallet::error] - pub enum Error { - /// Value too low - ValueLow, - /// Proposal does not exist - ProposalMissing, - /// Unknown index - BadIndex, - /// Cannot cancel the same proposal twice - AlreadyCanceled, - /// Proposal already made - DuplicateProposal, - /// Proposal still blacklisted - ProposalBlacklisted, - /// Next external proposal not simple majority - NotSimpleMajority, - /// Invalid hash - InvalidHash, - /// No external proposal - NoProposal, - /// Identity may not veto a proposal twice - AlreadyVetoed, - /// Not delegated - NotDelegated, - /// Preimage already noted - DuplicatePreimage, - /// Not imminent - NotImminent, - /// Too early - TooEarly, - /// Imminent - Imminent, - /// Preimage not found - PreimageMissing, - /// Vote given for invalid referendum - ReferendumInvalid, - /// Invalid preimage - PreimageInvalid, - /// No proposals waiting - NoneWaiting, - /// The target account does not have a lock. - NotLocked, - /// The lock on the account to be unlocked has not yet expired. - NotExpired, - /// The given account did not vote on the referendum. - NotVoter, - /// The actor has no permission to conduct the action. - NoPermission, - /// The account is already delegating. - AlreadyDelegating, - /// Too high a balance was provided that the account cannot afford. - InsufficientFunds, - /// The account is not currently delegating. - NotDelegating, - /// The account currently has votes attached to it and the operation cannot succeed until - /// these are removed, either through `unvote` or `reap_vote`. - VotesExist, - /// The instant referendum origin is currently disallowed. - InstantNotAllowed, - /// Delegation to oneself makes no sense. - Nonsense, - /// Invalid upper bound. - WrongUpperBound, - /// Maximum number of votes reached. - MaxVotesReached, - /// The provided witness data is wrong. - InvalidWitness, - /// Maximum number of proposals reached. - TooManyProposals, - } - - #[pallet::hooks] - impl Hooks> for Pallet { - /// Weight: see `begin_block` - fn on_initialize(n: T::BlockNumber) -> Weight { - Self::begin_block(n).unwrap_or_else(|e| { - sp_runtime::print(e); - 0 - }) - } - } - - #[pallet::call] - impl Pallet { - /// Propose a sensitive action to be taken. - /// - /// The dispatch origin of this call must be _Signed_ and the sender must - /// have funds to cover the deposit. - /// - /// - `proposal_hash`: The hash of the proposal preimage. - /// - `value`: The amount of deposit (must be at least `MinimumDeposit`). - /// - /// Emits `Proposed`. - /// - /// Weight: `O(p)` - #[pallet::weight(T::WeightInfo::propose())] - pub fn propose( - origin: OriginFor, - proposal_hash: T::Hash, - #[pallet::compact] value: BalanceOf, - ) -> DispatchResult { - let who = ensure_signed(origin)?; - ensure!(value >= T::MinimumDeposit::get(), Error::::ValueLow); - - let index = Self::public_prop_count(); - let real_prop_count = PublicProps::::decode_len().unwrap_or(0) as u32; - let max_proposals = T::MaxProposals::get(); - ensure!(real_prop_count < max_proposals, Error::::TooManyProposals); - - if let Some((until, _)) = >::get(proposal_hash) { - ensure!( - >::block_number() >= until, - Error::::ProposalBlacklisted, - ); - } - let currency_id = T::GovernanceCurrencyId::get(); - - T::Currency::reserve(currency_id, &who, value)?; - PublicPropCount::::put(index + 1); - >::insert(index, (&[&who][..], value)); - - >::append((index, proposal_hash, who)); - - Self::deposit_event(Event::::Proposed(index, value)); - Ok(()) - } - - /// Signals agreement with a particular proposal. - /// - /// The dispatch origin of this call must be _Signed_ and the sender - /// must have funds to cover the deposit, equal to the original deposit. - /// - /// - `proposal`: The index of the proposal to second. - /// - `seconds_upper_bound`: an upper bound on the current number of seconds on this - /// proposal. Extrinsic is weighted according to this value with no refund. - /// - /// Weight: `O(S)` where S is the number of seconds a proposal already has. - #[pallet::weight(T::WeightInfo::second(*seconds_upper_bound))] - pub fn second( - origin: OriginFor, - #[pallet::compact] proposal: PropIndex, - #[pallet::compact] seconds_upper_bound: u32, - ) -> DispatchResult { - let who = ensure_signed(origin)?; - - let seconds = - Self::len_of_deposit_of(proposal).ok_or_else(|| Error::::ProposalMissing)?; - ensure!(seconds <= seconds_upper_bound, Error::::WrongUpperBound); - let mut deposit = Self::deposit_of(proposal).ok_or(Error::::ProposalMissing)?; - let currency_id = T::GovernanceCurrencyId::get(); - - T::Currency::reserve(currency_id, &who, deposit.1)?; - deposit.0.push(who); - >::insert(proposal, deposit); - Ok(()) - } - - /// Vote in a referendum. If `vote.is_aye()`, the vote is to enact the proposal; - /// otherwise it is a vote to keep the status quo. - /// - /// The dispatch origin of this call must be _Signed_. - /// - /// - `ref_index`: The index of the referendum to vote for. - /// - `vote`: The vote configuration. - /// - /// Weight: `O(R)` where R is the number of referendums the voter has voted on. - #[pallet::weight( - T::WeightInfo::vote_new(T::MaxVotes::get()) - .max(T::WeightInfo::vote_existing(T::MaxVotes::get())) - )] - pub fn vote( - origin: OriginFor, - #[pallet::compact] ref_index: ReferendumIndex, - vote: AccountVote>, - ) -> DispatchResult { - let who = ensure_signed(origin)?; - Self::try_vote(&who, ref_index, vote) - } - - /// Schedule an emergency cancellation of a referendum. Cannot happen twice to the same - /// referendum. - /// - /// The dispatch origin of this call must be `CancellationOrigin`. - /// - /// -`ref_index`: The index of the referendum to cancel. - /// - /// Weight: `O(1)`. - #[pallet::weight((T::WeightInfo::emergency_cancel(), DispatchClass::Operational))] - pub fn emergency_cancel( - origin: OriginFor, - ref_index: ReferendumIndex, - ) -> DispatchResult { - T::CancellationOrigin::ensure_origin(origin)?; - - let status = Self::referendum_status(ref_index)?; - let h = status.proposal_hash; - ensure!(!>::contains_key(h), Error::::AlreadyCanceled); - - >::insert(h, true); - Self::internal_cancel_referendum(ref_index); - Ok(()) - } - - /// Schedule a referendum to be tabled once it is legal to schedule an external - /// referendum. - /// - /// The dispatch origin of this call must be `ExternalOrigin`. - /// - /// - `proposal_hash`: The preimage hash of the proposal. - /// - /// Weight: `O(V)` with V number of vetoers in the blacklist of proposal. - /// Decoding vec of length V. Charged as maximum - #[pallet::weight(T::WeightInfo::external_propose(MAX_VETOERS))] - pub fn external_propose(origin: OriginFor, proposal_hash: T::Hash) -> DispatchResult { - T::ExternalOrigin::ensure_origin(origin)?; - ensure!(!>::exists(), Error::::DuplicateProposal); - if let Some((until, _)) = >::get(proposal_hash) { - ensure!( - >::block_number() >= until, - Error::::ProposalBlacklisted, - ); - } - >::put((proposal_hash, VoteThreshold::SuperMajorityApprove)); - Ok(()) - } - - /// Schedule a majority-carries referendum to be tabled next once it is legal to schedule - /// an external referendum. - /// - /// The dispatch of this call must be `ExternalMajorityOrigin`. - /// - /// - `proposal_hash`: The preimage hash of the proposal. - /// - /// Unlike `external_propose`, blacklisting has no effect on this and it may replace a - /// pre-scheduled `external_propose` call. - /// - /// Weight: `O(1)` - #[pallet::weight(T::WeightInfo::external_propose_majority())] - pub fn external_propose_majority( - origin: OriginFor, - proposal_hash: T::Hash, - ) -> DispatchResult { - T::ExternalMajorityOrigin::ensure_origin(origin)?; - >::put((proposal_hash, VoteThreshold::SimpleMajority)); - Ok(()) - } - - /// Schedule a negative-turnout-bias referendum to be tabled next once it is legal to - /// schedule an external referendum. - /// - /// The dispatch of this call must be `ExternalDefaultOrigin`. - /// - /// - `proposal_hash`: The preimage hash of the proposal. - /// - /// Unlike `external_propose`, blacklisting has no effect on this and it may replace a - /// pre-scheduled `external_propose` call. - /// - /// Weight: `O(1)` - #[pallet::weight(T::WeightInfo::external_propose_default())] - pub fn external_propose_default( - origin: OriginFor, - proposal_hash: T::Hash, - ) -> DispatchResult { - T::ExternalDefaultOrigin::ensure_origin(origin)?; - >::put((proposal_hash, VoteThreshold::SuperMajorityAgainst)); - Ok(()) - } - - /// Schedule the currently externally-proposed majority-carries referendum to be tabled - /// immediately. If there is no externally-proposed referendum currently, or if there is one - /// but it is not a majority-carries referendum then it fails. - /// - /// The dispatch of this call must be `FastTrackOrigin`. - /// - /// - `proposal_hash`: The hash of the current external proposal. - /// - `voting_period`: The period that is allowed for voting on this proposal. Increased to - /// `FastTrackVotingPeriod` if too low. - /// - `delay`: The number of block after voting has ended in approval and this should be - /// enacted. This doesn't have a minimum amount. - /// - /// Emits `Started`. - /// - /// Weight: `O(1)` - #[pallet::weight(T::WeightInfo::fast_track())] - pub fn fast_track( - origin: OriginFor, - proposal_hash: T::Hash, - voting_period: T::BlockNumber, - delay: T::BlockNumber, - ) -> DispatchResult { - // Rather complicated bit of code to ensure that either: - // - `voting_period` is at least `FastTrackVotingPeriod` and `origin` is `FastTrackOrigin`; or - // - `InstantAllowed` is `true` and `origin` is `InstantOrigin`. - let maybe_ensure_instant = if voting_period < T::FastTrackVotingPeriod::get() { - Some(origin) - } else { - if let Err(origin) = T::FastTrackOrigin::try_origin(origin) { - Some(origin) - } else { - None - } - }; - if let Some(ensure_instant) = maybe_ensure_instant { - T::InstantOrigin::ensure_origin(ensure_instant)?; - ensure!(T::InstantAllowed::get(), Error::::InstantNotAllowed); - } - - let (e_proposal_hash, threshold) = - >::get().ok_or(Error::::ProposalMissing)?; - ensure!( - threshold != VoteThreshold::SuperMajorityApprove, - Error::::NotSimpleMajority, - ); - ensure!(proposal_hash == e_proposal_hash, Error::::InvalidHash); - - >::kill(); - let now = >::block_number(); - Self::inject_referendum(now + voting_period, proposal_hash, threshold, delay); - Ok(()) - } - - /// Veto and blacklist the external proposal hash. - /// - /// The dispatch origin of this call must be `VetoOrigin`. - /// - /// - `proposal_hash`: The preimage hash of the proposal to veto and blacklist. - /// - /// Emits `Vetoed`. - /// - /// Weight: `O(V + log(V))` where V is number of `existing vetoers` - #[pallet::weight(T::WeightInfo::veto_external(MAX_VETOERS))] - pub fn veto_external(origin: OriginFor, proposal_hash: T::Hash) -> DispatchResult { - let who = T::VetoOrigin::ensure_origin(origin)?; - - if let Some((e_proposal_hash, _)) = >::get() { - ensure!(proposal_hash == e_proposal_hash, Error::::ProposalMissing); - } else { - Err(Error::::NoProposal)?; - } - - let mut existing_vetoers = - >::get(&proposal_hash).map(|pair| pair.1).unwrap_or_else(Vec::new); - let insert_position = - existing_vetoers.binary_search(&who).err().ok_or(Error::::AlreadyVetoed)?; - - existing_vetoers.insert(insert_position, who.clone()); - let until = >::block_number() + T::CooloffPeriod::get(); - >::insert(&proposal_hash, (until, existing_vetoers)); - - Self::deposit_event(Event::::Vetoed(who, proposal_hash, until)); - >::kill(); - Ok(()) - } - - /// Remove a referendum. - /// - /// The dispatch origin of this call must be _Root_. - /// - /// - `ref_index`: The index of the referendum to cancel. - /// - /// # Weight: `O(1)`. - #[pallet::weight(T::WeightInfo::cancel_referendum())] - pub fn cancel_referendum( - origin: OriginFor, - #[pallet::compact] ref_index: ReferendumIndex, - ) -> DispatchResult { - ensure_root(origin)?; - Self::internal_cancel_referendum(ref_index); - Ok(()) - } - - /// Cancel a proposal queued for enactment. - /// - /// The dispatch origin of this call must be _Root_. - /// - /// - `which`: The index of the referendum to cancel. - /// - /// Weight: `O(D)` where `D` is the items in the dispatch queue. Weighted as `D = 10`. - #[pallet::weight((T::WeightInfo::cancel_queued(10), DispatchClass::Operational))] - pub fn cancel_queued(origin: OriginFor, which: ReferendumIndex) -> DispatchResult { - ensure_root(origin)?; - T::Scheduler::cancel_named((DEMOCRACY_ID, which).encode()) - .map_err(|_| Error::::ProposalMissing)?; - Ok(()) - } - - /// Delegate the voting power (with some given conviction) of the sending account. - /// - /// The balance delegated is locked for as long as it's delegated, and thereafter for the - /// time appropriate for the conviction's lock period. - /// - /// The dispatch origin of this call must be _Signed_, and the signing account must either: - /// - be delegating already; or - /// - have no voting activity (if there is, then it will need to be removed/consolidated - /// through `reap_vote` or `unvote`). - /// - /// - `to`: The account whose voting the `target` account's voting power will follow. - /// - `conviction`: The conviction that will be attached to the delegated votes. When the - /// account is undelegated, the funds will be locked for the corresponding period. - /// - `balance`: The amount of the account's balance to be used in delegating. This must - /// not be more than the account's current balance. - /// - /// Emits `Delegated`. - /// - /// Weight: `O(R)` where R is the number of referendums the voter delegating to has - /// voted on. Weight is charged as if maximum votes. - // NOTE: weight must cover an incorrect voting of origin with max votes, this is ensure - // because a valid delegation cover decoding a direct voting with max votes. - #[pallet::weight(T::WeightInfo::delegate(T::MaxVotes::get()))] - pub fn delegate( - origin: OriginFor, - to: T::AccountId, - conviction: Conviction, - balance: BalanceOf, - ) -> DispatchResultWithPostInfo { - let who = ensure_signed(origin)?; - let votes = Self::try_delegate(who, to, conviction, balance)?; - - Ok(Some(T::WeightInfo::delegate(votes)).into()) - } - - /// Undelegate the voting power of the sending account. - /// - /// Tokens may be unlocked following once an amount of time consistent with the lock period - /// of the conviction with which the delegation was issued. - /// - /// The dispatch origin of this call must be _Signed_ and the signing account must be - /// currently delegating. - /// - /// Emits `Undelegated`. - /// - /// Weight: `O(R)` where R is the number of referendums the voter delegating to has - /// voted on. Weight is charged as if maximum votes. - // NOTE: weight must cover an incorrect voting of origin with max votes, this is ensure - // because a valid delegation cover decoding a direct voting with max votes. - #[pallet::weight(T::WeightInfo::undelegate(T::MaxVotes::get().into()))] - pub fn undelegate(origin: OriginFor) -> DispatchResultWithPostInfo { - let who = ensure_signed(origin)?; - let votes = Self::try_undelegate(who)?; - Ok(Some(T::WeightInfo::undelegate(votes)).into()) - } - - /// Clears all public proposals. - /// - /// The dispatch origin of this call must be _Root_. - /// - /// Weight: `O(1)`. - #[pallet::weight(T::WeightInfo::clear_public_proposals())] - pub fn clear_public_proposals(origin: OriginFor) -> DispatchResult { - ensure_root(origin)?; - >::kill(); - Ok(()) - } - - /// Register the preimage for an upcoming proposal. This doesn't require the proposal to be - /// in the dispatch queue but does require a deposit, returned once enacted. - /// - /// The dispatch origin of this call must be _Signed_. - /// - /// - `encoded_proposal`: The preimage of a proposal. - /// - /// Emits `PreimageNoted`. - /// - /// Weight: `O(E)` with E size of `encoded_proposal` (protected by a required deposit). - #[pallet::weight(T::WeightInfo::note_preimage(encoded_proposal.len() as u32))] - pub fn note_preimage(origin: OriginFor, encoded_proposal: Vec) -> DispatchResult { - Self::note_preimage_inner(ensure_signed(origin)?, encoded_proposal)?; - Ok(()) - } - - /// Same as `note_preimage` but origin is `OperationalPreimageOrigin`. - #[pallet::weight(( - T::WeightInfo::note_preimage(encoded_proposal.len() as u32), - DispatchClass::Operational, - ))] - pub fn note_preimage_operational( - origin: OriginFor, - encoded_proposal: Vec, - ) -> DispatchResult { - let who = T::OperationalPreimageOrigin::ensure_origin(origin)?; - Self::note_preimage_inner(who, encoded_proposal)?; - Ok(()) - } - - /// Register the preimage for an upcoming proposal. This requires the proposal to be - /// in the dispatch queue. No deposit is needed. When this call is successful, i.e. - /// the preimage has not been uploaded before and matches some imminent proposal, - /// no fee is paid. - /// - /// The dispatch origin of this call must be _Signed_. - /// - /// - `encoded_proposal`: The preimage of a proposal. - /// - /// Emits `PreimageNoted`. - /// - /// Weight: `O(E)` with E size of `encoded_proposal` (protected by a required deposit). - #[pallet::weight(T::WeightInfo::note_imminent_preimage(encoded_proposal.len() as u32))] - pub fn note_imminent_preimage( - origin: OriginFor, - encoded_proposal: Vec, - ) -> DispatchResultWithPostInfo { - Self::note_imminent_preimage_inner(ensure_signed(origin)?, encoded_proposal)?; - // We check that this preimage was not uploaded before in `note_imminent_preimage_inner`, - // thus this call can only be successful once. If successful, user does not pay a fee. - Ok(Pays::No.into()) - } - - /// Same as `note_imminent_preimage` but origin is `OperationalPreimageOrigin`. - #[pallet::weight(( - T::WeightInfo::note_imminent_preimage(encoded_proposal.len() as u32), - DispatchClass::Operational, - ))] - pub fn note_imminent_preimage_operational( - origin: OriginFor, - encoded_proposal: Vec, - ) -> DispatchResultWithPostInfo { - let who = T::OperationalPreimageOrigin::ensure_origin(origin)?; - Self::note_imminent_preimage_inner(who, encoded_proposal)?; - // We check that this preimage was not uploaded before in `note_imminent_preimage_inner`, - // thus this call can only be successful once. If successful, user does not pay a fee. - Ok(Pays::No.into()) - } - - /// Remove an expired proposal preimage and collect the deposit. - /// - /// The dispatch origin of this call must be _Signed_. - /// - /// - `proposal_hash`: The preimage hash of a proposal. - /// - `proposal_length_upper_bound`: an upper bound on length of the proposal. - /// Extrinsic is weighted according to this value with no refund. - /// - /// This will only work after `VotingPeriod` blocks from the time that the preimage was - /// noted, if it's the same account doing it. If it's a different account, then it'll only - /// work an additional `EnactmentPeriod` later. - /// - /// Emits `PreimageReaped`. - /// - /// Weight: `O(D)` where D is length of proposal. - #[pallet::weight(T::WeightInfo::reap_preimage(*proposal_len_upper_bound))] - pub fn reap_preimage( - origin: OriginFor, - proposal_hash: T::Hash, - #[pallet::compact] proposal_len_upper_bound: u32, - ) -> DispatchResult { - let who = ensure_signed(origin)?; - - ensure!( - Self::pre_image_data_len(proposal_hash)? <= proposal_len_upper_bound, - Error::::WrongUpperBound, - ); - - let (provider, deposit, since, expiry) = >::get(&proposal_hash) - .and_then(|m| match m { - PreimageStatus::Available { provider, deposit, since, expiry, .. } => - Some((provider, deposit, since, expiry)), - _ => None, - }) - .ok_or(Error::::PreimageMissing)?; - - let now = >::block_number(); - let (voting, enactment) = (T::VotingPeriod::get(), T::EnactmentPeriod::get()); - let additional = if who == provider { Zero::zero() } else { enactment }; - ensure!(now >= since + voting + additional, Error::::TooEarly); - ensure!(expiry.map_or(true, |e| now > e), Error::::Imminent); - - let currency_id = T::GovernanceCurrencyId::get(); - - let res = - T::Currency::repatriate_reserved(currency_id, &provider, &who, deposit, BalanceStatus::Free); - debug_assert!(res.is_ok()); - >::remove(&proposal_hash); - Self::deposit_event(Event::::PreimageReaped(proposal_hash, provider, deposit, who)); - Ok(()) - } - - /// Unlock tokens that have an expired lock. - /// - /// The dispatch origin of this call must be _Signed_. - /// - /// - `target`: The account to remove the lock on. - /// - /// Weight: `O(R)` with R number of vote of target. - #[pallet::weight( - T::WeightInfo::unlock_set(T::MaxVotes::get()) - .max(T::WeightInfo::unlock_remove(T::MaxVotes::get())) - )] - pub fn unlock(origin: OriginFor, target: T::AccountId) -> DispatchResult { - ensure_signed(origin)?; - Self::update_lock(&target); - Ok(()) - } - - /// Remove a vote for a referendum. - /// - /// If: - /// - the referendum was cancelled, or - /// - the referendum is ongoing, or - /// - the referendum has ended such that - /// - the vote of the account was in opposition to the result; or - /// - there was no conviction to the account's vote; or - /// - the account made a split vote - /// ...then the vote is removed cleanly and a following call to `unlock` may result in more - /// funds being available. - /// - /// If, however, the referendum has ended and: - /// - it finished corresponding to the vote of the account, and - /// - the account made a standard vote with conviction, and - /// - the lock period of the conviction is not over - /// ...then the lock will be aggregated into the overall account's lock, which may involve - /// *overlocking* (where the two locks are combined into a single lock that is the maximum - /// of both the amount locked and the time is it locked for). - /// - /// The dispatch origin of this call must be _Signed_, and the signer must have a vote - /// registered for referendum `index`. - /// - /// - `index`: The index of referendum of the vote to be removed. - /// - /// Weight: `O(R + log R)` where R is the number of referenda that `target` has voted on. - /// Weight is calculated for the maximum number of vote. - #[pallet::weight(T::WeightInfo::remove_vote(T::MaxVotes::get()))] - pub fn remove_vote(origin: OriginFor, index: ReferendumIndex) -> DispatchResult { - let who = ensure_signed(origin)?; - Self::try_remove_vote(&who, index, UnvoteScope::Any) - } - - /// Remove a vote for a referendum. - /// - /// If the `target` is equal to the signer, then this function is exactly equivalent to - /// `remove_vote`. If not equal to the signer, then the vote must have expired, - /// either because the referendum was cancelled, because the voter lost the referendum or - /// because the conviction period is over. - /// - /// The dispatch origin of this call must be _Signed_. - /// - /// - `target`: The account of the vote to be removed; this account must have voted for - /// referendum `index`. - /// - `index`: The index of referendum of the vote to be removed. - /// - /// Weight: `O(R + log R)` where R is the number of referenda that `target` has voted on. - /// Weight is calculated for the maximum number of vote. - #[pallet::weight(T::WeightInfo::remove_other_vote(T::MaxVotes::get()))] - pub fn remove_other_vote( - origin: OriginFor, - target: T::AccountId, - index: ReferendumIndex, - ) -> DispatchResult { - let who = ensure_signed(origin)?; - let scope = if target == who { UnvoteScope::Any } else { UnvoteScope::OnlyExpired }; - Self::try_remove_vote(&target, index, scope)?; - Ok(()) - } - - /// Enact a proposal from a referendum. For now we just make the weight be the maximum. - #[pallet::weight(T::BlockWeights::get().max_block)] - pub fn enact_proposal( - origin: OriginFor, - proposal_hash: T::Hash, - index: ReferendumIndex, - ) -> DispatchResult { - ensure_root(origin)?; - Self::do_enact_proposal(proposal_hash, index) - } - - /// Permanently place a proposal into the blacklist. This prevents it from ever being - /// proposed again. - /// - /// If called on a queued public or external proposal, then this will result in it being - /// removed. If the `ref_index` supplied is an active referendum with the proposal hash, - /// then it will be cancelled. - /// - /// The dispatch origin of this call must be `BlacklistOrigin`. - /// - /// - `proposal_hash`: The proposal hash to blacklist permanently. - /// - `ref_index`: An ongoing referendum whose hash is `proposal_hash`, which will be - /// cancelled. - /// - /// Weight: `O(p)` (though as this is an high-privilege dispatch, we assume it has a - /// reasonable value). - #[pallet::weight((T::WeightInfo::blacklist(T::MaxProposals::get()), DispatchClass::Operational))] - pub fn blacklist( - origin: OriginFor, - proposal_hash: T::Hash, - maybe_ref_index: Option, - ) -> DispatchResult { - T::BlacklistOrigin::ensure_origin(origin)?; - - // Insert the proposal into the blacklist. - let permanent = (T::BlockNumber::max_value(), Vec::::new()); - Blacklist::::insert(&proposal_hash, permanent); - - // Remove the queued proposal, if it's there. - PublicProps::::mutate(|props| { - if let Some(index) = props.iter().position(|p| p.1 == proposal_hash) { - let (prop_index, ..) = props.remove(index); - if let Some((whos, amount)) = DepositOf::::take(prop_index) { - for who in whos.into_iter() { - - let currency_id = T::GovernanceCurrencyId::get(); - - T::Currency::slash_reserved(currency_id, &who, amount); - } - } - } - }); - - // Remove the external queued referendum, if it's there. - if matches!(NextExternal::::get(), Some((h, ..)) if h == proposal_hash) { - NextExternal::::kill(); - } - - // Remove the referendum, if it's there. - if let Some(ref_index) = maybe_ref_index { - if let Ok(status) = Self::referendum_status(ref_index) { - if status.proposal_hash == proposal_hash { - Self::internal_cancel_referendum(ref_index); - } - } - } - - Self::deposit_event(Event::::Blacklisted(proposal_hash)); - Ok(()) - } - - /// Remove a proposal. - /// - /// The dispatch origin of this call must be `CancelProposalOrigin`. - /// - /// - `prop_index`: The index of the proposal to cancel. - /// - /// Weight: `O(p)` where `p = PublicProps::::decode_len()` - #[pallet::weight(T::WeightInfo::cancel_proposal(T::MaxProposals::get()))] - pub fn cancel_proposal( - origin: OriginFor, - #[pallet::compact] prop_index: PropIndex, - ) -> DispatchResult { - T::CancelProposalOrigin::ensure_origin(origin)?; - - PublicProps::::mutate(|props| props.retain(|p| p.0 != prop_index)); - if let Some((whos, amount)) = DepositOf::::take(prop_index) { - for who in whos.into_iter() { - - let currency_id = T::GovernanceCurrencyId::get(); - - T::Currency::slash_reserved(currency_id, &who, amount); - } - } - - Ok(()) - } - } -} - -impl Pallet { - // exposed immutables. - - /// Get the amount locked in support of `proposal`; `None` if proposal isn't a valid proposal - /// index. - pub fn backing_for(proposal: PropIndex) -> Option> { - Self::deposit_of(proposal).map(|(l, d)| d * (l.len() as u32).into()) - } - - /// Get all referenda ready for tally at block `n`. - pub fn maturing_referenda_at( - n: T::BlockNumber, - ) -> Vec<(ReferendumIndex, ReferendumStatus>)> { - let next = Self::lowest_unbaked(); - let last = Self::referendum_count(); - Self::maturing_referenda_at_inner(n, next..last) - } - - fn maturing_referenda_at_inner( - n: T::BlockNumber, - range: core::ops::Range, - ) -> Vec<(ReferendumIndex, ReferendumStatus>)> { - range - .into_iter() - .map(|i| (i, Self::referendum_info(i))) - .filter_map(|(i, maybe_info)| match maybe_info { - Some(ReferendumInfo::Ongoing(status)) => Some((i, status)), - _ => None, - }) - .filter(|(_, status)| status.end == n) - .collect() - } - - // Exposed mutables. - - /// Start a referendum. - pub fn internal_start_referendum( - proposal_hash: T::Hash, - threshold: VoteThreshold, - delay: T::BlockNumber, - ) -> ReferendumIndex { - >::inject_referendum( - >::block_number() + T::VotingPeriod::get(), - proposal_hash, - threshold, - delay, - ) - } - - /// Remove a referendum. - pub fn internal_cancel_referendum(ref_index: ReferendumIndex) { - Self::deposit_event(Event::::Cancelled(ref_index)); - ReferendumInfoOf::::remove(ref_index); - } - - // private. - - /// Ok if the given referendum is active, Err otherwise - fn ensure_ongoing( - r: ReferendumInfo>, - ) -> Result>, DispatchError> { - match r { - ReferendumInfo::Ongoing(s) => Ok(s), - _ => Err(Error::::ReferendumInvalid.into()), - } - } - - fn referendum_status( - ref_index: ReferendumIndex, - ) -> Result>, DispatchError> { - let info = ReferendumInfoOf::::get(ref_index).ok_or(Error::::ReferendumInvalid)?; - Self::ensure_ongoing(info) - } - - /// Actually enact a vote, if legit. - fn try_vote( - who: &T::AccountId, - ref_index: ReferendumIndex, - vote: AccountVote>, - ) -> DispatchResult { - let mut status = Self::referendum_status(ref_index)?; - let currency_id = T::GovernanceCurrencyId::get(); - - ensure!(vote.balance() <= T::Currency::free_balance(currency_id, who), Error::::InsufficientFunds); - VotingOf::::try_mutate(who, |voting| -> DispatchResult { - if let Voting::Direct { ref mut votes, delegations, .. } = voting { - match votes.binary_search_by_key(&ref_index, |i| i.0) { - Ok(i) => { - // Shouldn't be possible to fail, but we handle it gracefully. - status.tally.remove(votes[i].1).ok_or(ArithmeticError::Underflow)?; - if let Some(approve) = votes[i].1.as_standard() { - status.tally.reduce(approve, *delegations); - } - votes[i].1 = vote; - }, - Err(i) => { - ensure!( - votes.len() as u32 <= T::MaxVotes::get(), - Error::::MaxVotesReached - ); - votes.insert(i, (ref_index, vote)); - }, - } - // Shouldn't be possible to fail, but we handle it gracefully. - status.tally.add(vote).ok_or(ArithmeticError::Overflow)?; - if let Some(approve) = vote.as_standard() { - status.tally.increase(approve, *delegations); - } - Ok(()) - } else { - Err(Error::::AlreadyDelegating.into()) - } - })?; - // Extend the lock to `balance` (rather than setting it) since we don't know what other - // votes are in place. - let currency_id = T::GovernanceCurrencyId::get(); - - T::Currency::extend_lock(DEMOCRACY_ID, currency_id, who, vote.balance()); - ReferendumInfoOf::::insert(ref_index, ReferendumInfo::Ongoing(status)); - Ok(()) - } - - /// Remove the account's vote for the given referendum if possible. This is possible when: - /// - The referendum has not finished. - /// - The referendum has finished and the voter lost their direction. - /// - The referendum has finished and the voter's lock period is up. - /// - /// This will generally be combined with a call to `unlock`. - fn try_remove_vote( - who: &T::AccountId, - ref_index: ReferendumIndex, - scope: UnvoteScope, - ) -> DispatchResult { - let info = ReferendumInfoOf::::get(ref_index); - VotingOf::::try_mutate(who, |voting| -> DispatchResult { - if let Voting::Direct { ref mut votes, delegations, ref mut prior } = voting { - let i = votes - .binary_search_by_key(&ref_index, |i| i.0) - .map_err(|_| Error::::NotVoter)?; - match info { - Some(ReferendumInfo::Ongoing(mut status)) => { - ensure!(matches!(scope, UnvoteScope::Any), Error::::NoPermission); - // Shouldn't be possible to fail, but we handle it gracefully. - status.tally.remove(votes[i].1).ok_or(ArithmeticError::Underflow)?; - if let Some(approve) = votes[i].1.as_standard() { - status.tally.reduce(approve, *delegations); - } - ReferendumInfoOf::::insert(ref_index, ReferendumInfo::Ongoing(status)); - }, - Some(ReferendumInfo::Finished { end, approved }) => - if let Some((lock_periods, balance)) = votes[i].1.locked_if(approved) { - let unlock_at = end + T::EnactmentPeriod::get() * lock_periods.into(); - let now = frame_system::Pallet::::block_number(); - if now < unlock_at { - ensure!( - matches!(scope, UnvoteScope::Any), - Error::::NoPermission - ); - prior.accumulate(unlock_at, balance) - } - }, - None => {}, // Referendum was cancelled. - } - votes.remove(i); - } - Ok(()) - })?; - Ok(()) - } - - /// Return the number of votes for `who` - fn increase_upstream_delegation(who: &T::AccountId, amount: Delegations>) -> u32 { - VotingOf::::mutate(who, |voting| match voting { - Voting::Delegating { delegations, .. } => { - // We don't support second level delegating, so we don't need to do anything more. - *delegations = delegations.saturating_add(amount); - 1 - }, - Voting::Direct { votes, delegations, .. } => { - *delegations = delegations.saturating_add(amount); - for &(ref_index, account_vote) in votes.iter() { - if let AccountVote::Standard { vote, .. } = account_vote { - ReferendumInfoOf::::mutate(ref_index, |maybe_info| { - if let Some(ReferendumInfo::Ongoing(ref mut status)) = maybe_info { - status.tally.increase(vote.aye, amount); - } - }); - } - } - votes.len() as u32 - }, - }) - } - - /// Return the number of votes for `who` - fn reduce_upstream_delegation(who: &T::AccountId, amount: Delegations>) -> u32 { - VotingOf::::mutate(who, |voting| match voting { - Voting::Delegating { delegations, .. } => { - // We don't support second level delegating, so we don't need to do anything more. - *delegations = delegations.saturating_sub(amount); - 1 - }, - Voting::Direct { votes, delegations, .. } => { - *delegations = delegations.saturating_sub(amount); - for &(ref_index, account_vote) in votes.iter() { - if let AccountVote::Standard { vote, .. } = account_vote { - ReferendumInfoOf::::mutate(ref_index, |maybe_info| { - if let Some(ReferendumInfo::Ongoing(ref mut status)) = maybe_info { - status.tally.reduce(vote.aye, amount); - } - }); - } - } - votes.len() as u32 - }, - }) - } - - /// Attempt to delegate `balance` times `conviction` of voting power from `who` to `target`. - /// - /// Return the upstream number of votes. - fn try_delegate( - who: T::AccountId, - target: T::AccountId, - conviction: Conviction, - balance: BalanceOf, - ) -> Result { - ensure!(who != target, Error::::Nonsense); - let currency_id = T::GovernanceCurrencyId::get(); - - ensure!(balance <= T::Currency::free_balance(currency_id, &who), Error::::InsufficientFunds); - let votes = VotingOf::::try_mutate(&who, |voting| -> Result { - let mut old = Voting::Delegating { - balance, - target: target.clone(), - conviction, - delegations: Default::default(), - prior: Default::default(), - }; - sp_std::mem::swap(&mut old, voting); - match old { - Voting::Delegating { balance, target, conviction, delegations, prior, .. } => { - // remove any delegation votes to our current target. - Self::reduce_upstream_delegation(&target, conviction.votes(balance)); - voting.set_common(delegations, prior); - }, - Voting::Direct { votes, delegations, prior } => { - // here we just ensure that we're currently idling with no votes recorded. - ensure!(votes.is_empty(), Error::::VotesExist); - voting.set_common(delegations, prior); - }, - } - let votes = Self::increase_upstream_delegation(&target, conviction.votes(balance)); - // Extend the lock to `balance` (rather than setting it) since we don't know what other - // votes are in place. - let currency_id = T::GovernanceCurrencyId::get(); - - T::Currency::extend_lock(DEMOCRACY_ID, currency_id, &who, balance); - Ok(votes) - })?; - Self::deposit_event(Event::::Delegated(who, target)); - Ok(votes) - } - - /// Attempt to end the current delegation. - /// - /// Return the number of votes of upstream. - fn try_undelegate(who: T::AccountId) -> Result { - let votes = VotingOf::::try_mutate(&who, |voting| -> Result { - let mut old = Voting::default(); - sp_std::mem::swap(&mut old, voting); - match old { - Voting::Delegating { balance, target, conviction, delegations, mut prior } => { - // remove any delegation votes to our current target. - let votes = - Self::reduce_upstream_delegation(&target, conviction.votes(balance)); - let now = frame_system::Pallet::::block_number(); - let lock_periods = conviction.lock_periods().into(); - prior.accumulate(now + T::EnactmentPeriod::get() * lock_periods, balance); - voting.set_common(delegations, prior); - - Ok(votes) - }, - Voting::Direct { .. } => Err(Error::::NotDelegating.into()), - } - })?; - Self::deposit_event(Event::::Undelegated(who)); - Ok(votes) - } - - /// Rejig the lock on an account. It will never get more stringent (since that would indicate - /// a security hole) but may be reduced from what they are currently. - fn update_lock(who: &T::AccountId) { - let lock_needed = VotingOf::::mutate(who, |voting| { - voting.rejig(frame_system::Pallet::::block_number()); - voting.locked_balance() - }); - let currency_id = T::GovernanceCurrencyId::get(); - - if lock_needed.is_zero() { - T::Currency::remove_lock(DEMOCRACY_ID, currency_id, who); - } else { - T::Currency::set_lock(DEMOCRACY_ID, currency_id, who, lock_needed); - } - } - - /// Start a referendum - fn inject_referendum( - end: T::BlockNumber, - proposal_hash: T::Hash, - threshold: VoteThreshold, - delay: T::BlockNumber, - ) -> ReferendumIndex { - let ref_index = Self::referendum_count(); - ReferendumCount::::put(ref_index + 1); - let status = - ReferendumStatus { end, proposal_hash, threshold, delay, tally: Default::default() }; - let item = ReferendumInfo::Ongoing(status); - >::insert(ref_index, item); - Self::deposit_event(Event::::Started(ref_index, threshold)); - ref_index - } - - /// Table the next waiting proposal for a vote. - fn launch_next(now: T::BlockNumber) -> DispatchResult { - if LastTabledWasExternal::::take() { - Self::launch_public(now).or_else(|_| Self::launch_external(now)) - } else { - Self::launch_external(now).or_else(|_| Self::launch_public(now)) - } - .map_err(|_| Error::::NoneWaiting.into()) - } - - /// Table the waiting external proposal for a vote, if there is one. - fn launch_external(now: T::BlockNumber) -> DispatchResult { - if let Some((proposal, threshold)) = >::take() { - LastTabledWasExternal::::put(true); - Self::deposit_event(Event::::ExternalTabled); - Self::inject_referendum( - now + T::VotingPeriod::get(), - proposal, - threshold, - T::EnactmentPeriod::get(), - ); - Ok(()) - } else { - Err(Error::::NoneWaiting)? - } - } - - /// Table the waiting public proposal with the highest backing for a vote. - fn launch_public(now: T::BlockNumber) -> DispatchResult { - let mut public_props = Self::public_props(); - if let Some((winner_index, _)) = public_props.iter() - .enumerate() - .max_by_key(|x| Self::backing_for((x.1).0).unwrap_or_else(Zero::zero) - /* ^^ defensive only: All current public proposals have an amount locked*/) - { - let (prop_index, proposal, _) = public_props.swap_remove(winner_index); - >::put(public_props); - - if let Some((depositors, deposit)) = >::take(prop_index) { - // refund depositors - for d in &depositors { - let currency_id = T::GovernanceCurrencyId::get(); - - T::Currency::unreserve(currency_id, d, deposit); - } - Self::deposit_event(Event::::Tabled(prop_index, deposit, depositors)); - Self::inject_referendum( - now + T::VotingPeriod::get(), - proposal, - VoteThreshold::SuperMajorityApprove, - T::EnactmentPeriod::get(), - ); - } - Ok(()) - } else { - Err(Error::::NoneWaiting)? - } - } - - fn do_enact_proposal(proposal_hash: T::Hash, index: ReferendumIndex) -> DispatchResult { - let preimage = >::take(&proposal_hash); - if let Some(PreimageStatus::Available { data, provider, deposit, .. }) = preimage { - if let Ok(proposal) = T::Proposal::decode(&mut &data[..]) { - let currency_id = T::GovernanceCurrencyId::get(); - - let err_amount = T::Currency::unreserve(currency_id, &provider, deposit); - debug_assert!(err_amount.is_zero()); - Self::deposit_event(Event::::PreimageUsed(proposal_hash, provider, deposit)); - - let res = proposal - .dispatch(frame_system::RawOrigin::Root.into()) - .map(|_| ()) - .map_err(|e| e.error); - Self::deposit_event(Event::::Executed(index, res)); - - Ok(()) - } else { - let currency_id = T::GovernanceCurrencyId::get(); - - T::Currency::slash_reserved(currency_id, &provider, deposit); - Self::deposit_event(Event::::PreimageInvalid(proposal_hash, index)); - Err(Error::::PreimageInvalid.into()) - } - } else { - Self::deposit_event(Event::::PreimageMissing(proposal_hash, index)); - Err(Error::::PreimageMissing.into()) - } - } - - fn bake_referendum( - now: T::BlockNumber, - index: ReferendumIndex, - status: ReferendumStatus>, - ) -> Result { - let currency_id = T::GovernanceCurrencyId::get(); - - let total_issuance = T::Currency::total_issuance(currency_id); - let approved = status.threshold.approved(status.tally, total_issuance); - - if approved { - Self::deposit_event(Event::::Passed(index)); - if status.delay.is_zero() { - let _ = Self::do_enact_proposal(status.proposal_hash, index); - } else { - let when = now + status.delay; - // Note that we need the preimage now. - Preimages::::mutate_exists( - &status.proposal_hash, - |maybe_pre| match *maybe_pre { - Some(PreimageStatus::Available { ref mut expiry, .. }) => - *expiry = Some(when), - ref mut a => *a = Some(PreimageStatus::Missing(when)), - }, - ); - - if T::Scheduler::schedule_named( - (DEMOCRACY_ID, index).encode(), - DispatchTime::At(when), - None, - 63, - frame_system::RawOrigin::Root.into(), - Call::enact_proposal(status.proposal_hash, index).into(), - ) - .is_err() - { - frame_support::print("LOGIC ERROR: bake_referendum/schedule_named failed"); - } - } - } else { - Self::deposit_event(Event::::NotPassed(index)); - } - - Ok(approved) - } - - /// Current era is ending; we should finish up any proposals. - /// - /// - /// # - /// If a referendum is launched or maturing, this will take full block weight. Otherwise: - /// - Complexity: `O(R)` where `R` is the number of unbaked referenda. - /// - Db reads: `LastTabledWasExternal`, `NextExternal`, `PublicProps`, `account`, - /// `ReferendumCount`, `LowestUnbaked` - /// - Db writes: `PublicProps`, `account`, `ReferendumCount`, `DepositOf`, `ReferendumInfoOf` - /// - Db reads per R: `DepositOf`, `ReferendumInfoOf` - /// # - fn begin_block(now: T::BlockNumber) -> Result { - let max_block_weight = T::BlockWeights::get().max_block; - let mut weight = 0; - - // pick out another public referendum if it's time. - if (now % T::LaunchPeriod::get()).is_zero() { - // Errors come from the queue being empty. we don't really care about that, and even if - // we did, there is nothing we can do here. - let _ = Self::launch_next(now); - weight = max_block_weight; - } - - let next = Self::lowest_unbaked(); - let last = Self::referendum_count(); - let r = last.saturating_sub(next); - weight = weight.saturating_add(T::WeightInfo::on_initialize_base(r)); - // tally up votes for any expiring referenda. - for (index, info) in Self::maturing_referenda_at_inner(now, next..last).into_iter() { - let approved = Self::bake_referendum(now, index, info)?; - ReferendumInfoOf::::insert(index, ReferendumInfo::Finished { end: now, approved }); - weight = max_block_weight; - } - - Ok(weight) - } - - /// Reads the length of account in DepositOf without getting the complete value in the runtime. - /// - /// Return 0 if no deposit for this proposal. - fn len_of_deposit_of(proposal: PropIndex) -> Option { - // DepositOf first tuple element is a vec, decoding its len is equivalent to decode a - // `Compact`. - decode_compact_u32_at(&>::hashed_key_for(proposal)) - } - - /// Check that pre image exists and its value is variant `PreimageStatus::Missing`. - /// - /// This check is done without getting the complete value in the runtime to avoid copying a big - /// value in the runtime. - fn check_pre_image_is_missing(proposal_hash: T::Hash) -> DispatchResult { - // To decode the enum variant we only need the first byte. - let mut buf = [0u8; 1]; - let key = >::hashed_key_for(proposal_hash); - let bytes = - sp_io::storage::read(&key, &mut buf, 0).ok_or_else(|| Error::::NotImminent)?; - // The value may be smaller that 1 byte. - let mut input = &buf[0..buf.len().min(bytes as usize)]; - - match input.read_byte() { - Ok(0) => Ok(()), // PreimageStatus::Missing is variant 0 - Ok(1) => Err(Error::::DuplicatePreimage.into()), - _ => { - sp_runtime::print("Failed to decode `PreimageStatus` variant"); - Err(Error::::NotImminent.into()) - }, - } - } - - /// Check that pre image exists, its value is variant `PreimageStatus::Available` and decode - /// the length of `data: Vec` fields. - /// - /// This check is done without getting the complete value in the runtime to avoid copying a big - /// value in the runtime. - /// - /// If the pre image is missing variant or doesn't exist then the error `PreimageMissing` is - /// returned. - fn pre_image_data_len(proposal_hash: T::Hash) -> Result { - // To decode the `data` field of Available variant we need: - // * one byte for the variant - // * at most 5 bytes to decode a `Compact` - let mut buf = [0u8; 6]; - let key = >::hashed_key_for(proposal_hash); - let bytes = - sp_io::storage::read(&key, &mut buf, 0).ok_or_else(|| Error::::PreimageMissing)?; - // The value may be smaller that 6 bytes. - let mut input = &buf[0..buf.len().min(bytes as usize)]; - - match input.read_byte() { - Ok(1) => (), // Check that input exists and is second variant. - Ok(0) => return Err(Error::::PreimageMissing.into()), - _ => { - sp_runtime::print("Failed to decode `PreimageStatus` variant"); - return Err(Error::::PreimageMissing.into()) - }, - } - - // Decode the length of the vector. - let len = codec::Compact::::decode(&mut input) - .map_err(|_| { - sp_runtime::print("Failed to decode `PreimageStatus` variant"); - DispatchError::from(Error::::PreimageMissing) - })? - .0; - - Ok(len) - } - - // See `note_preimage` - fn note_preimage_inner(who: T::AccountId, encoded_proposal: Vec) -> DispatchResult { - let proposal_hash = T::Hashing::hash(&encoded_proposal[..]); - ensure!(!>::contains_key(&proposal_hash), Error::::DuplicatePreimage); - - let deposit = >::from(encoded_proposal.len() as u32) - .saturating_mul(T::PreimageByteDeposit::get()); - - let currency_id = T::GovernanceCurrencyId::get(); - - T::Currency::reserve(currency_id, &who, deposit)?; - - let now = >::block_number(); - let a = PreimageStatus::Available { - data: encoded_proposal, - provider: who.clone(), - deposit, - since: now, - expiry: None, - }; - >::insert(proposal_hash, a); - - Self::deposit_event(Event::::PreimageNoted(proposal_hash, who, deposit)); - - Ok(()) - } - - // See `note_imminent_preimage` - fn note_imminent_preimage_inner( - who: T::AccountId, - encoded_proposal: Vec, - ) -> DispatchResult { - let proposal_hash = T::Hashing::hash(&encoded_proposal[..]); - Self::check_pre_image_is_missing(proposal_hash)?; - let status = Preimages::::get(&proposal_hash).ok_or(Error::::NotImminent)?; - let expiry = status.to_missing_expiry().ok_or(Error::::DuplicatePreimage)?; - - let now = >::block_number(); - let free = >::zero(); - let a = PreimageStatus::Available { - data: encoded_proposal, - provider: who.clone(), - deposit: Zero::zero(), - since: now, - expiry: Some(expiry), - }; - >::insert(proposal_hash, a); - - Self::deposit_event(Event::::PreimageNoted(proposal_hash, who, free)); - - Ok(()) - } -} - -/// Decode `Compact` from the trie at given key. -fn decode_compact_u32_at(key: &[u8]) -> Option { - // `Compact` takes at most 5 bytes. - let mut buf = [0u8; 5]; - let bytes = sp_io::storage::read(&key, &mut buf, 0)?; - // The value may be smaller than 5 bytes. - let mut input = &buf[0..buf.len().min(bytes as usize)]; - match codec::Compact::::decode(&mut input) { - Ok(c) => Some(c.0), - Err(_) => { - sp_runtime::print("Failed to decode compact u32 at:"); - sp_runtime::print(key); - None - }, - } -} diff --git a/lib-serml/democracy/src/tests.rs b/lib-serml/democracy/src/tests.rs deleted file mode 100644 index 9f177563d..000000000 --- a/lib-serml/democracy/src/tests.rs +++ /dev/null @@ -1,347 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! The crate's tests. - -use super::*; -use crate as pallet_democracy; -use codec::Encode; -use frame_support::{ - assert_noop, assert_ok, ord_parameter_types, parameter_types, - traits::{Filter, GenesisBuild, OnInitialize, SortedMembers}, - weights::Weight, -}; -use frame_system::{EnsureRoot, EnsureSignedBy}; -use pallet_balances::{Error as BalancesError}; -use sp_core::H256; -use sp_runtime::{ - testing::Header, - traits::{BadOrigin, BlakeTwo256, IdentityLookup}, - Perbill, -}; -use orml_traits::parameter_type_with_key; -use orml_tokens::BalanceLock; -use primitives::{Amount, ReserveIdentifier, TokenSymbol}; - -mod cancellation; -mod decoders; -mod delegation; -mod external_proposing; -mod fast_tracking; -mod lock_voting; -mod preimage; -mod public_proposals; -mod scheduling; -mod voting; - -pub type AccountId = u64; -pub type Balance = u64; -pub type BlockNumber = u64; - -pub const DRAM: CurrencyId = CurrencyId::Token(TokenSymbol::DRAM); - -const AYE: Vote = Vote { aye: true, conviction: Conviction::None }; -const NAY: Vote = Vote { aye: false, conviction: Conviction::None }; -const BIG_AYE: Vote = Vote { aye: true, conviction: Conviction::Locked1x }; -const BIG_NAY: Vote = Vote { aye: false, conviction: Conviction::Locked1x }; - -const MAX_PROPOSALS: u32 = 100; - -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; -type Block = frame_system::mocking::MockBlock; - -frame_support::construct_runtime!( - pub enum Runtime where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - Tokens: orml_tokens::{Pallet, Storage, Event, Config}, - Currencies: orml_currencies::{Pallet, Call, Event}, - Balances: pallet_balances::{Pallet, Call, Storage, Event}, - Scheduler: pallet_scheduler::{Pallet, Call, Storage, Config, Event}, - Democracy: pallet_democracy::{Pallet, Call, Storage, Config, Event}, - } -); - -// Test that a fitlered call can be dispatched. -pub struct BaseFilter; -impl Filter for BaseFilter { - fn filter(call: &Call) -> bool { - !matches!(call, &Call::Balances(pallet_balances::Call::set_balance(..))) - } -} - -parameter_types! { - pub const BlockHashCount: u64 = 250; - pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max(1_000_000); -} -impl frame_system::Config for Runtime { - type BaseCallFilter = BaseFilter; - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type Origin = Origin; - type Index = u64; - type BlockNumber = u64; - type Call = Call; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; - type Header = Header; - type Event = Event; - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); -} -parameter_types! { - pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block; -} -impl pallet_scheduler::Config for Runtime { - type Event = Event; - type Origin = Origin; - type PalletsOrigin = OriginCaller; - type Call = Call; - type MaximumWeight = MaximumSchedulerWeight; - type ScheduleOrigin = EnsureRoot; - type MaxScheduledPerBlock = (); - type WeightInfo = (); -} - -parameter_type_with_key! { - pub ExistentialDeposits: |_currency_id: CurrencyId| -> Balance { - Default::default() - }; -} - -impl orml_tokens::Config for Runtime { - type Event = Event; - type Balance = Balance; - type Amount = Amount; - type CurrencyId = CurrencyId; - type WeightInfo = (); - type ExistentialDeposits = ExistentialDeposits; - type OnDust = (); - type MaxLocks = (); - type DustRemovalWhitelist = (); -} - -parameter_types! { - pub const ExistentialDeposit: Balance = 1; - pub const MaxReserves: u32 = 50; -} - -impl pallet_balances::Config for Runtime { - type Balance = Balance; - type DustRemoval = (); - type Event = Event; - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Pallet; - type MaxLocks = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = ReserveIdentifier; - type WeightInfo = (); -} -pub type AdaptedBasicCurrency = orml_currencies::BasicCurrencyAdapter; - -parameter_types! { - pub const GetNativeCurrencyId: CurrencyId = DRAM; -} - -impl orml_currencies::Config for Runtime { - type Event = Event; - type MultiCurrency = Tokens; - type NativeCurrency = AdaptedBasicCurrency; - type GetNativeCurrencyId = GetNativeCurrencyId; - type WeightInfo = (); -} - -parameter_types! { - pub const GovernanceCurrencyId: CurrencyId = DRAM; -} - -parameter_types! { - pub const LaunchPeriod: u64 = 2; - pub const VotingPeriod: u64 = 2; - pub const FastTrackVotingPeriod: u64 = 2; - pub const MinimumDeposit: u64 = 1; - pub const EnactmentPeriod: u64 = 2; - pub const CooloffPeriod: u64 = 2; - pub const MaxVotes: u32 = 100; - pub const MaxProposals: u32 = MAX_PROPOSALS; - pub static PreimageByteDeposit: u64 = 0; - pub static InstantAllowed: bool = false; -} -ord_parameter_types! { - pub const One: u64 = 1; - pub const Two: u64 = 2; - pub const Three: u64 = 3; - pub const Four: u64 = 4; - pub const Five: u64 = 5; - pub const Six: u64 = 6; -} -pub struct OneToFive; -impl SortedMembers for OneToFive { - fn sorted_members() -> Vec { - vec![1, 2, 3, 4, 5] - } - #[cfg(feature = "runtime-benchmarks")] - fn add(_m: &u64) {} -} - -impl Config for Runtime { - type Proposal = Call; - type Event = Event; - type Currency = Currencies; - type GovernanceCurrencyId = GovernanceCurrencyId; - type EnactmentPeriod = EnactmentPeriod; - type LaunchPeriod = LaunchPeriod; - type VotingPeriod = VotingPeriod; - type FastTrackVotingPeriod = FastTrackVotingPeriod; - type MinimumDeposit = MinimumDeposit; - type ExternalOrigin = EnsureSignedBy; - type ExternalMajorityOrigin = EnsureSignedBy; - type ExternalDefaultOrigin = EnsureSignedBy; - type FastTrackOrigin = EnsureSignedBy; - type CancellationOrigin = EnsureSignedBy; - type BlacklistOrigin = EnsureRoot; - type CancelProposalOrigin = EnsureRoot; - type VetoOrigin = EnsureSignedBy; - type CooloffPeriod = CooloffPeriod; - type PreimageByteDeposit = PreimageByteDeposit; - type InstantOrigin = EnsureSignedBy; - type InstantAllowed = InstantAllowed; - type Scheduler = Scheduler; - type MaxVotes = MaxVotes; - type OperationalPreimageOrigin = EnsureSignedBy; - type PalletsOrigin = OriginCaller; - type WeightInfo = (); - type MaxProposals = MaxProposals; -} - -pub fn new_test_ext() -> sp_io::TestExternalities { - let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); - pallet_balances::GenesisConfig:: { - balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)], - } - .assimilate_storage(&mut t) - .unwrap(); - pallet_democracy::GenesisConfig::::default() - .assimilate_storage(&mut t) - .unwrap(); - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| System::set_block_number(1)); - ext -} - -/// Execute the function two times, with `true` and with `false`. -pub fn new_test_ext_execute_with_cond(execute: impl FnOnce(bool) -> () + Clone) { - new_test_ext().execute_with(|| (execute.clone())(false)); - new_test_ext().execute_with(|| execute(true)); -} - -#[test] -fn params_should_work() { - new_test_ext().execute_with(|| { - assert_eq!(Democracy::referendum_count(), 0); - assert_eq!(Balances::free_balance(42), 0); - assert_eq!(Tokens::total_issuance(DRAM), 0); - }); -} - -fn set_balance_proposal(value: u64) -> Vec { - Call::Balances(pallet_balances::Call::set_balance(42, value, 0)).encode() -} - -#[test] -fn set_balance_proposal_is_correctly_filtered_out() { - for i in 0..10 { - let call = Call::decode(&mut &set_balance_proposal(i)[..]).unwrap(); - assert!(!::BaseCallFilter::filter(&call)); - } -} - -fn set_balance_proposal_hash(value: u64) -> H256 { - BlakeTwo256::hash(&set_balance_proposal(value)[..]) -} - -fn set_balance_proposal_hash_and_note(value: u64) -> H256 { - let p = set_balance_proposal(value); - let h = BlakeTwo256::hash(&p[..]); - match Democracy::note_preimage(Origin::signed(6), p) { - Ok(_) => (), - Err(x) if x == Error::::DuplicatePreimage.into() => (), - Err(x) => panic!("{:?}", x), - } - h -} - -fn propose_set_balance(who: u64, value: u64, delay: u64) -> DispatchResult { - Democracy::propose(Origin::signed(who), set_balance_proposal_hash(value), delay) -} - -fn propose_set_balance_and_note(who: u64, value: u64, delay: u64) -> DispatchResult { - Democracy::propose(Origin::signed(who), set_balance_proposal_hash_and_note(value), delay) -} - -fn next_block() { - System::set_block_number(System::block_number() + 1); - Scheduler::on_initialize(System::block_number()); - assert!(Democracy::begin_block(System::block_number()).is_ok()); -} - -fn fast_forward_to(n: u64) { - while System::block_number() < n { - next_block(); - } -} - -fn begin_referendum() -> ReferendumIndex { - System::set_block_number(0); - assert_ok!(propose_set_balance_and_note(1, 2, 1)); - fast_forward_to(2); - 0 -} - -fn aye(who: u64) -> AccountVote { - AccountVote::Standard { vote: AYE, balance: Balances::free_balance(&who) } -} - -fn nay(who: u64) -> AccountVote { - AccountVote::Standard { vote: NAY, balance: Balances::free_balance(&who) } -} - -fn big_aye(who: u64) -> AccountVote { - AccountVote::Standard { vote: BIG_AYE, balance: Balances::free_balance(&who) } -} - -fn big_nay(who: u64) -> AccountVote { - AccountVote::Standard { vote: BIG_NAY, balance: Balances::free_balance(&who) } -} - -fn tally(r: ReferendumIndex) -> Tally { - Democracy::referendum_status(r).unwrap().tally -} diff --git a/lib-serml/democracy/src/tests/cancellation.rs b/lib-serml/democracy/src/tests/cancellation.rs deleted file mode 100644 index b81007e1b..000000000 --- a/lib-serml/democracy/src/tests/cancellation.rs +++ /dev/null @@ -1,92 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! The tests for cancelation functionality. - -use super::*; - -#[test] -fn cancel_referendum_should_work() { - new_test_ext().execute_with(|| { - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SuperMajorityApprove, - 0, - ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - assert_ok!(Democracy::cancel_referendum(Origin::root(), r.into())); - - next_block(); - next_block(); - - assert_eq!(Balances::free_balance(42), 0); - }); -} - -#[test] -fn cancel_queued_should_work() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - assert_ok!(propose_set_balance_and_note(1, 2, 1)); - - // start of 2 => next referendum scheduled. - fast_forward_to(2); - - assert_ok!(Democracy::vote(Origin::signed(1), 0, aye(1))); - - fast_forward_to(4); - - assert!(pallet_scheduler::Agenda::::get(6)[0].is_some()); - - assert_noop!(Democracy::cancel_queued(Origin::root(), 1), Error::::ProposalMissing); - assert_ok!(Democracy::cancel_queued(Origin::root(), 0)); - assert!(pallet_scheduler::Agenda::::get(6)[0].is_none()); - }); -} - -#[test] -fn emergency_cancel_should_work() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SuperMajorityApprove, - 2, - ); - assert!(Democracy::referendum_status(r).is_ok()); - - assert_noop!(Democracy::emergency_cancel(Origin::signed(3), r), BadOrigin); - assert_ok!(Democracy::emergency_cancel(Origin::signed(4), r)); - assert!(Democracy::referendum_info(r).is_none()); - - // some time later... - - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SuperMajorityApprove, - 2, - ); - assert!(Democracy::referendum_status(r).is_ok()); - assert_noop!( - Democracy::emergency_cancel(Origin::signed(4), r), - Error::::AlreadyCanceled, - ); - }); -} diff --git a/lib-serml/democracy/src/tests/decoders.rs b/lib-serml/democracy/src/tests/decoders.rs deleted file mode 100644 index 7e7a6b35b..000000000 --- a/lib-serml/democracy/src/tests/decoders.rs +++ /dev/null @@ -1,85 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! The for various partial storage decoders - -use super::*; -use frame_support::storage::{migration, unhashed}; - -#[test] -fn test_decode_compact_u32_at() { - new_test_ext().execute_with(|| { - let v = codec::Compact(u64::MAX); - migration::put_storage_value(b"test", b"", &[], v); - assert_eq!(decode_compact_u32_at(b"test"), None); - - for v in vec![0, 10, u32::MAX] { - let compact_v = codec::Compact(v); - unhashed::put(b"test", &compact_v); - assert_eq!(decode_compact_u32_at(b"test"), Some(v)); - } - - unhashed::kill(b"test"); - assert_eq!(decode_compact_u32_at(b"test"), None); - }) -} - -#[test] -fn len_of_deposit_of() { - new_test_ext().execute_with(|| { - for l in vec![0, 1, 200, 1000] { - let value: (Vec, u64) = ((0..l).map(|_| Default::default()).collect(), 3u64); - DepositOf::::insert(2, value); - assert_eq!(Democracy::len_of_deposit_of(2), Some(l)); - } - - DepositOf::::remove(2); - assert_eq!(Democracy::len_of_deposit_of(2), None); - }) -} - -#[test] -fn pre_image() { - new_test_ext().execute_with(|| { - let key = Default::default(); - let missing = PreimageStatus::Missing(0); - Preimages::::insert(key, missing); - assert_noop!(Democracy::pre_image_data_len(key), Error::::PreimageMissing); - assert_eq!(Democracy::check_pre_image_is_missing(key), Ok(())); - - Preimages::::remove(key); - assert_noop!(Democracy::pre_image_data_len(key), Error::::PreimageMissing); - assert_noop!(Democracy::check_pre_image_is_missing(key), Error::::NotImminent); - - for l in vec![0, 10, 100, 1000u32] { - let available = PreimageStatus::Available { - data: (0..l).map(|i| i as u8).collect(), - provider: 0, - deposit: 0, - since: 0, - expiry: None, - }; - - Preimages::::insert(key, available); - assert_eq!(Democracy::pre_image_data_len(key), Ok(l)); - assert_noop!( - Democracy::check_pre_image_is_missing(key), - Error::::DuplicatePreimage - ); - } - }) -} diff --git a/lib-serml/democracy/src/tests/delegation.rs b/lib-serml/democracy/src/tests/delegation.rs deleted file mode 100644 index 38636728d..000000000 --- a/lib-serml/democracy/src/tests/delegation.rs +++ /dev/null @@ -1,179 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! The tests for functionality concerning delegation. - -use super::*; - -#[test] -fn single_proposal_should_work_with_delegation() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - - assert_ok!(propose_set_balance_and_note(1, 2, 1)); - - fast_forward_to(2); - - // Delegate first vote. - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20)); - let r = 0; - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - assert_eq!(tally(r), Tally { ayes: 3, nays: 0, turnout: 30 }); - - // Delegate a second vote. - assert_ok!(Democracy::delegate(Origin::signed(3), 1, Conviction::None, 30)); - assert_eq!(tally(r), Tally { ayes: 6, nays: 0, turnout: 60 }); - - // Reduce first vote. - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 10)); - assert_eq!(tally(r), Tally { ayes: 5, nays: 0, turnout: 50 }); - - // Second vote delegates to first; we don't do tiered delegation, so it doesn't get used. - assert_ok!(Democracy::delegate(Origin::signed(3), 2, Conviction::None, 30)); - assert_eq!(tally(r), Tally { ayes: 2, nays: 0, turnout: 20 }); - - // Main voter cancels their vote - assert_ok!(Democracy::remove_vote(Origin::signed(1), r)); - assert_eq!(tally(r), Tally { ayes: 0, nays: 0, turnout: 0 }); - - // First delegator delegates half funds with conviction; nothing changes yet. - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::Locked1x, 10)); - assert_eq!(tally(r), Tally { ayes: 0, nays: 0, turnout: 0 }); - - // Main voter reinstates their vote - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - assert_eq!(tally(r), Tally { ayes: 11, nays: 0, turnout: 20 }); - }); -} - -#[test] -fn self_delegation_not_allowed() { - new_test_ext().execute_with(|| { - assert_noop!( - Democracy::delegate(Origin::signed(1), 1, Conviction::None, 10), - Error::::Nonsense, - ); - }); -} - -#[test] -fn cyclic_delegation_should_unwind() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - - assert_ok!(propose_set_balance_and_note(1, 2, 1)); - - fast_forward_to(2); - - // Check behavior with cycle. - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20)); - assert_ok!(Democracy::delegate(Origin::signed(3), 2, Conviction::None, 30)); - assert_ok!(Democracy::delegate(Origin::signed(1), 3, Conviction::None, 10)); - let r = 0; - assert_ok!(Democracy::undelegate(Origin::signed(3))); - assert_ok!(Democracy::vote(Origin::signed(3), r, aye(3))); - assert_ok!(Democracy::undelegate(Origin::signed(1))); - assert_ok!(Democracy::vote(Origin::signed(1), r, nay(1))); - - // Delegated vote is counted. - assert_eq!(tally(r), Tally { ayes: 3, nays: 3, turnout: 60 }); - }); -} - -#[test] -fn single_proposal_should_work_with_vote_and_delegation() { - // If transactor already voted, delegated vote is overwritten. - new_test_ext().execute_with(|| { - System::set_block_number(0); - - assert_ok!(propose_set_balance_and_note(1, 2, 1)); - - fast_forward_to(2); - - let r = 0; - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - assert_ok!(Democracy::vote(Origin::signed(2), r, nay(2))); - assert_eq!(tally(r), Tally { ayes: 1, nays: 2, turnout: 30 }); - - // Delegate vote. - assert_ok!(Democracy::remove_vote(Origin::signed(2), r)); - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20)); - // Delegated vote replaces the explicit vote. - assert_eq!(tally(r), Tally { ayes: 3, nays: 0, turnout: 30 }); - }); -} - -#[test] -fn single_proposal_should_work_with_undelegation() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - - assert_ok!(propose_set_balance_and_note(1, 2, 1)); - - // Delegate and undelegate vote. - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20)); - assert_ok!(Democracy::undelegate(Origin::signed(2))); - - fast_forward_to(2); - let r = 0; - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - - // Delegated vote is not counted. - assert_eq!(tally(r), Tally { ayes: 1, nays: 0, turnout: 10 }); - }); -} - -#[test] -fn single_proposal_should_work_with_delegation_and_vote() { - // If transactor voted, delegated vote is overwritten. - new_test_ext().execute_with(|| { - let r = begin_referendum(); - // Delegate, undelegate and vote. - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::None, 20)); - assert_eq!(tally(r), Tally { ayes: 3, nays: 0, turnout: 30 }); - assert_ok!(Democracy::undelegate(Origin::signed(2))); - assert_ok!(Democracy::vote(Origin::signed(2), r, aye(2))); - // Delegated vote is not counted. - assert_eq!(tally(r), Tally { ayes: 3, nays: 0, turnout: 30 }); - }); -} - -#[test] -fn conviction_should_be_honored_in_delegation() { - // If transactor voted, delegated vote is overwritten. - new_test_ext().execute_with(|| { - let r = begin_referendum(); - // Delegate, undelegate and vote. - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::Locked6x, 20)); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - // Delegated vote is huge. - assert_eq!(tally(r), Tally { ayes: 121, nays: 0, turnout: 30 }); - }); -} - -#[test] -fn split_vote_delegation_should_be_ignored() { - // If transactor voted, delegated vote is overwritten. - new_test_ext().execute_with(|| { - let r = begin_referendum(); - assert_ok!(Democracy::delegate(Origin::signed(2), 1, Conviction::Locked6x, 20)); - assert_ok!(Democracy::vote(Origin::signed(1), r, AccountVote::Split { aye: 10, nay: 0 })); - // Delegated vote is huge. - assert_eq!(tally(r), Tally { ayes: 1, nays: 0, turnout: 10 }); - }); -} diff --git a/lib-serml/democracy/src/tests/external_proposing.rs b/lib-serml/democracy/src/tests/external_proposing.rs deleted file mode 100644 index 966fc7dd3..000000000 --- a/lib-serml/democracy/src/tests/external_proposing.rs +++ /dev/null @@ -1,303 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! The tests for functionality concerning the "external" origin. - -use super::*; - -#[test] -fn veto_external_works() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - assert_ok!(Democracy::external_propose( - Origin::signed(2), - set_balance_proposal_hash_and_note(2), - )); - assert!(>::exists()); - - let h = set_balance_proposal_hash_and_note(2); - assert_ok!(Democracy::veto_external(Origin::signed(3), h.clone())); - // cancelled. - assert!(!>::exists()); - // fails - same proposal can't be resubmitted. - assert_noop!( - Democracy::external_propose(Origin::signed(2), set_balance_proposal_hash(2),), - Error::::ProposalBlacklisted - ); - - fast_forward_to(1); - // fails as we're still in cooloff period. - assert_noop!( - Democracy::external_propose(Origin::signed(2), set_balance_proposal_hash(2),), - Error::::ProposalBlacklisted - ); - - fast_forward_to(2); - // works; as we're out of the cooloff period. - assert_ok!(Democracy::external_propose( - Origin::signed(2), - set_balance_proposal_hash_and_note(2), - )); - assert!(>::exists()); - - // 3 can't veto the same thing twice. - assert_noop!( - Democracy::veto_external(Origin::signed(3), h.clone()), - Error::::AlreadyVetoed - ); - - // 4 vetoes. - assert_ok!(Democracy::veto_external(Origin::signed(4), h.clone())); - // cancelled again. - assert!(!>::exists()); - - fast_forward_to(3); - // same proposal fails as we're still in cooloff - assert_noop!( - Democracy::external_propose(Origin::signed(2), set_balance_proposal_hash(2),), - Error::::ProposalBlacklisted - ); - // different proposal works fine. - assert_ok!(Democracy::external_propose( - Origin::signed(2), - set_balance_proposal_hash_and_note(3), - )); - }); -} - -#[test] -fn external_blacklisting_should_work() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - - assert_ok!(Democracy::external_propose( - Origin::signed(2), - set_balance_proposal_hash_and_note(2), - )); - - let hash = set_balance_proposal_hash(2); - assert_ok!(Democracy::blacklist(Origin::root(), hash, None)); - - fast_forward_to(2); - assert_noop!(Democracy::referendum_status(0), Error::::ReferendumInvalid); - - assert_noop!( - Democracy::external_propose(Origin::signed(2), set_balance_proposal_hash_and_note(2),), - Error::::ProposalBlacklisted, - ); - }); -} - -#[test] -fn external_referendum_works() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - assert_noop!( - Democracy::external_propose(Origin::signed(1), set_balance_proposal_hash(2),), - BadOrigin, - ); - assert_ok!(Democracy::external_propose( - Origin::signed(2), - set_balance_proposal_hash_and_note(2), - )); - assert_noop!( - Democracy::external_propose(Origin::signed(2), set_balance_proposal_hash(1),), - Error::::DuplicateProposal - ); - fast_forward_to(2); - assert_eq!( - Democracy::referendum_status(0), - Ok(ReferendumStatus { - end: 4, - proposal_hash: set_balance_proposal_hash(2), - threshold: VoteThreshold::SuperMajorityApprove, - delay: 2, - tally: Tally { ayes: 0, nays: 0, turnout: 0 }, - }) - ); - }); -} - -#[test] -fn external_majority_referendum_works() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - assert_noop!( - Democracy::external_propose_majority(Origin::signed(1), set_balance_proposal_hash(2)), - BadOrigin, - ); - assert_ok!(Democracy::external_propose_majority( - Origin::signed(3), - set_balance_proposal_hash_and_note(2) - )); - fast_forward_to(2); - assert_eq!( - Democracy::referendum_status(0), - Ok(ReferendumStatus { - end: 4, - proposal_hash: set_balance_proposal_hash(2), - threshold: VoteThreshold::SimpleMajority, - delay: 2, - tally: Tally { ayes: 0, nays: 0, turnout: 0 }, - }) - ); - }); -} - -#[test] -fn external_default_referendum_works() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - assert_noop!( - Democracy::external_propose_default(Origin::signed(3), set_balance_proposal_hash(2)), - BadOrigin, - ); - assert_ok!(Democracy::external_propose_default( - Origin::signed(1), - set_balance_proposal_hash_and_note(2) - )); - fast_forward_to(2); - assert_eq!( - Democracy::referendum_status(0), - Ok(ReferendumStatus { - end: 4, - proposal_hash: set_balance_proposal_hash(2), - threshold: VoteThreshold::SuperMajorityAgainst, - delay: 2, - tally: Tally { ayes: 0, nays: 0, turnout: 0 }, - }) - ); - }); -} - -#[test] -fn external_and_public_interleaving_works() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - assert_ok!(Democracy::external_propose( - Origin::signed(2), - set_balance_proposal_hash_and_note(1), - )); - assert_ok!(propose_set_balance_and_note(6, 2, 2)); - - fast_forward_to(2); - - // both waiting: external goes first. - assert_eq!( - Democracy::referendum_status(0), - Ok(ReferendumStatus { - end: 4, - proposal_hash: set_balance_proposal_hash_and_note(1), - threshold: VoteThreshold::SuperMajorityApprove, - delay: 2, - tally: Tally { ayes: 0, nays: 0, turnout: 0 }, - }) - ); - // replenish external - assert_ok!(Democracy::external_propose( - Origin::signed(2), - set_balance_proposal_hash_and_note(3), - )); - - fast_forward_to(4); - - // both waiting: public goes next. - assert_eq!( - Democracy::referendum_status(1), - Ok(ReferendumStatus { - end: 6, - proposal_hash: set_balance_proposal_hash_and_note(2), - threshold: VoteThreshold::SuperMajorityApprove, - delay: 2, - tally: Tally { ayes: 0, nays: 0, turnout: 0 }, - }) - ); - // don't replenish public - - fast_forward_to(6); - - // it's external "turn" again, though since public is empty that doesn't really matter - assert_eq!( - Democracy::referendum_status(2), - Ok(ReferendumStatus { - end: 8, - proposal_hash: set_balance_proposal_hash_and_note(3), - threshold: VoteThreshold::SuperMajorityApprove, - delay: 2, - tally: Tally { ayes: 0, nays: 0, turnout: 0 }, - }) - ); - // replenish external - assert_ok!(Democracy::external_propose( - Origin::signed(2), - set_balance_proposal_hash_and_note(5), - )); - - fast_forward_to(8); - - // external goes again because there's no public waiting. - assert_eq!( - Democracy::referendum_status(3), - Ok(ReferendumStatus { - end: 10, - proposal_hash: set_balance_proposal_hash_and_note(5), - threshold: VoteThreshold::SuperMajorityApprove, - delay: 2, - tally: Tally { ayes: 0, nays: 0, turnout: 0 }, - }) - ); - // replenish both - assert_ok!(Democracy::external_propose( - Origin::signed(2), - set_balance_proposal_hash_and_note(7), - )); - assert_ok!(propose_set_balance_and_note(6, 4, 2)); - - fast_forward_to(10); - - // public goes now since external went last time. - assert_eq!( - Democracy::referendum_status(4), - Ok(ReferendumStatus { - end: 12, - proposal_hash: set_balance_proposal_hash_and_note(4), - threshold: VoteThreshold::SuperMajorityApprove, - delay: 2, - tally: Tally { ayes: 0, nays: 0, turnout: 0 }, - }) - ); - // replenish public again - assert_ok!(propose_set_balance_and_note(6, 6, 2)); - // cancel external - let h = set_balance_proposal_hash_and_note(7); - assert_ok!(Democracy::veto_external(Origin::signed(3), h)); - - fast_forward_to(12); - - // public goes again now since there's no external waiting. - assert_eq!( - Democracy::referendum_status(5), - Ok(ReferendumStatus { - end: 14, - proposal_hash: set_balance_proposal_hash_and_note(6), - threshold: VoteThreshold::SuperMajorityApprove, - delay: 2, - tally: Tally { ayes: 0, nays: 0, turnout: 0 }, - }) - ); - }); -} diff --git a/lib-serml/democracy/src/tests/fast_tracking.rs b/lib-serml/democracy/src/tests/fast_tracking.rs deleted file mode 100644 index e143baea6..000000000 --- a/lib-serml/democracy/src/tests/fast_tracking.rs +++ /dev/null @@ -1,98 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! The tests for fast-tracking functionality. - -use super::*; - -#[test] -fn fast_track_referendum_works() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - let h = set_balance_proposal_hash_and_note(2); - assert_noop!( - Democracy::fast_track(Origin::signed(5), h, 3, 2), - Error::::ProposalMissing - ); - assert_ok!(Democracy::external_propose_majority( - Origin::signed(3), - set_balance_proposal_hash_and_note(2) - )); - assert_noop!(Democracy::fast_track(Origin::signed(1), h, 3, 2), BadOrigin); - assert_ok!(Democracy::fast_track(Origin::signed(5), h, 2, 0)); - assert_eq!( - Democracy::referendum_status(0), - Ok(ReferendumStatus { - end: 2, - proposal_hash: set_balance_proposal_hash_and_note(2), - threshold: VoteThreshold::SimpleMajority, - delay: 0, - tally: Tally { ayes: 0, nays: 0, turnout: 0 }, - }) - ); - }); -} - -#[test] -fn instant_referendum_works() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - let h = set_balance_proposal_hash_and_note(2); - assert_noop!( - Democracy::fast_track(Origin::signed(5), h, 3, 2), - Error::::ProposalMissing - ); - assert_ok!(Democracy::external_propose_majority( - Origin::signed(3), - set_balance_proposal_hash_and_note(2) - )); - assert_noop!(Democracy::fast_track(Origin::signed(1), h, 3, 2), BadOrigin); - assert_noop!(Democracy::fast_track(Origin::signed(5), h, 1, 0), BadOrigin); - assert_noop!( - Democracy::fast_track(Origin::signed(6), h, 1, 0), - Error::::InstantNotAllowed - ); - INSTANT_ALLOWED.with(|v| *v.borrow_mut() = true); - assert_ok!(Democracy::fast_track(Origin::signed(6), h, 1, 0)); - assert_eq!( - Democracy::referendum_status(0), - Ok(ReferendumStatus { - end: 1, - proposal_hash: set_balance_proposal_hash_and_note(2), - threshold: VoteThreshold::SimpleMajority, - delay: 0, - tally: Tally { ayes: 0, nays: 0, turnout: 0 }, - }) - ); - }); -} - -#[test] -fn fast_track_referendum_fails_when_no_simple_majority() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - let h = set_balance_proposal_hash_and_note(2); - assert_ok!(Democracy::external_propose( - Origin::signed(2), - set_balance_proposal_hash_and_note(2) - )); - assert_noop!( - Democracy::fast_track(Origin::signed(5), h, 3, 2), - Error::::NotSimpleMajority - ); - }); -} diff --git a/lib-serml/democracy/src/tests/lock_voting.rs b/lib-serml/democracy/src/tests/lock_voting.rs deleted file mode 100644 index 3abbf358e..000000000 --- a/lib-serml/democracy/src/tests/lock_voting.rs +++ /dev/null @@ -1,378 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! The tests for functionality concerning locking and lock-voting. - -use super::*; -use std::convert::TryFrom; - -fn aye(x: u8, balance: u64) -> AccountVote { - AccountVote::Standard { - vote: Vote { aye: true, conviction: Conviction::try_from(x).unwrap() }, - balance, - } -} - -fn nay(x: u8, balance: u64) -> AccountVote { - AccountVote::Standard { - vote: Vote { aye: false, conviction: Conviction::try_from(x).unwrap() }, - balance, - } -} - -fn the_lock(amount: u64) -> BalanceLock { - BalanceLock { id: DEMOCRACY_ID, amount } -} - -/// TODO: Make up workind Tests for the commented tests -// #[test] -// fn lock_voting_should_work() { -// new_test_ext().execute_with(|| { -// System::set_block_number(0); -// let r = Democracy::inject_referendum( -// 2, -// set_balance_proposal_hash_and_note(2), -// VoteThreshold::SuperMajorityApprove, -// 0, -// ); -// assert_ok!(Democracy::vote(Origin::signed(1), r, nay(5, 10))); -// assert_ok!(Democracy::vote(Origin::signed(2), r, aye(4, 20))); -// assert_ok!(Democracy::vote(Origin::signed(3), r, aye(3, 30))); -// assert_ok!(Democracy::vote(Origin::signed(4), r, aye(2, 40))); -// assert_ok!(Democracy::vote(Origin::signed(5), r, nay(1, 50))); -// assert_eq!(tally(r), Tally { ayes: 250, nays: 100, turnout: 150 }); - -// // All balances are currently locked. -// for i in 1..=5 { -// assert_eq!(Tokens::locks(i, DRAM), vec![the_lock(i * 10)]); -// } - -// fast_forward_to(2); - -// // Referendum passed; 1 and 5 didn't get their way and can now reap and unlock. -// assert_ok!(Democracy::remove_vote(Origin::signed(1), r)); -// assert_ok!(Democracy::unlock(Origin::signed(1), 1)); -// // Anyone can reap and unlock anyone else's in this context. -// assert_ok!(Democracy::remove_other_vote(Origin::signed(2), 5, r)); -// assert_ok!(Democracy::unlock(Origin::signed(2), 5)); - -// // 2, 3, 4 got their way with the vote, so they cannot be reaped by others. -// assert_noop!( -// Democracy::remove_other_vote(Origin::signed(1), 2, r), -// Error::::NoPermission -// ); -// // However, they can be unvoted by the owner, though it will make no difference to the lock. -// assert_ok!(Democracy::remove_vote(Origin::signed(2), r)); -// assert_ok!(Democracy::unlock(Origin::signed(2), 2)); - -// assert_eq!(Tokens::locks(1, DRAM), vec![]); -// assert_eq!(Tokens::locks(2, DRAM), vec![the_lock(20)]); -// assert_eq!(Tokens::locks(3, DRAM), vec![the_lock(30)]); -// assert_eq!(Tokens::locks(4, DRAM), vec![the_lock(40)]); -// assert_eq!(Tokens::locks(5, DRAM), vec![]); -// assert_eq!(Tokens::free_balance(DRAM, &42), 2); - -// fast_forward_to(5); -// // No change yet... -// assert_noop!( -// Democracy::remove_other_vote(Origin::signed(1), 4, r), -// Error::::NoPermission -// ); -// assert_ok!(Democracy::unlock(Origin::signed(1), 4)); -// assert_eq!(Tokens::locks(4, DRAM), vec![the_lock(40)]); -// fast_forward_to(6); -// // 4 should now be able to reap and unlock -// assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 4, r)); -// assert_ok!(Democracy::unlock(Origin::signed(1), 4)); -// assert_eq!(Tokens::locks(4, DRAM), vec![]); - -// fast_forward_to(9); -// assert_noop!( -// Democracy::remove_other_vote(Origin::signed(1), 3, r), -// Error::::NoPermission -// ); -// assert_ok!(Democracy::unlock(Origin::signed(1), 3)); -// assert_eq!(Tokens::locks(3, DRAM), vec![the_lock(30)]); -// fast_forward_to(10); -// assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 3, r)); -// assert_ok!(Democracy::unlock(Origin::signed(1), 3)); -// assert_eq!(Tokens::locks(3, DRAM), vec![]); - -// // 2 doesn't need to reap_vote here because it was already done before. -// fast_forward_to(17); -// assert_ok!(Democracy::unlock(Origin::signed(1), 2)); -// assert_eq!(Tokens::locks(2, DRAM), vec![the_lock(20)]); -// fast_forward_to(18); -// assert_ok!(Democracy::unlock(Origin::signed(1), 2)); -// assert_eq!(Tokens::locks(2, DRAM), vec![]); -// }); -// } - -#[test] -fn no_locks_without_conviction_should_work() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SuperMajorityApprove, - 0, - ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(0, 10))); - - fast_forward_to(2); - - assert_eq!(Tokens::free_balance(DRAM, &42), 0); - assert_ok!(Democracy::remove_other_vote(Origin::signed(2), 1, r)); - assert_ok!(Democracy::unlock(Origin::signed(2), 1)); - assert_eq!(Tokens::locks(1, DRAM), vec![]); - }); -} - -#[test] -fn lock_voting_should_work_with_delegation() { - new_test_ext().execute_with(|| { - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SuperMajorityApprove, - 0, - ); - assert_ok!(Democracy::vote(Origin::signed(1), r, nay(5, 10))); - assert_ok!(Democracy::vote(Origin::signed(2), r, aye(4, 20))); - assert_ok!(Democracy::vote(Origin::signed(3), r, aye(3, 30))); - assert_ok!(Democracy::delegate(Origin::signed(4), 2, Conviction::Locked2x, 40)); - assert_ok!(Democracy::vote(Origin::signed(5), r, nay(1, 50))); - - assert_eq!(tally(r), Tally { ayes: 250, nays: 100, turnout: 150 }); - - next_block(); - next_block(); - - assert_eq!(Tokens::free_balance(DRAM, &42), 0); - }); -} - -fn setup_three_referenda() -> (u32, u32, u32) { - System::set_block_number(0); - let r1 = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SimpleMajority, - 0, - ); - assert_ok!(Democracy::vote(Origin::signed(5), r1, aye(4, 10))); - - let r2 = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SimpleMajority, - 0, - ); - assert_ok!(Democracy::vote(Origin::signed(5), r2, aye(3, 20))); - - let r3 = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SimpleMajority, - 0, - ); - assert_ok!(Democracy::vote(Origin::signed(5), r3, aye(2, 50))); - - fast_forward_to(2); - - (r1, r2, r3) -} - -// #[test] -// fn prior_lockvotes_should_be_enforced() { -// new_test_ext().execute_with(|| { -// let r = setup_three_referenda(); -// // r.0 locked 10 until #18. -// // r.1 locked 20 until #10. -// // r.2 locked 50 until #6. - -// fast_forward_to(5); -// assert_noop!( -// Democracy::remove_other_vote(Origin::signed(1), 5, r.2), -// Error::::NoPermission -// ); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![the_lock(50)]); -// fast_forward_to(6); -// assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 5, r.2)); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![the_lock(20)]); -// fast_forward_to(9); -// assert_noop!( -// Democracy::remove_other_vote(Origin::signed(1), 5, r.1), -// Error::::NoPermission -// ); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![the_lock(20)]); -// fast_forward_to(10); -// assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 5, r.1)); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![the_lock(10)]); -// fast_forward_to(17); -// assert_noop!( -// Democracy::remove_other_vote(Origin::signed(1), 5, r.0), -// Error::::NoPermission -// ); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![the_lock(10)]); -// fast_forward_to(18); -// assert_ok!(Democracy::remove_other_vote(Origin::signed(1), 5, r.0)); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![]); -// }); -// } - -// #[test] -// fn single_consolidation_of_lockvotes_should_work_as_before() { -// new_test_ext().execute_with(|| { -// let r = setup_three_referenda(); -// // r.0 locked 10 until #18. -// // r.1 locked 20 until #10. -// // r.2 locked 50 until #6. - -// fast_forward_to(5); -// assert_ok!(Democracy::remove_vote(Origin::signed(5), r.2)); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![the_lock(50)]); -// fast_forward_to(6); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![the_lock(20)]); - -// fast_forward_to(9); -// assert_ok!(Democracy::remove_vote(Origin::signed(5), r.1)); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![the_lock(20)]); -// fast_forward_to(10); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![the_lock(10)]); - -// fast_forward_to(17); -// assert_ok!(Democracy::remove_vote(Origin::signed(5), r.0)); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![the_lock(10)]); -// fast_forward_to(18); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![]); -// }); -// } - -// #[test] -// fn multi_consolidation_of_lockvotes_should_be_conservative() { -// new_test_ext().execute_with(|| { -// let r = setup_three_referenda(); -// // r.0 locked 10 until #18. -// // r.1 locked 20 until #10. -// // r.2 locked 50 until #6. - -// assert_ok!(Democracy::remove_vote(Origin::signed(5), r.2)); -// assert_ok!(Democracy::remove_vote(Origin::signed(5), r.1)); -// assert_ok!(Democracy::remove_vote(Origin::signed(5), r.0)); - -// fast_forward_to(6); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert!(Tokens::locks(5, DRAM)[0].amount >= 20); - -// fast_forward_to(10); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert!(Tokens::locks(5, DRAM)[0].amount >= 10); - -// fast_forward_to(18); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![]); -// }); -// } - -// #[test] -// fn locks_should_persist_from_voting_to_delegation() { -// new_test_ext().execute_with(|| { -// System::set_block_number(0); -// let r = Democracy::inject_referendum( -// 2, -// set_balance_proposal_hash_and_note(2), -// VoteThreshold::SimpleMajority, -// 0, -// ); -// assert_ok!(Democracy::vote(Origin::signed(5), r, aye(4, 10))); -// fast_forward_to(2); -// assert_ok!(Democracy::remove_vote(Origin::signed(5), r)); -// // locked 10 until #18. - -// assert_ok!(Democracy::delegate(Origin::signed(5), 1, Conviction::Locked3x, 20)); -// // locked 20. -// assert!(Tokens::locks(5, DRAM)[0].amount == 20); - -// assert_ok!(Democracy::undelegate(Origin::signed(5))); -// // locked 20 until #10 - -// fast_forward_to(9); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert!(Tokens::locks(5, DRAM)[0].amount == 20); - -// fast_forward_to(10); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert!(Tokens::locks(5, DRAM)[0].amount >= 10); - -// fast_forward_to(17); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert!(Tokens::locks(5, DRAM)[0].amount >= 10); - -// fast_forward_to(18); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![]); -// }); -// } - -// #[test] -// fn locks_should_persist_from_delegation_to_voting() { -// new_test_ext().execute_with(|| { -// System::set_block_number(0); -// assert_ok!(Democracy::delegate(Origin::signed(5), 1, Conviction::Locked5x, 5)); -// assert_ok!(Democracy::undelegate(Origin::signed(5))); -// // locked 5 until #32 - -// let r = setup_three_referenda(); -// // r.0 locked 10 until #18. -// // r.1 locked 20 until #10. -// // r.2 locked 50 until #6. - -// assert_ok!(Democracy::remove_vote(Origin::signed(5), r.2)); -// assert_ok!(Democracy::remove_vote(Origin::signed(5), r.1)); -// assert_ok!(Democracy::remove_vote(Origin::signed(5), r.0)); - -// fast_forward_to(6); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert!(Tokens::locks(5, DRAM)[0].amount >= 20); - -// fast_forward_to(10); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert!(Tokens::locks(5, DRAM)[0].amount >= 10); - -// fast_forward_to(18); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert!(Tokens::locks(5, DRAM)[0].amount >= 5); - -// fast_forward_to(32); -// assert_ok!(Democracy::unlock(Origin::signed(5), 5)); -// assert_eq!(Tokens::locks(5, DRAM), vec![]); -// }); -// } diff --git a/lib-serml/democracy/src/tests/preimage.rs b/lib-serml/democracy/src/tests/preimage.rs deleted file mode 100644 index 6bd5fbfe9..000000000 --- a/lib-serml/democracy/src/tests/preimage.rs +++ /dev/null @@ -1,219 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! The preimage tests. - -use super::*; - -#[test] -fn missing_preimage_should_fail() { - new_test_ext().execute_with(|| { - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash(2), - VoteThreshold::SuperMajorityApprove, - 0, - ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - - next_block(); - next_block(); - - assert_eq!(Balances::free_balance(42), 0); - }); -} - -#[test] -fn preimage_deposit_should_be_required_and_returned() { - new_test_ext_execute_with_cond(|operational| { - // fee of 100 is too much. - PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 100); - assert_noop!( - if operational { - Democracy::note_preimage_operational(Origin::signed(6), vec![0; 500]) - } else { - Democracy::note_preimage(Origin::signed(6), vec![0; 500]) - }, - BalancesError::::InsufficientBalance, - ); - // fee of 1 is reasonable. - PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1); - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SuperMajorityApprove, - 0, - ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - - assert_eq!(Balances::reserved_balance(6), 12); - - next_block(); - next_block(); - - assert_eq!(Balances::reserved_balance(6), 0); - assert_eq!(Balances::free_balance(6), 60); - assert_eq!(Balances::free_balance(42), 2); - }); -} - -#[test] -fn preimage_deposit_should_be_reapable_earlier_by_owner() { - new_test_ext_execute_with_cond(|operational| { - PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1); - assert_ok!(if operational { - Democracy::note_preimage_operational(Origin::signed(6), set_balance_proposal(2)) - } else { - Democracy::note_preimage(Origin::signed(6), set_balance_proposal(2)) - }); - - assert_eq!(Balances::reserved_balance(6), 12); - - next_block(); - assert_noop!( - Democracy::reap_preimage(Origin::signed(6), set_balance_proposal_hash(2), u32::MAX), - Error::::TooEarly - ); - next_block(); - assert_ok!(Democracy::reap_preimage( - Origin::signed(6), - set_balance_proposal_hash(2), - u32::MAX - )); - - assert_eq!(Balances::free_balance(6), 60); - assert_eq!(Balances::reserved_balance(6), 0); - }); -} - -#[test] -fn preimage_deposit_should_be_reapable() { - new_test_ext_execute_with_cond(|operational| { - assert_noop!( - Democracy::reap_preimage(Origin::signed(5), set_balance_proposal_hash(2), u32::MAX), - Error::::PreimageMissing - ); - - PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1); - assert_ok!(if operational { - Democracy::note_preimage_operational(Origin::signed(6), set_balance_proposal(2)) - } else { - Democracy::note_preimage(Origin::signed(6), set_balance_proposal(2)) - }); - assert_eq!(Balances::reserved_balance(6), 12); - - next_block(); - next_block(); - next_block(); - assert_noop!( - Democracy::reap_preimage(Origin::signed(5), set_balance_proposal_hash(2), u32::MAX), - Error::::TooEarly - ); - - next_block(); - assert_ok!(Democracy::reap_preimage( - Origin::signed(5), - set_balance_proposal_hash(2), - u32::MAX - )); - assert_eq!(Balances::reserved_balance(6), 0); - assert_eq!(Balances::free_balance(6), 48); - assert_eq!(Balances::free_balance(5), 62); - }); -} - -#[test] -fn noting_imminent_preimage_for_free_should_work() { - new_test_ext_execute_with_cond(|operational| { - PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1); - - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash(2), - VoteThreshold::SuperMajorityApprove, - 1, - ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - - assert_noop!( - if operational { - Democracy::note_imminent_preimage_operational( - Origin::signed(6), - set_balance_proposal(2), - ) - } else { - Democracy::note_imminent_preimage(Origin::signed(6), set_balance_proposal(2)) - }, - Error::::NotImminent - ); - - next_block(); - - // Now we're in the dispatch queue it's all good. - assert_ok!(Democracy::note_imminent_preimage(Origin::signed(6), set_balance_proposal(2))); - - next_block(); - - assert_eq!(Balances::free_balance(42), 2); - }); -} - -#[test] -fn reaping_imminent_preimage_should_fail() { - new_test_ext().execute_with(|| { - let h = set_balance_proposal_hash_and_note(2); - let r = Democracy::inject_referendum(3, h, VoteThreshold::SuperMajorityApprove, 1); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - next_block(); - next_block(); - assert_noop!( - Democracy::reap_preimage(Origin::signed(6), h, u32::MAX), - Error::::Imminent - ); - }); -} - -#[test] -fn note_imminent_preimage_can_only_be_successful_once() { - new_test_ext().execute_with(|| { - PREIMAGE_BYTE_DEPOSIT.with(|v| *v.borrow_mut() = 1); - - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash(2), - VoteThreshold::SuperMajorityApprove, - 1, - ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - next_block(); - - // First time works - assert_ok!(Democracy::note_imminent_preimage(Origin::signed(6), set_balance_proposal(2))); - - // Second time fails - assert_noop!( - Democracy::note_imminent_preimage(Origin::signed(6), set_balance_proposal(2)), - Error::::DuplicatePreimage - ); - - // Fails from any user - assert_noop!( - Democracy::note_imminent_preimage(Origin::signed(5), set_balance_proposal(2)), - Error::::DuplicatePreimage - ); - }); -} diff --git a/lib-serml/democracy/src/tests/public_proposals.rs b/lib-serml/democracy/src/tests/public_proposals.rs deleted file mode 100644 index 81906603b..000000000 --- a/lib-serml/democracy/src/tests/public_proposals.rs +++ /dev/null @@ -1,149 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! The tests for the public proposal queue. - -use super::*; - -#[test] -fn backing_for_should_work() { - new_test_ext().execute_with(|| { - assert_ok!(propose_set_balance_and_note(1, 2, 2)); - assert_ok!(propose_set_balance_and_note(1, 4, 4)); - assert_ok!(propose_set_balance_and_note(1, 3, 3)); - assert_eq!(Democracy::backing_for(0), Some(2)); - assert_eq!(Democracy::backing_for(1), Some(4)); - assert_eq!(Democracy::backing_for(2), Some(3)); - }); -} - -#[test] -fn deposit_for_proposals_should_be_taken() { - new_test_ext().execute_with(|| { - assert_ok!(propose_set_balance_and_note(1, 2, 5)); - assert_ok!(Democracy::second(Origin::signed(2), 0, u32::MAX)); - assert_ok!(Democracy::second(Origin::signed(5), 0, u32::MAX)); - assert_ok!(Democracy::second(Origin::signed(5), 0, u32::MAX)); - assert_ok!(Democracy::second(Origin::signed(5), 0, u32::MAX)); - assert_eq!(Balances::free_balance(1), 5); - assert_eq!(Balances::free_balance(2), 15); - assert_eq!(Balances::free_balance(5), 35); - }); -} - -#[test] -fn deposit_for_proposals_should_be_returned() { - new_test_ext().execute_with(|| { - assert_ok!(propose_set_balance_and_note(1, 2, 5)); - assert_ok!(Democracy::second(Origin::signed(2), 0, u32::MAX)); - assert_ok!(Democracy::second(Origin::signed(5), 0, u32::MAX)); - assert_ok!(Democracy::second(Origin::signed(5), 0, u32::MAX)); - assert_ok!(Democracy::second(Origin::signed(5), 0, u32::MAX)); - fast_forward_to(3); - assert_eq!(Balances::free_balance(1), 10); - assert_eq!(Balances::free_balance(2), 20); - assert_eq!(Balances::free_balance(5), 50); - }); -} - -#[test] -fn proposal_with_deposit_below_minimum_should_not_work() { - new_test_ext().execute_with(|| { - assert_noop!(propose_set_balance(1, 2, 0), Error::::ValueLow); - }); -} - -#[test] -fn poor_proposer_should_not_work() { - new_test_ext().execute_with(|| { - assert_noop!(propose_set_balance(1, 2, 11), BalancesError::::InsufficientBalance); - }); -} - -#[test] -fn poor_seconder_should_not_work() { - new_test_ext().execute_with(|| { - assert_ok!(propose_set_balance_and_note(2, 2, 11)); - assert_noop!( - Democracy::second(Origin::signed(1), 0, u32::MAX), - BalancesError::::InsufficientBalance - ); - }); -} - -#[test] -fn invalid_seconds_upper_bound_should_not_work() { - new_test_ext().execute_with(|| { - assert_ok!(propose_set_balance_and_note(1, 2, 5)); - assert_noop!(Democracy::second(Origin::signed(2), 0, 0), Error::::WrongUpperBound); - }); -} - -#[test] -fn cancel_proposal_should_work() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - assert_ok!(propose_set_balance_and_note(1, 2, 2)); - assert_ok!(propose_set_balance_and_note(1, 4, 4)); - assert_noop!(Democracy::cancel_proposal(Origin::signed(1), 0), BadOrigin); - assert_ok!(Democracy::cancel_proposal(Origin::root(), 0)); - assert_eq!(Democracy::backing_for(0), None); - assert_eq!(Democracy::backing_for(1), Some(4)); - }); -} - -#[test] -fn blacklisting_should_work() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - let hash = set_balance_proposal_hash(2); - - assert_ok!(propose_set_balance_and_note(1, 2, 2)); - assert_ok!(propose_set_balance_and_note(1, 4, 4)); - - assert_noop!(Democracy::blacklist(Origin::signed(1), hash.clone(), None), BadOrigin); - assert_ok!(Democracy::blacklist(Origin::root(), hash, None)); - - assert_eq!(Democracy::backing_for(0), None); - assert_eq!(Democracy::backing_for(1), Some(4)); - - assert_noop!(propose_set_balance_and_note(1, 2, 2), Error::::ProposalBlacklisted); - - fast_forward_to(2); - - let hash = set_balance_proposal_hash(4); - assert_ok!(Democracy::referendum_status(0)); - assert_ok!(Democracy::blacklist(Origin::root(), hash, Some(0))); - assert_noop!(Democracy::referendum_status(0), Error::::ReferendumInvalid); - }); -} - -#[test] -fn runners_up_should_come_after() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - assert_ok!(propose_set_balance_and_note(1, 2, 2)); - assert_ok!(propose_set_balance_and_note(1, 4, 4)); - assert_ok!(propose_set_balance_and_note(1, 3, 3)); - fast_forward_to(2); - assert_ok!(Democracy::vote(Origin::signed(1), 0, aye(1))); - fast_forward_to(4); - assert_ok!(Democracy::vote(Origin::signed(1), 1, aye(1))); - fast_forward_to(6); - assert_ok!(Democracy::vote(Origin::signed(1), 2, aye(1))); - }); -} diff --git a/lib-serml/democracy/src/tests/scheduling.rs b/lib-serml/democracy/src/tests/scheduling.rs deleted file mode 100644 index 06b492bc6..000000000 --- a/lib-serml/democracy/src/tests/scheduling.rs +++ /dev/null @@ -1,112 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! The tests for functionality concerning normal starting, ending and enacting of referenda. - -use super::*; - -#[test] -fn simple_passing_should_work() { - new_test_ext().execute_with(|| { - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SuperMajorityApprove, - 0, - ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - assert_eq!(tally(r), Tally { ayes: 1, nays: 0, turnout: 10 }); - next_block(); - next_block(); - assert_eq!(Balances::free_balance(42), 2); - }); -} - -#[test] -fn simple_failing_should_work() { - new_test_ext().execute_with(|| { - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SuperMajorityApprove, - 0, - ); - assert_ok!(Democracy::vote(Origin::signed(1), r, nay(1))); - assert_eq!(tally(r), Tally { ayes: 0, nays: 1, turnout: 10 }); - - next_block(); - next_block(); - - assert_eq!(Balances::free_balance(42), 0); - }); -} - -#[test] -fn ooo_inject_referendums_should_work() { - new_test_ext().execute_with(|| { - let r1 = Democracy::inject_referendum( - 3, - set_balance_proposal_hash_and_note(3), - VoteThreshold::SuperMajorityApprove, - 0, - ); - let r2 = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SuperMajorityApprove, - 0, - ); - - assert_ok!(Democracy::vote(Origin::signed(1), r2, aye(1))); - assert_eq!(tally(r2), Tally { ayes: 1, nays: 0, turnout: 10 }); - - next_block(); - assert_eq!(Balances::free_balance(42), 2); - - assert_ok!(Democracy::vote(Origin::signed(1), r1, aye(1))); - assert_eq!(tally(r1), Tally { ayes: 1, nays: 0, turnout: 10 }); - - next_block(); - assert_eq!(Balances::free_balance(42), 3); - }); -} - -#[test] -fn delayed_enactment_should_work() { - new_test_ext().execute_with(|| { - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SuperMajorityApprove, - 1, - ); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - assert_ok!(Democracy::vote(Origin::signed(2), r, aye(2))); - assert_ok!(Democracy::vote(Origin::signed(3), r, aye(3))); - assert_ok!(Democracy::vote(Origin::signed(4), r, aye(4))); - assert_ok!(Democracy::vote(Origin::signed(5), r, aye(5))); - assert_ok!(Democracy::vote(Origin::signed(6), r, aye(6))); - - assert_eq!(tally(r), Tally { ayes: 21, nays: 0, turnout: 210 }); - - next_block(); - assert_eq!(Balances::free_balance(42), 0); - - next_block(); - assert_eq!(Balances::free_balance(42), 2); - }); -} diff --git a/lib-serml/democracy/src/tests/voting.rs b/lib-serml/democracy/src/tests/voting.rs deleted file mode 100644 index 8c7fd7569..000000000 --- a/lib-serml/democracy/src/tests/voting.rs +++ /dev/null @@ -1,169 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! The tests for normal voting functionality. - -use super::*; - -#[test] -fn overvoting_should_fail() { - new_test_ext().execute_with(|| { - let r = begin_referendum(); - assert_noop!( - Democracy::vote(Origin::signed(1), r, aye(2)), - Error::::InsufficientFunds - ); - }); -} - -#[test] -fn split_voting_should_work() { - new_test_ext().execute_with(|| { - let r = begin_referendum(); - let v = AccountVote::Split { aye: 40, nay: 20 }; - assert_noop!(Democracy::vote(Origin::signed(5), r, v), Error::::InsufficientFunds); - let v = AccountVote::Split { aye: 30, nay: 20 }; - assert_ok!(Democracy::vote(Origin::signed(5), r, v)); - - assert_eq!(tally(r), Tally { ayes: 3, nays: 2, turnout: 50 }); - }); -} - -#[test] -fn split_vote_cancellation_should_work() { - new_test_ext().execute_with(|| { - let r = begin_referendum(); - let v = AccountVote::Split { aye: 30, nay: 20 }; - assert_ok!(Democracy::vote(Origin::signed(5), r, v)); - assert_ok!(Democracy::remove_vote(Origin::signed(5), r)); - assert_eq!(tally(r), Tally { ayes: 0, nays: 0, turnout: 0 }); - assert_ok!(Democracy::unlock(Origin::signed(5), 5)); - assert_eq!(Balances::locks(5), vec![]); - }); -} - -#[test] -fn single_proposal_should_work() { - new_test_ext().execute_with(|| { - System::set_block_number(0); - assert_ok!(propose_set_balance_and_note(1, 2, 1)); - let r = 0; - assert!(Democracy::referendum_info(r).is_none()); - - // start of 2 => next referendum scheduled. - fast_forward_to(2); - assert_ok!(Democracy::vote(Origin::signed(1), r, aye(1))); - - assert_eq!(Democracy::referendum_count(), 1); - assert_eq!( - Democracy::referendum_status(0), - Ok(ReferendumStatus { - end: 4, - proposal_hash: set_balance_proposal_hash_and_note(2), - threshold: VoteThreshold::SuperMajorityApprove, - delay: 2, - tally: Tally { ayes: 1, nays: 0, turnout: 10 }, - }) - ); - - fast_forward_to(3); - - // referendum still running - assert_ok!(Democracy::referendum_status(0)); - - // referendum runs during 2 and 3, ends @ start of 4. - fast_forward_to(4); - - assert_noop!(Democracy::referendum_status(0), Error::::ReferendumInvalid); - assert!(pallet_scheduler::Agenda::::get(6)[0].is_some()); - - // referendum passes and wait another two blocks for enactment. - fast_forward_to(6); - - assert_eq!(Balances::free_balance(42), 2); - }); -} - -#[test] -fn controversial_voting_should_work() { - new_test_ext().execute_with(|| { - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SuperMajorityApprove, - 0, - ); - - assert_ok!(Democracy::vote(Origin::signed(1), r, big_aye(1))); - assert_ok!(Democracy::vote(Origin::signed(2), r, big_nay(2))); - assert_ok!(Democracy::vote(Origin::signed(3), r, big_nay(3))); - assert_ok!(Democracy::vote(Origin::signed(4), r, big_aye(4))); - assert_ok!(Democracy::vote(Origin::signed(5), r, big_nay(5))); - assert_ok!(Democracy::vote(Origin::signed(6), r, big_aye(6))); - - assert_eq!(tally(r), Tally { ayes: 110, nays: 100, turnout: 210 }); - - next_block(); - next_block(); - - assert_eq!(Balances::free_balance(42), 2); - }); -} - -#[test] -fn controversial_low_turnout_voting_should_work() { - new_test_ext().execute_with(|| { - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SuperMajorityApprove, - 0, - ); - assert_ok!(Democracy::vote(Origin::signed(5), r, big_nay(5))); - assert_ok!(Democracy::vote(Origin::signed(6), r, big_aye(6))); - - assert_eq!(tally(r), Tally { ayes: 60, nays: 50, turnout: 110 }); - - next_block(); - next_block(); - - assert_eq!(Balances::free_balance(42), 0); - }); -} - -#[test] -fn passing_low_turnout_voting_should_work() { - new_test_ext().execute_with(|| { - assert_eq!(Balances::free_balance(42), 0); - assert_eq!(Balances::total_issuance(), 210); - - let r = Democracy::inject_referendum( - 2, - set_balance_proposal_hash_and_note(2), - VoteThreshold::SuperMajorityApprove, - 0, - ); - assert_ok!(Democracy::vote(Origin::signed(4), r, big_aye(4))); - assert_ok!(Democracy::vote(Origin::signed(5), r, big_nay(5))); - assert_ok!(Democracy::vote(Origin::signed(6), r, big_aye(6))); - assert_eq!(tally(r), Tally { ayes: 100, nays: 50, turnout: 150 }); - - next_block(); - next_block(); - assert_eq!(Balances::free_balance(42), 2); - }); -} diff --git a/lib-serml/democracy/src/types.rs b/lib-serml/democracy/src/types.rs deleted file mode 100644 index 4e643006e..000000000 --- a/lib-serml/democracy/src/types.rs +++ /dev/null @@ -1,205 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Miscellaneous additional datatypes. - -use crate::{AccountVote, Conviction, Vote, VoteThreshold}; -use codec::{Decode, Encode}; -use sp_runtime::{ - traits::{Bounded, CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, Saturating, Zero}, - RuntimeDebug, -}; - -/// Info regarding an ongoing referendum. -#[derive(Encode, Decode, Default, Clone, PartialEq, Eq, RuntimeDebug)] -pub struct Tally { - /// The number of aye votes, expressed in terms of post-conviction lock-vote. - pub(crate) ayes: Balance, - /// The number of nay votes, expressed in terms of post-conviction lock-vote. - pub(crate) nays: Balance, - /// The amount of funds currently expressing its opinion. Pre-conviction. - pub(crate) turnout: Balance, -} - -/// Amount of votes and capital placed in delegation for an account. -#[derive(Encode, Decode, Default, Copy, Clone, PartialEq, Eq, RuntimeDebug)] -pub struct Delegations { - /// The number of votes (this is post-conviction). - pub(crate) votes: Balance, - /// The amount of raw capital, used for the turnout. - pub(crate) capital: Balance, -} - -impl Saturating for Delegations { - fn saturating_add(self, o: Self) -> Self { - Self { - votes: self.votes.saturating_add(o.votes), - capital: self.capital.saturating_add(o.capital), - } - } - - fn saturating_sub(self, o: Self) -> Self { - Self { - votes: self.votes.saturating_sub(o.votes), - capital: self.capital.saturating_sub(o.capital), - } - } - - fn saturating_mul(self, o: Self) -> Self { - Self { - votes: self.votes.saturating_mul(o.votes), - capital: self.capital.saturating_mul(o.capital), - } - } - - fn saturating_pow(self, exp: usize) -> Self { - Self { votes: self.votes.saturating_pow(exp), capital: self.capital.saturating_pow(exp) } - } -} - -impl< - Balance: From - + Zero - + Copy - + CheckedAdd - + CheckedSub - + CheckedMul - + CheckedDiv - + Bounded - + Saturating, - > Tally -{ - /// Create a new tally. - pub fn new(vote: Vote, balance: Balance) -> Self { - let Delegations { votes, capital } = vote.conviction.votes(balance); - Self { - ayes: if vote.aye { votes } else { Zero::zero() }, - nays: if vote.aye { Zero::zero() } else { votes }, - turnout: capital, - } - } - - /// Add an account's vote into the tally. - pub fn add(&mut self, vote: AccountVote) -> Option<()> { - match vote { - AccountVote::Standard { vote, balance } => { - let Delegations { votes, capital } = vote.conviction.votes(balance); - self.turnout = self.turnout.checked_add(&capital)?; - match vote.aye { - true => self.ayes = self.ayes.checked_add(&votes)?, - false => self.nays = self.nays.checked_add(&votes)?, - } - }, - AccountVote::Split { aye, nay } => { - let aye = Conviction::None.votes(aye); - let nay = Conviction::None.votes(nay); - self.turnout = self.turnout.checked_add(&aye.capital)?.checked_add(&nay.capital)?; - self.ayes = self.ayes.checked_add(&aye.votes)?; - self.nays = self.nays.checked_add(&nay.votes)?; - }, - } - Some(()) - } - - /// Remove an account's vote from the tally. - pub fn remove(&mut self, vote: AccountVote) -> Option<()> { - match vote { - AccountVote::Standard { vote, balance } => { - let Delegations { votes, capital } = vote.conviction.votes(balance); - self.turnout = self.turnout.checked_sub(&capital)?; - match vote.aye { - true => self.ayes = self.ayes.checked_sub(&votes)?, - false => self.nays = self.nays.checked_sub(&votes)?, - } - }, - AccountVote::Split { aye, nay } => { - let aye = Conviction::None.votes(aye); - let nay = Conviction::None.votes(nay); - self.turnout = self.turnout.checked_sub(&aye.capital)?.checked_sub(&nay.capital)?; - self.ayes = self.ayes.checked_sub(&aye.votes)?; - self.nays = self.nays.checked_sub(&nay.votes)?; - }, - } - Some(()) - } - - /// Increment some amount of votes. - pub fn increase(&mut self, approve: bool, delegations: Delegations) -> Option<()> { - self.turnout = self.turnout.saturating_add(delegations.capital); - match approve { - true => self.ayes = self.ayes.saturating_add(delegations.votes), - false => self.nays = self.nays.saturating_add(delegations.votes), - } - Some(()) - } - - /// Decrement some amount of votes. - pub fn reduce(&mut self, approve: bool, delegations: Delegations) -> Option<()> { - self.turnout = self.turnout.saturating_sub(delegations.capital); - match approve { - true => self.ayes = self.ayes.saturating_sub(delegations.votes), - false => self.nays = self.nays.saturating_sub(delegations.votes), - } - Some(()) - } -} - -/// Info regarding an ongoing referendum. -#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)] -pub struct ReferendumStatus { - /// When voting on this referendum will end. - pub(crate) end: BlockNumber, - /// The hash of the proposal being voted on. - pub(crate) proposal_hash: Hash, - /// The thresholding mechanism to determine whether it passed. - pub(crate) threshold: VoteThreshold, - /// The delay (in blocks) to wait after a successful referendum before deploying. - pub(crate) delay: BlockNumber, - /// The current tally of votes in this referendum. - pub(crate) tally: Tally, -} - -/// Info regarding a referendum, present or past. -#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)] -pub enum ReferendumInfo { - /// Referendum is happening, the arg is the block number at which it will end. - Ongoing(ReferendumStatus), - /// Referendum finished at `end`, and has been `approved` or rejected. - Finished { approved: bool, end: BlockNumber }, -} - -impl ReferendumInfo { - /// Create a new instance. - pub fn new( - end: BlockNumber, - proposal_hash: Hash, - threshold: VoteThreshold, - delay: BlockNumber, - ) -> Self { - let s = ReferendumStatus { end, proposal_hash, threshold, delay, tally: Tally::default() }; - ReferendumInfo::Ongoing(s) - } -} - -/// Whether an `unvote` operation is able to make actions that are not strictly always in the -/// interest of an account. -pub enum UnvoteScope { - /// Permitted to do everything. - Any, - /// Permitted to do only the changes that do not need the owner's permission. - OnlyExpired, -} diff --git a/lib-serml/democracy/src/vote.rs b/lib-serml/democracy/src/vote.rs deleted file mode 100644 index 7b1b32ea3..000000000 --- a/lib-serml/democracy/src/vote.rs +++ /dev/null @@ -1,186 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! The vote datatype. - -use crate::{Conviction, Delegations, ReferendumIndex}; -use codec::{Decode, Encode, EncodeLike, Input, Output}; -use sp_runtime::{ - traits::{Saturating, Zero}, - RuntimeDebug, -}; -use sp_std::{convert::TryFrom, prelude::*, result::Result}; - -/// A number of lock periods, plus a vote, one way or the other. -#[derive(Copy, Clone, Eq, PartialEq, Default, RuntimeDebug)] -pub struct Vote { - pub aye: bool, - pub conviction: Conviction, -} - -impl Encode for Vote { - fn encode_to(&self, output: &mut T) { - output.push_byte(u8::from(self.conviction) | if self.aye { 0b1000_0000 } else { 0 }); - } -} - -impl EncodeLike for Vote {} - -impl Decode for Vote { - fn decode(input: &mut I) -> Result { - let b = input.read_byte()?; - Ok(Vote { - aye: (b & 0b1000_0000) == 0b1000_0000, - conviction: Conviction::try_from(b & 0b0111_1111) - .map_err(|_| codec::Error::from("Invalid conviction"))?, - }) - } -} - -/// A vote for a referendum of a particular account. -#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, RuntimeDebug)] -pub enum AccountVote { - /// A standard vote, one-way (approve or reject) with a given amount of conviction. - Standard { vote: Vote, balance: Balance }, - /// A split vote with balances given for both ways, and with no conviction, useful for - /// parachains when voting. - Split { aye: Balance, nay: Balance }, -} - -impl AccountVote { - /// Returns `Some` of the lock periods that the account is locked for, assuming that the - /// referendum passed iff `approved` is `true`. - pub fn locked_if(self, approved: bool) -> Option<(u32, Balance)> { - // winning side: can only be removed after the lock period ends. - match self { - AccountVote::Standard { vote, balance } if vote.aye == approved => - Some((vote.conviction.lock_periods(), balance)), - _ => None, - } - } - - /// The total balance involved in this vote. - pub fn balance(self) -> Balance { - match self { - AccountVote::Standard { balance, .. } => balance, - AccountVote::Split { aye, nay } => aye.saturating_add(nay), - } - } - - /// Returns `Some` with whether the vote is an aye vote if it is standard, otherwise `None` if - /// it is split. - pub fn as_standard(self) -> Option { - match self { - AccountVote::Standard { vote, .. } => Some(vote.aye), - _ => None, - } - } -} - -/// A "prior" lock, i.e. a lock for some now-forgotten reason. -#[derive(Encode, Decode, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, RuntimeDebug)] -pub struct PriorLock(BlockNumber, Balance); - -impl PriorLock { - /// Accumulates an additional lock. - pub fn accumulate(&mut self, until: BlockNumber, amount: Balance) { - self.0 = self.0.max(until); - self.1 = self.1.max(amount); - } - - pub fn locked(&self) -> Balance { - self.1 - } - - pub fn rejig(&mut self, now: BlockNumber) { - if now >= self.0 { - self.0 = Zero::zero(); - self.1 = Zero::zero(); - } - } -} - -/// An indicator for what an account is doing; it can either be delegating or voting. -#[derive(Encode, Decode, Clone, Eq, PartialEq, RuntimeDebug)] -pub enum Voting { - /// The account is voting directly. `delegations` is the total amount of post-conviction voting - /// weight that it controls from those that have delegated to it. - Direct { - /// The current votes of the account. - votes: Vec<(ReferendumIndex, AccountVote)>, - /// The total amount of delegations that this account has received. - delegations: Delegations, - /// Any pre-existing locks from past voting/delegating activity. - prior: PriorLock, - }, - /// The account is delegating `balance` of its balance to a `target` account with `conviction`. - Delegating { - balance: Balance, - target: AccountId, - conviction: Conviction, - /// The total amount of delegations that this account has received. - delegations: Delegations, - /// Any pre-existing locks from past voting/delegating activity. - prior: PriorLock, - }, -} - -impl Default - for Voting -{ - fn default() -> Self { - Voting::Direct { - votes: Vec::new(), - delegations: Default::default(), - prior: PriorLock(Zero::zero(), Default::default()), - } - } -} - -impl - Voting -{ - pub fn rejig(&mut self, now: BlockNumber) { - match self { - Voting::Direct { prior, .. } => prior, - Voting::Delegating { prior, .. } => prior, - } - .rejig(now); - } - - /// The amount of this account's balance that much currently be locked due to voting. - pub fn locked_balance(&self) -> Balance { - match self { - Voting::Direct { votes, prior, .. } => - votes.iter().map(|i| i.1.balance()).fold(prior.locked(), |a, i| a.max(i)), - Voting::Delegating { balance, .. } => *balance, - } - } - - pub fn set_common( - &mut self, - delegations: Delegations, - prior: PriorLock, - ) { - let (d, p) = match self { - Voting::Direct { ref mut delegations, ref mut prior, .. } => (delegations, prior), - Voting::Delegating { ref mut delegations, ref mut prior, .. } => (delegations, prior), - }; - *d = delegations; - *p = prior; - } -} diff --git a/lib-serml/democracy/src/vote_threshold.rs b/lib-serml/democracy/src/vote_threshold.rs deleted file mode 100644 index feaa59692..000000000 --- a/lib-serml/democracy/src/vote_threshold.rs +++ /dev/null @@ -1,118 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Voting thresholds. - -use crate::Tally; -use codec::{Decode, Encode}; -#[cfg(feature = "std")] -use serde::{Deserialize, Serialize}; -use sp_runtime::traits::{IntegerSquareRoot, Zero}; -use sp_std::ops::{Add, Div, Mul, Rem}; - -/// A means of determining if a vote is past pass threshold. -#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, sp_runtime::RuntimeDebug)] -#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] -pub enum VoteThreshold { - /// A supermajority of approvals is needed to pass this vote. - SuperMajorityApprove, - /// A supermajority of rejects is needed to fail this vote. - SuperMajorityAgainst, - /// A simple majority of approvals is needed to pass this vote. - SimpleMajority, -} - -pub trait Approved { - /// Given a `tally` of votes and a total size of `electorate`, this returns `true` if the - /// overall outcome is in favor of approval according to `self`'s threshold method. - fn approved(&self, tally: Tally, electorate: Balance) -> bool; -} - -/// Return `true` iff `n1 / d1 < n2 / d2`. `d1` and `d2` may not be zero. -fn compare_rationals< - T: Zero + Mul + Div + Rem + Ord + Copy, ->( - mut n1: T, - mut d1: T, - mut n2: T, - mut d2: T, -) -> bool { - // Uses a continued fractional representation for a non-overflowing compare. - // Detailed at https://janmr.com/blog/2014/05/comparing-rational-numbers-without-overflow/. - loop { - let q1 = n1 / d1; - let q2 = n2 / d2; - if q1 < q2 { - return true - } - if q2 < q1 { - return false - } - let r1 = n1 % d1; - let r2 = n2 % d2; - if r2.is_zero() { - return false - } - if r1.is_zero() { - return true - } - n1 = d2; - n2 = d1; - d1 = r2; - d2 = r1; - } -} - -impl< - Balance: IntegerSquareRoot - + Zero - + Ord - + Add - + Mul - + Div - + Rem - + Copy, - > Approved for VoteThreshold -{ - fn approved(&self, tally: Tally, electorate: Balance) -> bool { - let sqrt_voters = tally.turnout.integer_sqrt(); - let sqrt_electorate = electorate.integer_sqrt(); - if sqrt_voters.is_zero() { - return false - } - match *self { - VoteThreshold::SuperMajorityApprove => - compare_rationals(tally.nays, sqrt_voters, tally.ayes, sqrt_electorate), - VoteThreshold::SuperMajorityAgainst => - compare_rationals(tally.nays, sqrt_electorate, tally.ayes, sqrt_voters), - VoteThreshold::SimpleMajority => tally.ayes > tally.nays, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn should_work() { - assert!(!VoteThreshold::SuperMajorityApprove - .approved(Tally { ayes: 60, nays: 50, turnout: 110 }, 210)); - assert!(VoteThreshold::SuperMajorityApprove - .approved(Tally { ayes: 100, nays: 50, turnout: 150 }, 210)); - } -} diff --git a/lib-serml/democracy/src/weights.rs b/lib-serml/democracy/src/weights.rs deleted file mode 100644 index 6572e6288..000000000 --- a/lib-serml/democracy/src/weights.rs +++ /dev/null @@ -1,404 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Autogenerated weights for pallet_democracy -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 -//! DATE: 2021-06-19, STEPS: `[50, ]`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 - -// Executed Command: -// target/release/substrate -// benchmark -// --chain=dev -// --steps=50 -// --repeat=20 -// --pallet=pallet_democracy -// --extrinsic=* -// --execution=wasm -// --wasm-execution=compiled -// --heap-pages=4096 -// --output=./frame/democracy/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - - -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] - -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; -use sp_std::marker::PhantomData; - -/// Weight functions needed for pallet_democracy. -pub trait WeightInfo { - fn propose() -> Weight; - fn second(s: u32, ) -> Weight; - fn vote_new(r: u32, ) -> Weight; - fn vote_existing(r: u32, ) -> Weight; - fn emergency_cancel() -> Weight; - fn blacklist(p: u32, ) -> Weight; - fn external_propose(v: u32, ) -> Weight; - fn external_propose_majority() -> Weight; - fn external_propose_default() -> Weight; - fn fast_track() -> Weight; - fn veto_external(v: u32, ) -> Weight; - fn cancel_proposal(p: u32, ) -> Weight; - fn cancel_referendum() -> Weight; - fn cancel_queued(r: u32, ) -> Weight; - fn on_initialize_base(r: u32, ) -> Weight; - fn delegate(r: u32, ) -> Weight; - fn undelegate(r: u32, ) -> Weight; - fn clear_public_proposals() -> Weight; - fn note_preimage(b: u32, ) -> Weight; - fn note_imminent_preimage(b: u32, ) -> Weight; - fn reap_preimage(b: u32, ) -> Weight; - fn unlock_remove(r: u32, ) -> Weight; - fn unlock_set(r: u32, ) -> Weight; - fn remove_vote(r: u32, ) -> Weight; - fn remove_other_vote(r: u32, ) -> Weight; -} - -/// Weights for pallet_democracy using the Substrate node and recommended hardware. -pub struct SubstrateWeight(PhantomData); -impl WeightInfo for SubstrateWeight { - fn propose() -> Weight { - (71_782_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - fn second(s: u32, ) -> Weight { - (41_071_000 as Weight) - // Standard Error: 1_000 - .saturating_add((211_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn vote_new(r: u32, ) -> Weight { - (46_179_000 as Weight) - // Standard Error: 0 - .saturating_add((283_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - fn vote_existing(r: u32, ) -> Weight { - (46_169_000 as Weight) - // Standard Error: 0 - .saturating_add((284_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - fn emergency_cancel() -> Weight { - (28_615_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - fn blacklist(p: u32, ) -> Weight { - (80_711_000 as Weight) - // Standard Error: 4_000 - .saturating_add((590_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(6 as Weight)) - } - fn external_propose(v: u32, ) -> Weight { - (13_197_000 as Weight) - // Standard Error: 0 - .saturating_add((90_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn external_propose_majority() -> Weight { - (2_712_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn external_propose_default() -> Weight { - (2_680_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn fast_track() -> Weight { - (28_340_000 as Weight) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - fn veto_external(v: u32, ) -> Weight { - (28_894_000 as Weight) - // Standard Error: 0 - .saturating_add((133_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - fn cancel_proposal(p: u32, ) -> Weight { - (54_339_000 as Weight) - // Standard Error: 1_000 - .saturating_add((561_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - fn cancel_referendum() -> Weight { - (17_183_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn cancel_queued(r: u32, ) -> Weight { - (30_500_000 as Weight) - // Standard Error: 1_000 - .saturating_add((1_730_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - fn on_initialize_base(r: u32, ) -> Weight { - (7_788_000 as Weight) - // Standard Error: 4_000 - .saturating_add((5_422_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - } - fn delegate(r: u32, ) -> Weight { - (55_676_000 as Weight) - // Standard Error: 5_000 - .saturating_add((7_553_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) - } - fn undelegate(r: u32, ) -> Weight { - (23_908_000 as Weight) - // Standard Error: 5_000 - .saturating_add((7_551_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) - } - fn clear_public_proposals() -> Weight { - (3_023_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn note_preimage(b: u32, ) -> Weight { - (44_069_000 as Weight) - // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn note_imminent_preimage(b: u32, ) -> Weight { - (28_457_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn reap_preimage(b: u32, ) -> Weight { - (39_646_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn unlock_remove(r: u32, ) -> Weight { - (39_499_000 as Weight) - // Standard Error: 0 - .saturating_add((148_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - fn unlock_set(r: u32, ) -> Weight { - (37_340_000 as Weight) - // Standard Error: 0 - .saturating_add((266_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - fn remove_vote(r: u32, ) -> Weight { - (20_397_000 as Weight) - // Standard Error: 0 - .saturating_add((259_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - fn remove_other_vote(r: u32, ) -> Weight { - (20_425_000 as Weight) - // Standard Error: 0 - .saturating_add((156_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } -} - -// For backwards compatibility and tests -impl WeightInfo for () { - fn propose() -> Weight { - (71_782_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - fn second(s: u32, ) -> Weight { - (41_071_000 as Weight) - // Standard Error: 1_000 - .saturating_add((211_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn vote_new(r: u32, ) -> Weight { - (46_179_000 as Weight) - // Standard Error: 0 - .saturating_add((283_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - fn vote_existing(r: u32, ) -> Weight { - (46_169_000 as Weight) - // Standard Error: 0 - .saturating_add((284_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - fn emergency_cancel() -> Weight { - (28_615_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - fn blacklist(p: u32, ) -> Weight { - (80_711_000 as Weight) - // Standard Error: 4_000 - .saturating_add((590_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(6 as Weight)) - } - fn external_propose(v: u32, ) -> Weight { - (13_197_000 as Weight) - // Standard Error: 0 - .saturating_add((90_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn external_propose_majority() -> Weight { - (2_712_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn external_propose_default() -> Weight { - (2_680_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn fast_track() -> Weight { - (28_340_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - fn veto_external(v: u32, ) -> Weight { - (28_894_000 as Weight) - // Standard Error: 0 - .saturating_add((133_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - fn cancel_proposal(p: u32, ) -> Weight { - (54_339_000 as Weight) - // Standard Error: 1_000 - .saturating_add((561_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - fn cancel_referendum() -> Weight { - (17_183_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn cancel_queued(r: u32, ) -> Weight { - (30_500_000 as Weight) - // Standard Error: 1_000 - .saturating_add((1_730_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - fn on_initialize_base(r: u32, ) -> Weight { - (7_788_000 as Weight) - // Standard Error: 4_000 - .saturating_add((5_422_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - } - fn delegate(r: u32, ) -> Weight { - (55_676_000 as Weight) - // Standard Error: 5_000 - .saturating_add((7_553_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) - } - fn undelegate(r: u32, ) -> Weight { - (23_908_000 as Weight) - // Standard Error: 5_000 - .saturating_add((7_551_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(r as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(r as Weight))) - } - fn clear_public_proposals() -> Weight { - (3_023_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn note_preimage(b: u32, ) -> Weight { - (44_069_000 as Weight) - // Standard Error: 0 - .saturating_add((3_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn note_imminent_preimage(b: u32, ) -> Weight { - (28_457_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn reap_preimage(b: u32, ) -> Weight { - (39_646_000 as Weight) - // Standard Error: 0 - .saturating_add((2_000 as Weight).saturating_mul(b as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn unlock_remove(r: u32, ) -> Weight { - (39_499_000 as Weight) - // Standard Error: 0 - .saturating_add((148_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - fn unlock_set(r: u32, ) -> Weight { - (37_340_000 as Weight) - // Standard Error: 0 - .saturating_add((266_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - fn remove_vote(r: u32, ) -> Weight { - (20_397_000 as Weight) - // Standard Error: 0 - .saturating_add((259_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - fn remove_other_vote(r: u32, ) -> Weight { - (20_425_000 as Weight) - // Standard Error: 0 - .saturating_add((156_000 as Weight).saturating_mul(r as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } -} diff --git a/lib-serml/serp/serp-staking/Cargo.toml b/lib-serml/serp/serp-staking/Cargo.toml deleted file mode 100644 index 58ef7d030..000000000 --- a/lib-serml/serp/serp-staking/Cargo.toml +++ /dev/null @@ -1,83 +0,0 @@ -[package] -name = "serp-staking" -version = "0.9.0" -authors = ["Setheum Labs"] -edition = "2018" - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -static_assertions = "1.1.0" -serde = { version = "1.0.126", optional = true } -codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } - -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -sp-io ={ default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8"} -sp-staking = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8"} -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8"} -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8"} -pallet-session = { default-features = false, features = ["historical"], git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8"} -pallet-authorship = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8"} -sp-application-crypto = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8"} -frame-election-provider-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8"} -log = { version = "0.4.14", default-features = false } -paste = "1.0" - -# orml dependencies -orml-traits = { path = "../../../lib-openrml/traits", default-features = false } -orml-utilities = { path = "../../../lib-openrml/utilities", default-features = false } -orml-tokens = { path = "../../../lib-openrml/tokens", default-features = false } - -# local dependencies -primitives = { package = "setheum-primitives", path = "../../../primitives", default-features = false } -support = { package = "setheum-support", path = "../../support", default-features = false } - -# Optional imports for benchmarking -frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false, optional = true } -rand_chacha = { version = "0.2", default-features = false, optional = true } - -[dev-dependencies] -sp-storage = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -sp-tracing = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -pallet-staking-reward-curve = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -substrate-test-utils = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -frame-election-provider-support = { features = ["runtime-benchmarks"], git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -rand_chacha = { version = "0.2" } -parking_lot = "0.11.1" -hex = "0.4" -orml-currencies = { path = "../../../lib-openrml/currencies" } - -[features] -default = ["std"] -std = [ - "serde", - "codec/std", - "sp-std/std", - "sp-io/std", - "frame-support/std", - "sp-runtime/std", - "sp-staking/std", - "pallet-session/std", - "frame-system/std", - "pallet-authorship/std", - "sp-application-crypto/std", - "log/std", - "frame-election-provider-support/std", - "orml-tokens/std", - "orml-traits/std", - "orml-utilities/std", - "primitives/std", - "support/std", -] -runtime-benchmarks = [ - "frame-benchmarking", - "frame-election-provider-support/runtime-benchmarks", - "rand_chacha", -] -try-runtime = ["frame-support/try-runtime"] diff --git a/lib-serml/serp/serp-staking/README.md b/lib-serml/serp/serp-staking/README.md deleted file mode 100644 index ee0a6b3f8..000000000 --- a/lib-serml/serp/serp-staking/README.md +++ /dev/null @@ -1,246 +0,0 @@ -# Staking Module - -Serp Staking supports multicurrency rewards, such that in Setheum, staking the -Dinar (DNAR) will reward the Dirham (DRAM) and the Setter (SETR). - -The Staking module is used to manage funds at stake by network maintainers. - -- [`staking::Config`](https://docs.rs/serp-staking/latest/serp_staking/trait.Config.html) -- [`Call`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html) -- [`Module`](https://docs.rs/serp-staking/latest/serp_staking/struct.Module.html) - -## Overview - -The Staking module is the means by which a set of network maintainers (known as _authorities_ in -some contexts and _validators_ in others) are chosen based upon those who voluntarily place -funds under deposit. Under deposit, those funds are rewarded under normal operation but are held -at pain of _slash_ (expropriation) should the staked maintainer be found not to be discharging -its duties properly. - -### Terminology - - -- Staking: The process of locking up funds for some time, placing them at risk of slashing - (loss) in order to become a rewarded maintainer of the network. -- Validating: The process of running a node to actively maintain the network, either by - producing blocks or guaranteeing finality of the chain. -- Nominating: The process of placing staked funds behind one or more validators in order to - share in any reward, and punishment, they take. -- Stash account: The account holding an owner's funds used for staking. -- Controller account: The account that controls an owner's funds for staking. -- Era: A (whole) number of sessions, which is the period that the validator set (and each - validator's active nominator set) is recalculated and where rewards are paid out. -- Slash: The punishment of a staker by reducing its funds. - -### Goals - - -The staking system in Substrate NPoS is designed to make the following possible: - -- Stake funds that are controlled by a cold wallet. -- Withdraw some, or deposit more, funds without interrupting the role of an entity. -- Switch between roles (nominator, validator, idle) with minimal overhead. - -### Scenarios - -#### Staking - -Almost any interaction with the Staking module requires a process of _**bonding**_ (also known -as being a _staker_). To become *bonded*, a fund-holding account known as the _stash account_, -which holds some or all of the funds that become frozen in place as part of the staking process, -is paired with an active **controller** account, which issues instructions on how they shall be -used. - -An account pair can become bonded using the [`bond`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html#variant.bond) call. - -Stash accounts can change their associated controller using the -[`set_controller`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html#variant.set_controller) call. - -There are three possible roles that any staked account pair can be in: `Validator`, `Nominator` -and `Idle` (defined in [`StakerStatus`](https://docs.rs/serp-staking/latest/serp_staking/enum.StakerStatus.html)). There are three -corresponding instructions to change between roles, namely: -[`validate`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html#variant.validate), -[`nominate`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html#variant.nominate), and [`chill`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html#variant.chill). - -#### Validating - -A **validator** takes the role of either validating blocks or ensuring their finality, -maintaining the veracity of the network. A validator should avoid both any sort of malicious -misbehavior and going offline. Bonded accounts that state interest in being a validator do NOT -get immediately chosen as a validator. Instead, they are declared as a _candidate_ and they -_might_ get elected at the _next era_ as a validator. The result of the election is determined -by nominators and their votes. - -An account can become a validator candidate via the -[`validate`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html#variant.validate) call. - -#### Nomination - -A **nominator** does not take any _direct_ role in maintaining the network, instead, it votes on -a set of validators to be elected. Once interest in nomination is stated by an account, it -takes effect at the next election round. The funds in the nominator's stash account indicate the -_weight_ of its vote. Both the rewards and any punishment that a validator earns are shared -between the validator and its nominators. This rule incentivizes the nominators to NOT vote for -the misbehaving/offline validators as much as possible, simply because the nominators will also -lose funds if they vote poorly. - -An account can become a nominator via the [`nominate`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html#variant.nominate) call. - -#### Rewards and Slash - -The **reward and slashing** procedure is the core of the Staking module, attempting to _embrace -valid behavior_ while _punishing any misbehavior or lack of availability_. - -Rewards must be claimed for each era before it gets too old by `$HISTORY_DEPTH` using the -`payout_stakers` call. Any account can call `payout_stakers`, which pays the reward to the -validator as well as its nominators. Only the [`Config::MaxNominatorRewardedPerValidator`] -biggest stakers can claim their reward. This is to limit the i/o cost to mutate storage for each -nominator's account. - -Slashing can occur at any point in time, once misbehavior is reported. Once slashing is -determined, a value is deducted from the balance of the validator and all the nominators who -voted for this validator (values are deducted from the _stash_ account of the slashed entity). - -Slashing logic is further described in the documentation of the `slashing` module. - -Similar to slashing, rewards are also shared among a validator and its associated nominators. -Yet, the reward funds are not always transferred to the stash account and can be configured. See -[Reward Calculation](https://docs.rs/serp-staking/latest/serp_staking/#reward-calculation) for more details. - -#### Chilling - -Finally, any of the roles above can choose to step back temporarily and just chill for a while. -This means that if they are a nominator, they will not be considered as voters anymore and if -they are validators, they will no longer be a candidate for the next election. - -An account can step back via the [`chill`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html#variant.chill) call. - -### Session managing - -The module implement the trait `SessionManager`. Which is the only API to query new validator -set and allowing these validator set to be rewarded once their era is ended. - -## Interface - -### Dispatchable Functions - -The dispatchable functions of the Staking module enable the steps needed for entities to accept -and change their role, alongside some helper functions to get/set the metadata of the module. - -### Public Functions - -The Staking module contains many public storage items and (im)mutable functions. - -## Usage - -### Example: Rewarding a validator by id. - -```rust -use frame_support::{decl_module, dispatch}; -use frame_system::ensure_signed; -use serp_staking::{self as staking}; - -pub trait Config: staking::Config {} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - /// Reward a validator. - #[weight = 0] - pub fn reward_myself(origin) -> dispatch::DispatchResult { - let reported = ensure_signed(origin)?; - >::reward_by_ids(vec![(reported, 10)]); - Ok(()) - } - } -} -``` - -## Implementation Details - -### Era payout - -The era payout is computed using yearly inflation curve defined at -[`T::RewardCurve`](https://docs.rs/serp-staking/latest/serp_staking/trait.Config.html#associatedtype.RewardCurve) as such: - -```nocompile -staker_payout = yearly_inflation(npos_token_staked / total_tokens) * total_tokens / era_per_year -``` -This payout is used to reward stakers as defined in next section - -### Reward Calculation - -Validators and nominators are rewarded at the end of each era. The total reward of an era is -calculated using the era duration and the staking rate (the total amount of tokens staked by -nominators and validators, divided by the total token supply). It aims to incentivize toward a -defined staking rate. The full specification can be found -[here](https://research.web3.foundation/en/latest/polkadot/economics/1-token-economics.html#inflation-model). - -Total reward is split among validators and their nominators depending on the number of points -they received during the era. Points are added to a validator using -[`reward_by_ids`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html#variant.reward_by_ids) or -[`reward_by_indices`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html#variant.reward_by_indices). - -[`Module`](https://docs.rs/serp-staking/latest/serp_staking/struct.Module.html) implements -[`pallet_authorship::EventHandler`](https://docs.rs/pallet-authorship/latest/pallet_authorship/trait.EventHandler.html) to add reward -points to block producer and block producer of referenced uncles. - -The validator and its nominator split their reward as following: - -The validator can declare an amount, named -[`commission`](https://docs.rs/serp-staking/latest/serp_staking/struct.ValidatorPrefs.html#structfield.commission), that does not get shared -with the nominators at each reward payout through its -[`ValidatorPrefs`](https://docs.rs/serp-staking/latest/serp_staking/struct.ValidatorPrefs.html). This value gets deducted from the total reward -that is paid to the validator and its nominators. The remaining portion is split among the -validator and all of the nominators that nominated the validator, proportional to the value -staked behind this validator (_i.e._ dividing the -[`own`](https://docs.rs/serp-staking/latest/serp_staking/struct.Exposure.html#structfield.own) or -[`others`](https://docs.rs/serp-staking/latest/serp_staking/struct.Exposure.html#structfield.others) by -[`total`](https://docs.rs/serp-staking/latest/serp_staking/struct.Exposure.html#structfield.total) in [`Exposure`](https://docs.rs/serp-staking/latest/serp_staking/struct.Exposure.html)). - -All entities who receive a reward have the option to choose their reward destination through the -[`Payee`](https://docs.rs/serp-staking/latest/serp_staking/struct.Payee.html) storage item (see -[`set_payee`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html#variant.set_payee)), to be one of the following: - -- Controller account, (obviously) not increasing the staked value. -- Stash account, not increasing the staked value. -- Stash account, also increasing the staked value. - -### Additional Fund Management Operations - -Any funds already placed into stash can be the target of the following operations: - -The controller account can free a portion (or all) of the funds using the -[`unbond`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html#variant.unbond) call. Note that the funds are not immediately -accessible. Instead, a duration denoted by [`BondingDuration`](https://docs.rs/serp-staking/latest/serp_staking/trait.Config.html#associatedtype.BondingDuration) -(in number of eras) must pass until the funds can actually be removed. Once the -`BondingDuration` is over, the [`withdraw_unbonded`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html#variant.withdraw_unbonded) -call can be used to actually withdraw the funds. - -Note that there is a limitation to the number of fund-chunks that can be scheduled to be -unlocked in the future via [`unbond`](https://docs.rs/serp-staking/latest/serp_staking/enum.Call.html#variant.unbond). In case this maximum -(`MAX_UNLOCKING_CHUNKS`) is reached, the bonded account _must_ first wait until a successful -call to `withdraw_unbonded` to remove some of the chunks. - -### Election Algorithm - -The current election algorithm is implemented based on Phragmén. The reference implementation -can be found [here](https://github.com/w3f/consensus/tree/master/NPoS). - -The election algorithm, aside from electing the validators with the most stake value and votes, -tries to divide the nominator votes among candidates in an equal manner. To further assure this, -an optional post-processing can be applied that iteratively normalizes the nominator staked -values until the total difference among votes of a particular nominator are less than a -threshold. - -## GenesisConfig - -The Staking module depends on the [`GenesisConfig`](https://docs.rs/serp-staking/latest/serp_staking/struct.GenesisConfig.html). The -`GenesisConfig` is optional and allow to set some initial stakers. - -## Related Modules - -- [Balances](https://docs.rs/pallet-balances/latest/pallet_balances/): Used to manage values at stake. -- [Session](https://docs.rs/pallet-session/latest/pallet_session/): Used to manage sessions. Also, a list of new - validators is stored in the Session module's `Validators` at the end of each era. - -License: Apache-2.0 diff --git a/lib-serml/serp/serp-staking/reward-curve/Cargo.toml b/lib-serml/serp/serp-staking/reward-curve/Cargo.toml deleted file mode 100644 index f7e97254c..000000000 --- a/lib-serml/serp/serp-staking/reward-curve/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "serp-staking-reward-curve" -version = "0.9.0" -authors = ["Setheum Labs"] - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[lib] -proc-macro = true - -[dependencies] -syn = { version = "1.0.58", features = ["full", "visit"] } -quote = "1.0.3" -proc-macro2 = "1.0.6" -proc-macro-crate = "1.0.0" - -[dev-dependencies] -sp-runtime = { version = "4.0.0-dev", path = "../../../primitives/runtime" } diff --git a/lib-serml/serp/serp-staking/reward-curve/src/lib.rs b/lib-serml/serp/serp-staking/reward-curve/src/lib.rs deleted file mode 100644 index b2f2c42bc..000000000 --- a/lib-serml/serp/serp-staking/reward-curve/src/lib.rs +++ /dev/null @@ -1,446 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Proc macro to generate the reward curve functions and tests. - -mod log; - -use log::log2; -use proc_macro::TokenStream; -use proc_macro2::{Span, TokenStream as TokenStream2}; -use proc_macro_crate::{crate_name, FoundCrate}; -use quote::{quote, ToTokens}; -use std::convert::TryInto; -use syn::parse::{Parse, ParseStream}; - -/// Accepts a number of expressions to create a instance of PiecewiseLinear which represents the -/// NPoS curve (as detailed -/// [here](https://research.web3.foundation/en/latest/polkadot/Token%20Economics.html#inflation-model)) -/// for those parameters. Parameters are: -/// - `min_inflation`: the minimal amount to be rewarded between validators, expressed as a fraction -/// of total issuance. Known as `I_0` in the literature. -/// Expressed in millionth, must be between 0 and 1_000_000. -/// -/// - `max_inflation`: the maximum amount to be rewarded between validators, expressed as a fraction -/// of total issuance. This is attained only when `ideal_stake` is achieved. -/// Expressed in millionth, must be between min_inflation and 1_000_000. -/// -/// - `ideal_stake`: the fraction of total issued tokens that should be actively staked behind -/// validators. Known as `x_ideal` in the literature. -/// Expressed in millionth, must be between 0_100_000 and 0_900_000. -/// -/// - `falloff`: Known as `decay_rate` in the literature. A co-efficient dictating the strength of -/// the global incentivization to get the `ideal_stake`. A higher number results in less typical -/// inflation at the cost of greater volatility for validators. -/// Expressed in millionth, must be between 0 and 1_000_000. -/// -/// - `max_piece_count`: The maximum number of pieces in the curve. A greater number uses more -/// resources but results in higher accuracy. -/// Must be between 2 and 1_000. -/// -/// - `test_precision`: The maximum error allowed in the generated test. -/// Expressed in millionth, must be between 0 and 1_000_000. -/// -/// # Example -/// -/// ``` -/// # fn main() {} -/// use sp_runtime::curve::PiecewiseLinear; -/// -/// serp_staking_reward_curve::build! { -/// const I_NPOS: PiecewiseLinear<'static> = curve!( -/// min_inflation: 0_025_000, -/// max_inflation: 0_100_000, -/// ideal_stake: 0_500_000, -/// falloff: 0_050_000, -/// max_piece_count: 40, -/// test_precision: 0_005_000, -/// ); -/// } -/// ``` -#[proc_macro] -pub fn build(input: TokenStream) -> TokenStream { - let input = syn::parse_macro_input!(input as INposInput); - - let points = compute_points(&input); - - let declaration = generate_piecewise_linear(points); - let test_module = generate_test_module(&input); - - let imports = match crate_name("sp-runtime") { - Ok(FoundCrate::Itself) => quote!( - extern crate sp_runtime as _sp_runtime; - ), - Ok(FoundCrate::Name(sp_runtime)) => { - let ident = syn::Ident::new(&sp_runtime, Span::call_site()); - quote!( extern crate #ident as _sp_runtime; ) - }, - Err(e) => syn::Error::new(Span::call_site(), e).to_compile_error(), - }; - - let const_name = input.ident; - let const_type = input.typ; - - quote!( - const #const_name: #const_type = { - #imports - #declaration - }; - #test_module - ) - .into() -} - -const MILLION: u32 = 1_000_000; - -mod keyword { - syn::custom_keyword!(curve); - syn::custom_keyword!(min_inflation); - syn::custom_keyword!(max_inflation); - syn::custom_keyword!(ideal_stake); - syn::custom_keyword!(falloff); - syn::custom_keyword!(max_piece_count); - syn::custom_keyword!(test_precision); -} - -struct INposInput { - ident: syn::Ident, - typ: syn::Type, - min_inflation: u32, - ideal_stake: u32, - max_inflation: u32, - falloff: u32, - max_piece_count: u32, - test_precision: u32, -} - -struct Bounds { - min: u32, - min_strict: bool, - max: u32, - max_strict: bool, -} - -impl Bounds { - fn check(&self, value: u32) -> bool { - let wrong = (self.min_strict && value <= self.min) || - (!self.min_strict && value < self.min) || - (self.max_strict && value >= self.max) || - (!self.max_strict && value > self.max); - - !wrong - } -} - -impl core::fmt::Display for Bounds { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!( - f, - "{}{:07}; {:07}{}", - if self.min_strict { "]" } else { "[" }, - self.min, - self.max, - if self.max_strict { "[" } else { "]" }, - ) - } -} - -fn parse_field( - input: ParseStream, - bounds: Bounds, -) -> syn::Result { - ::parse(input)?; - ::parse(input)?; - let value_lit = syn::LitInt::parse(input)?; - let value: u32 = value_lit.base10_parse()?; - if !bounds.check(value) { - return Err(syn::Error::new( - value_lit.span(), - format!( - "Invalid {}: {}, must be in {}", - Token::default().to_token_stream(), - value, - bounds, - ), - )) - } - - Ok(value) -} - -impl Parse for INposInput { - fn parse(input: ParseStream) -> syn::Result { - let args_input; - - ::parse(input)?; - let ident = ::parse(input)?; - ::parse(input)?; - let typ = ::parse(input)?; - ::parse(input)?; - ::parse(input)?; - ::parse(input)?; - syn::parenthesized!(args_input in input); - ::parse(input)?; - - if !input.is_empty() { - return Err(input.error("expected end of input stream, no token expected")) - } - - let min_inflation = parse_field::( - &args_input, - Bounds { min: 0, min_strict: true, max: 1_000_000, max_strict: false }, - )?; - ::parse(&args_input)?; - let max_inflation = parse_field::( - &args_input, - Bounds { min: min_inflation, min_strict: true, max: 1_000_000, max_strict: false }, - )?; - ::parse(&args_input)?; - let ideal_stake = parse_field::( - &args_input, - Bounds { min: 0_100_000, min_strict: false, max: 0_900_000, max_strict: false }, - )?; - ::parse(&args_input)?; - let falloff = parse_field::( - &args_input, - Bounds { min: 0_010_000, min_strict: false, max: 1_000_000, max_strict: false }, - )?; - ::parse(&args_input)?; - let max_piece_count = parse_field::( - &args_input, - Bounds { min: 2, min_strict: false, max: 1_000, max_strict: false }, - )?; - ::parse(&args_input)?; - let test_precision = parse_field::( - &args_input, - Bounds { min: 0, min_strict: false, max: 1_000_000, max_strict: false }, - )?; - >::parse(&args_input)?; - - if !args_input.is_empty() { - return Err(args_input.error("expected end of input stream, no token expected")) - } - - Ok(Self { - ident, - typ, - min_inflation, - ideal_stake, - max_inflation, - falloff, - max_piece_count, - test_precision, - }) - } -} - -struct INPoS { - i_0: u32, - i_ideal_times_x_ideal: u32, - i_ideal: u32, - x_ideal: u32, - d: u32, -} - -impl INPoS { - fn from_input(input: &INposInput) -> Self { - INPoS { - i_0: input.min_inflation, - i_ideal: (input.max_inflation as u64 * MILLION as u64 / input.ideal_stake as u64) - .try_into() - .unwrap(), - i_ideal_times_x_ideal: input.max_inflation, - x_ideal: input.ideal_stake, - d: input.falloff, - } - } - - // calculates x from: - // y = i_0 + (i_ideal * x_ideal - i_0) * 2^((x_ideal - x)/d) - // See web3 docs for the details - fn compute_opposite_after_x_ideal(&self, y: u32) -> u32 { - if y == self.i_0 { - return u32::MAX - } - // Note: the log term calculated here represents a per_million value - let log = log2(self.i_ideal_times_x_ideal - self.i_0, y - self.i_0); - - let term: u32 = ((self.d as u64 * log as u64) / 1_000_000).try_into().unwrap(); - - self.x_ideal + term - } -} - -fn compute_points(input: &INposInput) -> Vec<(u32, u32)> { - let inpos = INPoS::from_input(input); - - let mut points = vec![(0, inpos.i_0), (inpos.x_ideal, inpos.i_ideal_times_x_ideal)]; - - // For each point p: (next_p.0 - p.0) < segment_length && (next_p.1 - p.1) < segment_length. - // This ensures that the total number of segment doesn't overflow max_piece_count. - let max_length = (input.max_inflation - input.min_inflation + 1_000_000 - inpos.x_ideal) / - (input.max_piece_count - 1); - - let mut delta_y = max_length; - let mut y = input.max_inflation; - - // The algorithm divide the curve in segment with vertical len and horizontal len less - // than `max_length`. This is not very accurate in case of very consequent steep. - while delta_y != 0 { - let next_y = y - delta_y; - - if next_y <= input.min_inflation { - delta_y = delta_y.saturating_sub(1); - continue - } - - let next_x = inpos.compute_opposite_after_x_ideal(next_y); - - if (next_x - points.last().unwrap().0) > max_length { - delta_y = delta_y.saturating_sub(1); - continue - } - - if next_x >= 1_000_000 { - let prev = points.last().unwrap(); - // Compute the y corresponding to x=1_000_000 using the this point and the previous one. - - let delta_y: u32 = ((next_x - 1_000_000) as u64 * (prev.1 - next_y) as u64 / - (next_x - prev.0) as u64) - .try_into() - .unwrap(); - - let y = next_y + delta_y; - - points.push((1_000_000, y)); - return points - } - points.push((next_x, next_y)); - y = next_y; - } - - points.push((1_000_000, inpos.i_0)); - - points -} - -fn generate_piecewise_linear(points: Vec<(u32, u32)>) -> TokenStream2 { - let mut points_tokens = quote!(); - - let max = points - .iter() - .map(|&(_, x)| x) - .max() - .unwrap_or(0) - .checked_mul(1_000) - // clip at 1.0 for sanity only since it'll panic later if too high. - .unwrap_or(1_000_000_000); - - for (x, y) in points { - let error = || { - panic!( - "Generated reward curve approximation doesn't fit into [0, 1] -> [0, 1] because \ - of point: - x = {:07} per million - y = {:07} per million", - x, y - ) - }; - - let x_perbill = x.checked_mul(1_000).unwrap_or_else(error); - let y_perbill = y.checked_mul(1_000).unwrap_or_else(error); - - points_tokens.extend(quote!( - ( - _sp_runtime::Perbill::from_parts(#x_perbill), - _sp_runtime::Perbill::from_parts(#y_perbill), - ), - )); - } - - quote!( - _sp_runtime::curve::PiecewiseLinear::<'static> { - points: & [ #points_tokens ], - maximum: _sp_runtime::Perbill::from_parts(#max), - } - ) -} - -fn generate_test_module(input: &INposInput) -> TokenStream2 { - let inpos = INPoS::from_input(input); - - let ident = &input.ident; - let precision = input.test_precision; - let i_0 = inpos.i_0 as f64 / MILLION as f64; - let i_ideal_times_x_ideal = inpos.i_ideal_times_x_ideal as f64 / MILLION as f64; - let i_ideal = inpos.i_ideal as f64 / MILLION as f64; - let x_ideal = inpos.x_ideal as f64 / MILLION as f64; - let d = inpos.d as f64 / MILLION as f64; - let max_piece_count = input.max_piece_count; - - quote!( - #[cfg(test)] - mod __serp_staking_reward_curve_test_module { - fn i_npos(x: f64) -> f64 { - if x <= #x_ideal { - #i_0 + x * (#i_ideal - #i_0 / #x_ideal) - } else { - #i_0 + (#i_ideal_times_x_ideal - #i_0) * 2_f64.powf((#x_ideal - x) / #d) - } - } - - const MILLION: u32 = 1_000_000; - - #[test] - fn reward_curve_precision() { - for &base in [MILLION, u32::MAX].iter() { - let number_of_check = 100_000.min(base); - for check_index in 0..=number_of_check { - let i = (check_index as u64 * base as u64 / number_of_check as u64) as u32; - let x = i as f64 / base as f64; - let float_res = (i_npos(x) * base as f64).round() as u32; - let int_res = super::#ident.calculate_for_fraction_times_denominator(i, base); - let err = ( - (float_res.max(int_res) - float_res.min(int_res)) as u64 - * MILLION as u64 - / float_res as u64 - ) as u32; - if err > #precision { - panic!("\n\ - Generated reward curve approximation differ from real one:\n\t\ - for i = {} and base = {}, f(i/base) * base = {},\n\t\ - but approximation = {},\n\t\ - err = {:07} millionth,\n\t\ - try increase the number of segment: {} or the test_error: {}.\n", - i, base, float_res, int_res, err, #max_piece_count, #precision - ); - } - } - } - } - - #[test] - fn reward_curve_piece_count() { - assert!( - super::#ident.points.len() as u32 - 1 <= #max_piece_count, - "Generated reward curve approximation is invalid: \ - has more points than specified, please fill an issue." - ); - } - } - ) -} diff --git a/lib-serml/serp/serp-staking/reward-curve/src/log.rs b/lib-serml/serp/serp-staking/reward-curve/src/log.rs deleted file mode 100644 index c196aaaa3..000000000 --- a/lib-serml/serp/serp-staking/reward-curve/src/log.rs +++ /dev/null @@ -1,127 +0,0 @@ -use std::convert::TryInto; - -/// Simple u32 power of 2 function - simply uses a bit shift -macro_rules! pow2 { - ($n:expr) => { - 1_u32 << $n - }; -} - -/// Returns the k_th per_million taylor term for a log2 function -fn taylor_term(k: u32, y_num: u128, y_den: u128) -> u32 { - let _2_div_ln_2: u128 = 2_885_390u128; - - if k == 0 { - (_2_div_ln_2 * (y_num).pow(1) / (y_den).pow(1)).try_into().unwrap() - } else { - let mut res = _2_div_ln_2 * (y_num).pow(3) / (y_den).pow(3); - for _ in 1..k { - res = res * (y_num).pow(2) / (y_den).pow(2); - } - res /= 2 * k as u128 + 1; - - res.try_into().unwrap() - } -} - -/// Performs a log2 operation using a rational fraction -/// -/// result = log2(p/q) where p/q is bound to [1, 1_000_000] -/// Where: -/// * q represents the numerator of the rational fraction input -/// * p represents the denominator of the rational fraction input -/// * result represents a per-million output of log2 -pub fn log2(p: u32, q: u32) -> u32 { - assert!(p >= q); // keep p/q bound to [1, inf) - assert!(p <= u32::MAX / 2); - - // This restriction should not be mandatory. But function is only tested and used for this. - assert!(p <= 1_000_000); - assert!(q <= 1_000_000); - - // log2(1) = 0 - if p == q { - return 0 - } - - // find the power of 2 where q * 2^n <= p < q * 2^(n+1) - let mut n = 0u32; - while (p < pow2!(n) * q) || (p >= pow2!(n + 1) * q) { - n += 1; - assert!(n < 32); // cannot represent 2^32 in u32 - } - assert!(p < pow2!(n + 1) * q); - - let y_num: u32 = p - pow2!(n) * q; - let y_den: u32 = p + pow2!(n) * q; - - // Loop through each Taylor series coefficient until it reaches 10^-6 - let mut res = n * 1_000_000u32; - let mut k = 0; - loop { - let term = taylor_term(k, y_num.into(), y_den.into()); - if term == 0 { - break - } - - res += term; - k += 1; - } - - res -} - -#[test] -fn test_log() { - let div = 1_000; - for p in 0..=div { - for q in 1..=p { - let p: u32 = (1_000_000 as u64 * p as u64 / div as u64).try_into().unwrap(); - let q: u32 = (1_000_000 as u64 * q as u64 / div as u64).try_into().unwrap(); - - let res = -(log2(p, q) as i64); - let expected = ((q as f64 / p as f64).log(2.0) * 1_000_000 as f64).round() as i64; - assert!((res - expected).abs() <= 6); - } - } -} - -#[test] -#[should_panic] -fn test_log_p_must_be_greater_than_q() { - let p: u32 = 1_000; - let q: u32 = 1_001; - let _ = log2(p, q); -} - -#[test] -#[should_panic] -fn test_log_p_upper_bound() { - let p: u32 = 1_000_001; - let q: u32 = 1_000_000; - let _ = log2(p, q); -} - -#[test] -#[should_panic] -fn test_log_q_limit() { - let p: u32 = 1_000_000; - let q: u32 = 0; - let _ = log2(p, q); -} - -#[test] -fn test_log_of_one_boundary() { - let p: u32 = 1_000_000; - let q: u32 = 1_000_000; - assert_eq!(log2(p, q), 0); -} - -#[test] -fn test_log_of_largest_input() { - let p: u32 = 1_000_000; - let q: u32 = 1; - let expected = 19_931_568; - let tolerance = 100; - assert!((log2(p, q) as i32 - expected as i32).abs() < tolerance); -} diff --git a/lib-serml/serp/serp-staking/reward-curve/tests/test.rs b/lib-serml/serp/serp-staking/reward-curve/tests/test.rs deleted file mode 100644 index 3c2795d8d..000000000 --- a/lib-serml/serp/serp-staking/reward-curve/tests/test.rs +++ /dev/null @@ -1,45 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Test crate for serp-staking-reward-curve. Allows to test for procedural macro. -//! See tests directory. - -mod test_small_falloff { - serp_staking_reward_curve::build! { - const REWARD_CURVE: sp_runtime::curve::PiecewiseLinear<'static> = curve!( - min_inflation: 0_020_000, - max_inflation: 0_200_000, - ideal_stake: 0_600_000, - falloff: 0_010_000, - max_piece_count: 200, - test_precision: 0_005_000, - ); - } -} - -mod test_big_falloff { - serp_staking_reward_curve::build! { - const REWARD_CURVE: sp_runtime::curve::PiecewiseLinear<'static> = curve!( - min_inflation: 0_100_000, - max_inflation: 0_400_000, - ideal_stake: 0_400_000, - falloff: 1_000_000, - max_piece_count: 40, - test_precision: 0_005_000, - ); - } -} diff --git a/lib-serml/serp/serp-staking/reward-fn/Cargo.toml b/lib-serml/serp/serp-staking/reward-fn/Cargo.toml deleted file mode 100644 index 4fcc099b4..000000000 --- a/lib-serml/serp/serp-staking/reward-fn/Cargo.toml +++ /dev/null @@ -1,20 +0,0 @@ -[package] -name = "serp-staking-reward-fn" -version = "0.9.0" -authors = ["Setheum Labs"] - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[lib] - -[dependencies] -sp-arithmetic = { default-features = false, version = "3.0.0", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8"} -log = { version = "0.4.14", default-features = false } - -[features] -default = ["std"] -std = [ - "sp-arithmetic/std", - "log/std", -] diff --git a/lib-serml/serp/serp-staking/reward-fn/src/lib.rs b/lib-serml/serp/serp-staking/reward-fn/src/lib.rs deleted file mode 100644 index 3f91c39b4..000000000 --- a/lib-serml/serp/serp-staking/reward-fn/src/lib.rs +++ /dev/null @@ -1,233 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#![cfg_attr(not(feature = "std"), no_std)] - -//! Useful function for inflation for nominated proof of stake. - -use core::convert::TryFrom; -use sp_arithmetic::{ - biguint::BigUint, - traits::{SaturatedConversion, Zero}, - PerThing, Perquintill, -}; - -/// Compute yearly inflation using function -/// -/// ```ignore -/// I(x) = for x between 0 and x_ideal: x / x_ideal, -/// for x between x_ideal and 1: 2^((x_ideal - x) / d) -/// ``` -/// -/// where: -/// * x is the stake rate, i.e. fraction of total issued tokens that actively staked behind -/// validators. -/// * d is the falloff or `decay_rate` -/// * x_ideal: the ideal stake rate. -/// -/// The result is meant to be scaled with minimum inflation and maximum inflation. -/// -/// (as detailed -/// [here](https://research.web3.foundation/en/latest/polkadot/economics/1-token-economics.html#inflation-model-with-parachains)) -/// -/// Arguments are: -/// * `stake`: -/// The fraction of total issued tokens that actively staked behind -/// validators. Known as `x` in the literature. -/// Must be between 0 and 1. -/// * `ideal_stake`: -/// The fraction of total issued tokens that should be actively staked behind -/// validators. Known as `x_ideal` in the literature. -/// Must be between 0 and 1. -/// * `falloff`: -/// Known as `decay_rate` in the literature. A co-efficient dictating the strength of -/// the global incentivization to get the `ideal_stake`. A higher number results in less typical -/// inflation at the cost of greater volatility for validators. -/// Must be more than 0.01. -pub fn compute_inflation(stake: P, ideal_stake: P, falloff: P) -> P { - if stake < ideal_stake { - // ideal_stake is more than 0 because it is strictly more than stake - return stake / ideal_stake - } - - if falloff < P::from_percent(1.into()) { - log::error!("Invalid inflation computation: falloff less than 1% is not supported"); - return PerThing::zero() - } - - let accuracy = { - let mut a = BigUint::from(Into::::into(P::ACCURACY)); - a.lstrip(); - a - }; - - let mut falloff = BigUint::from(falloff.deconstruct().into()); - falloff.lstrip(); - - let ln2 = { - /// `ln(2)` expressed in as perquintillionth. - const LN2: u64 = 0_693_147_180_559_945_309; - let ln2 = P::from_rational(LN2.into(), Perquintill::ACCURACY.into()); - BigUint::from(ln2.deconstruct().into()) - }; - - // falloff is stripped above. - let ln2_div_d = div_by_stripped(ln2.mul(&accuracy), &falloff); - - let inpos_param = INPoSParam { - x_ideal: BigUint::from(ideal_stake.deconstruct().into()), - x: BigUint::from(stake.deconstruct().into()), - accuracy, - ln2_div_d, - }; - - let res = compute_taylor_serie_part(&inpos_param); - - match u128::try_from(res.clone()) { - Ok(res) if res <= Into::::into(P::ACCURACY) => P::from_parts(res.saturated_into()), - // If result is beyond bounds there is nothing we can do - _ => { - log::error!("Invalid inflation computation: unexpected result {:?}", res); - P::zero() - }, - } -} - -/// Internal struct holding parameter info alongside other cached value. -/// -/// All expressed in part from `accuracy` -struct INPoSParam { - ln2_div_d: BigUint, - x_ideal: BigUint, - x: BigUint, - /// Must be stripped and have no leading zeros. - accuracy: BigUint, -} - -/// Compute `2^((x_ideal - x) / d)` using taylor serie. -/// -/// x must be strictly more than x_ideal. -/// -/// result is expressed with accuracy `INPoSParam.accuracy` -fn compute_taylor_serie_part(p: &INPoSParam) -> BigUint { - // The last computed taylor term. - let mut last_taylor_term = p.accuracy.clone(); - - // Whereas taylor sum is positive. - let mut taylor_sum_positive = true; - - // The sum of all taylor term. - let mut taylor_sum = last_taylor_term.clone(); - - for k in 1..300 { - last_taylor_term = compute_taylor_term(k, &last_taylor_term, p); - - if last_taylor_term.is_zero() { - break - } - - let last_taylor_term_positive = k % 2 == 0; - - if taylor_sum_positive == last_taylor_term_positive { - taylor_sum = taylor_sum.add(&last_taylor_term); - } else { - if taylor_sum >= last_taylor_term { - taylor_sum = taylor_sum - .sub(&last_taylor_term) - // NOTE: Should never happen as checked above - .unwrap_or_else(|e| e); - } else { - taylor_sum_positive = !taylor_sum_positive; - taylor_sum = last_taylor_term - .clone() - .sub(&taylor_sum) - // NOTE: Should never happen as checked above - .unwrap_or_else(|e| e); - } - } - } - - if !taylor_sum_positive { - return BigUint::zero() - } - - taylor_sum.lstrip(); - taylor_sum -} - -/// Return the absolute value of k-th taylor term of `2^((x_ideal - x))/d` i.e. -/// `((x - x_ideal) * ln(2) / d)^k / k!` -/// -/// x must be strictly more x_ideal. -/// -/// We compute the term from the last term using this formula: -/// -/// `((x - x_ideal) * ln(2) / d)^k / k! == previous_term * (x - x_ideal) * ln(2) / d / k` -/// -/// `previous_taylor_term` and result are expressed with accuracy `INPoSParam.accuracy` -fn compute_taylor_term(k: u32, previous_taylor_term: &BigUint, p: &INPoSParam) -> BigUint { - let x_minus_x_ideal = - p.x.clone() - .sub(&p.x_ideal) - // NOTE: Should never happen, as x must be more than x_ideal - .unwrap_or_else(|_| BigUint::zero()); - - let res = previous_taylor_term.clone().mul(&x_minus_x_ideal).mul(&p.ln2_div_d).div_unit(k); - - // p.accuracy is stripped by definition. - let res = div_by_stripped(res, &p.accuracy); - let mut res = div_by_stripped(res, &p.accuracy); - - res.lstrip(); - res -} - -/// Compute a div b. -/// -/// requires `b` to be stripped and have no leading zeros. -fn div_by_stripped(mut a: BigUint, b: &BigUint) -> BigUint { - a.lstrip(); - - if b.len() == 0 { - log::error!("Computation error: Invalid division"); - return BigUint::zero() - } - - if b.len() == 1 { - return a.div_unit(b.checked_get(0).unwrap_or(1)) - } - - if b.len() > a.len() { - return BigUint::zero() - } - - if b.len() == a.len() { - // 100_000^2 is more than 2^32-1, thus `new_a` has more limbs than `b`. - let mut new_a = a.mul(&BigUint::from(100_000u64.pow(2))); - new_a.lstrip(); - - debug_assert!(new_a.len() > b.len()); - return new_a - .div(b, false) - .map(|res| res.0) - .unwrap_or_else(|| BigUint::zero()) - .div_unit(100_000) - .div_unit(100_000) - } - - a.div(b, false).map(|res| res.0).unwrap_or_else(|| BigUint::zero()) -} diff --git a/lib-serml/serp/serp-staking/reward-fn/tests/test.rs b/lib-serml/serp/serp-staking/reward-fn/tests/test.rs deleted file mode 100644 index 121aec463..000000000 --- a/lib-serml/serp/serp-staking/reward-fn/tests/test.rs +++ /dev/null @@ -1,101 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use sp_arithmetic::{PerThing, PerU16, Perbill, Percent, Perquintill}; - -/// This test the precision and panics if error too big error. -/// -/// error is asserted to be less or equal to 8/accuracy or 8*f64::EPSILON -fn test_precision(stake: P, ideal_stake: P, falloff: P) { - let accuracy_f64 = Into::::into(P::ACCURACY) as f64; - let res = serp_staking_reward_fn::compute_inflation(stake, ideal_stake, falloff); - let res = Into::::into(res.deconstruct()) as f64 / accuracy_f64; - - let expect = float_i_npos(stake, ideal_stake, falloff); - - let error = (res - expect).abs(); - - if error > 8f64 / accuracy_f64 && error > 8.0 * f64::EPSILON { - panic!( - "stake: {:?}, ideal_stake: {:?}, falloff: {:?}, res: {}, expect: {}", - stake, ideal_stake, falloff, res, expect - ); - } -} - -/// compute the inflation using floats -fn float_i_npos(stake: P, ideal_stake: P, falloff: P) -> f64 { - let accuracy_f64 = Into::::into(P::ACCURACY) as f64; - - let ideal_stake = Into::::into(ideal_stake.deconstruct()) as f64 / accuracy_f64; - let stake = Into::::into(stake.deconstruct()) as f64 / accuracy_f64; - let falloff = Into::::into(falloff.deconstruct()) as f64 / accuracy_f64; - - let x_ideal = ideal_stake; - let x = stake; - let d = falloff; - - if x < x_ideal { - x / x_ideal - } else { - 2_f64.powf((x_ideal - x) / d) - } -} - -#[test] -fn test_precision_for_minimum_falloff() { - fn test_falloff_precision_for_minimum_falloff() { - for stake in 0..1_000 { - let stake = P::from_rational(stake, 1_000); - let ideal_stake = P::zero(); - let falloff = P::from_rational(1, 100); - test_precision(stake, ideal_stake, falloff); - } - } - - test_falloff_precision_for_minimum_falloff::(); - - test_falloff_precision_for_minimum_falloff::(); - - test_falloff_precision_for_minimum_falloff::(); - - test_falloff_precision_for_minimum_falloff::(); -} - -#[test] -fn compute_inflation_works() { - fn compute_inflation_works() { - for stake in 0..100 { - for ideal_stake in 0..10 { - for falloff in 1..10 { - let stake = P::from_rational(stake, 100); - let ideal_stake = P::from_rational(ideal_stake, 10); - let falloff = P::from_rational(falloff, 100); - test_precision(stake, ideal_stake, falloff); - } - } - } - } - - compute_inflation_works::(); - - compute_inflation_works::(); - - compute_inflation_works::(); - - compute_inflation_works::(); -} diff --git a/lib-serml/serp/serp-staking/src/benchmarking.rs b/lib-serml/serp/serp-staking/src/benchmarking.rs deleted file mode 100644 index 15a20dfb9..000000000 --- a/lib-serml/serp/serp-staking/src/benchmarking.rs +++ /dev/null @@ -1,757 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Staking pallet benchmarking. - -use super::*; -use crate::Pallet as Staking; -use testing_utils::*; - -pub use frame_benchmarking::{ - account, benchmarks, impl_benchmark_test_suite, whitelist_account, whitelisted_caller, -}; -use frame_system::RawOrigin; -use sp_runtime::traits::One; - -const SEED: u32 = 0; -const MAX_SPANS: u32 = 100; -const MAX_VALIDATORS: u32 = 1000; -const MAX_NOMINATORS: u32 = 1000; -const MAX_SLASHES: u32 = 1000; - -// Add slashing spans to a user account. Not relevant for actual use, only to benchmark -// read and write operations. -fn add_slashing_spans(who: &T::AccountId, spans: u32) { - if spans == 0 { - return - } - - // For the first slashing span, we initialize - let mut slashing_spans = crate::slashing::SlashingSpans::new(0); - SpanSlash::::insert((who, 0), crate::slashing::SpanRecord::default()); - - for i in 1..spans { - assert!(slashing_spans.end_span(i)); - SpanSlash::::insert((who, i), crate::slashing::SpanRecord::default()); - } - SlashingSpans::::insert(who, slashing_spans); -} - -// This function clears all existing validators and nominators from the set, and generates one new -// validator being nominated by n nominators, and returns the validator stash account and the -// nominators' stash and controller. It also starts an era and creates pending payouts. -pub fn create_validator_with_nominators( - n: u32, - upper_bound: u32, - dead: bool, - destination: RewardDestination, -) -> Result<(T::AccountId, Vec<(T::AccountId, T::AccountId)>), &'static str> { - // Clean up any existing state. - clear_validators_and_nominators::(); - let mut points_total = 0; - let mut points_individual = Vec::new(); - - let (v_stash, v_controller) = create_stash_controller::(0, 100, destination.clone())?; - let validator_prefs = - ValidatorPrefs { commission: Perbill::from_percent(50), ..Default::default() }; - Staking::::validate(RawOrigin::Signed(v_controller).into(), validator_prefs)?; - let stash_lookup: ::Source = T::Lookup::unlookup(v_stash.clone()); - - points_total += 10; - points_individual.push((v_stash.clone(), 10)); - - let mut nominators = Vec::new(); - - // Give the validator n nominators, but keep total users in the system the same. - for i in 0..upper_bound { - let (n_stash, n_controller) = if !dead { - create_stash_controller::(u32::MAX - i, 100, destination.clone())? - } else { - create_stash_and_dead_controller::(u32::MAX - i, 100, destination.clone())? - }; - if i < n { - Staking::::nominate( - RawOrigin::Signed(n_controller.clone()).into(), - vec![stash_lookup.clone()], - )?; - nominators.push((n_stash, n_controller)); - } - } - - ValidatorCount::::put(1); - - // Start a new Era - let new_validators = Staking::::try_trigger_new_era(SessionIndex::one(), true).unwrap(); - - assert_eq!(new_validators.len(), 1); - assert_eq!(new_validators[0], v_stash, "Our validator was not selected!"); - - // Give Era Points - let reward = EraRewardPoints:: { - total: points_total, - individual: points_individual.into_iter().collect(), - }; - - let current_era = CurrentEra::::get().unwrap(); - ErasRewardPoints::::insert(current_era, reward); - - // Create reward pool - let total_payout = T::Currency::minimum_balance() - .saturating_mul(upper_bound.into()) - .saturating_mul(1000u32.into()); - >::insert(current_era, total_payout); - - Ok((v_stash, nominators)) -} - -const USER_SEED: u32 = 999666; - -benchmarks! { - bond { - let stash = create_funded_user::("stash", USER_SEED, 100); - let controller = create_funded_user::("controller", USER_SEED, 100); - let controller_lookup: ::Source = T::Lookup::unlookup(controller.clone()); - let reward_destination = RewardDestination::Staked; - let amount = T::Currency::minimum_balance() * 10u32.into(); - whitelist_account!(stash); - }: _(RawOrigin::Signed(stash.clone()), controller_lookup, amount, reward_destination) - verify { - assert!(Bonded::::contains_key(stash)); - assert!(Ledger::::contains_key(controller)); - } - - bond_extra { - let (stash, controller) = create_stash_controller::(USER_SEED, 100, Default::default())?; - let max_additional = T::Currency::minimum_balance() * 10u32.into(); - let ledger = Ledger::::get(&controller).ok_or("ledger not created before")?; - let original_bonded: BalanceOf = ledger.active; - whitelist_account!(stash); - }: _(RawOrigin::Signed(stash), max_additional) - verify { - let ledger = Ledger::::get(&controller).ok_or("ledger not created after")?; - let new_bonded: BalanceOf = ledger.active; - assert!(original_bonded < new_bonded); - } - - unbond { - let (_, controller) = create_stash_controller::(USER_SEED, 100, Default::default())?; - let amount = T::Currency::minimum_balance() * 10u32.into(); - let ledger = Ledger::::get(&controller).ok_or("ledger not created before")?; - let original_bonded: BalanceOf = ledger.active; - whitelist_account!(controller); - }: _(RawOrigin::Signed(controller.clone()), amount) - verify { - let ledger = Ledger::::get(&controller).ok_or("ledger not created after")?; - let new_bonded: BalanceOf = ledger.active; - assert!(original_bonded > new_bonded); - } - - // Withdraw only updates the ledger - withdraw_unbonded_update { - // Slashing Spans - let s in 0 .. MAX_SPANS; - let (stash, controller) = create_stash_controller::(0, 100, Default::default())?; - add_slashing_spans::(&stash, s); - let amount = T::Currency::minimum_balance() * 5u32.into(); // Half of total - Staking::::unbond(RawOrigin::Signed(controller.clone()).into(), amount)?; - CurrentEra::::put(EraIndex::max_value()); - let ledger = Ledger::::get(&controller).ok_or("ledger not created before")?; - let original_total: BalanceOf = ledger.total; - whitelist_account!(controller); - }: withdraw_unbonded(RawOrigin::Signed(controller.clone()), s) - verify { - let ledger = Ledger::::get(&controller).ok_or("ledger not created after")?; - let new_total: BalanceOf = ledger.total; - assert!(original_total > new_total); - } - - // Worst case scenario, everything is removed after the bonding duration - withdraw_unbonded_kill { - // Slashing Spans - let s in 0 .. MAX_SPANS; - let (stash, controller) = create_stash_controller::(0, 100, Default::default())?; - add_slashing_spans::(&stash, s); - let amount = T::Currency::minimum_balance() * 10u32.into(); - Staking::::unbond(RawOrigin::Signed(controller.clone()).into(), amount)?; - CurrentEra::::put(EraIndex::max_value()); - let ledger = Ledger::::get(&controller).ok_or("ledger not created before")?; - let original_total: BalanceOf = ledger.total; - whitelist_account!(controller); - }: withdraw_unbonded(RawOrigin::Signed(controller.clone()), s) - verify { - assert!(!Ledger::::contains_key(controller)); - } - - validate { - let (stash, controller) = create_stash_controller::(USER_SEED, 100, Default::default())?; - let prefs = ValidatorPrefs::default(); - whitelist_account!(controller); - }: _(RawOrigin::Signed(controller), prefs) - verify { - assert!(Validators::::contains_key(stash)); - } - - kick { - // scenario: we want to kick `k` nominators from nominating us (we are a validator). - // we'll assume that `k` is under 128 for the purposes of determining the slope. - // each nominator should have `T::MAX_NOMINATIONS` validators nominated, and our validator - // should be somewhere in there. - let k in 1 .. 128; - - // these are the other validators; there are `T::MAX_NOMINATIONS - 1` of them, so - // there are a total of `T::MAX_NOMINATIONS` validators in the system. - let rest_of_validators = create_validators::(T::MAX_NOMINATIONS - 1, 100)?; - - // this is the validator that will be kicking. - let (stash, controller) = create_stash_controller::( - T::MAX_NOMINATIONS - 1, - 100, - Default::default(), - )?; - let stash_lookup: ::Source = T::Lookup::unlookup(stash.clone()); - - // they start validating. - Staking::::validate(RawOrigin::Signed(controller.clone()).into(), Default::default())?; - - // we now create the nominators. there will be `k` of them; each will nominate all - // validators. we will then kick each of the `k` nominators from the main validator. - let mut nominator_stashes = Vec::with_capacity(k as usize); - for i in 0 .. k { - // create a nominator stash. - let (n_stash, n_controller) = create_stash_controller::( - T::MAX_NOMINATIONS + i, - 100, - Default::default(), - )?; - - // bake the nominations; we first clone them from the rest of the validators. - let mut nominations = rest_of_validators.clone(); - // then insert "our" validator somewhere in there (we vary it) to avoid accidental - // optimisations/pessimisations. - nominations.insert(i as usize % (nominations.len() + 1), stash_lookup.clone()); - // then we nominate. - Staking::::nominate(RawOrigin::Signed(n_controller.clone()).into(), nominations)?; - - nominator_stashes.push(n_stash); - } - - // all nominators now should be nominating our validator... - for n in nominator_stashes.iter() { - assert!(Nominators::::get(n).unwrap().targets.contains(&stash)); - } - - // we need the unlookuped version of the nominator stash for the kick. - let kicks = nominator_stashes.iter() - .map(|n| T::Lookup::unlookup(n.clone())) - .collect::>(); - - whitelist_account!(controller); - }: _(RawOrigin::Signed(controller), kicks) - verify { - // all nominators now should *not* be nominating our validator... - for n in nominator_stashes.iter() { - assert!(!Nominators::::get(n).unwrap().targets.contains(&stash)); - } - } - - // Worst case scenario, T::MAX_NOMINATIONS - nominate { - let n in 1 .. T::MAX_NOMINATIONS; - let (stash, controller) = create_stash_controller::(n + 1, 100, Default::default())?; - let validators = create_validators::(n, 100)?; - whitelist_account!(controller); - }: _(RawOrigin::Signed(controller), validators) - verify { - assert!(Nominators::::contains_key(stash)); - } - - chill { - let (_, controller) = create_stash_controller::(USER_SEED, 100, Default::default())?; - whitelist_account!(controller); - }: _(RawOrigin::Signed(controller)) - - set_payee { - let (stash, controller) = create_stash_controller::(USER_SEED, 100, Default::default())?; - assert_eq!(Payee::::get(&stash), RewardDestination::Staked); - whitelist_account!(controller); - }: _(RawOrigin::Signed(controller), RewardDestination::Controller) - verify { - assert_eq!(Payee::::get(&stash), RewardDestination::Controller); - } - - set_controller { - let (stash, _) = create_stash_controller::(USER_SEED, 100, Default::default())?; - let new_controller = create_funded_user::("new_controller", USER_SEED, 100); - let new_controller_lookup = T::Lookup::unlookup(new_controller.clone()); - whitelist_account!(stash); - }: _(RawOrigin::Signed(stash), new_controller_lookup) - verify { - assert!(Ledger::::contains_key(&new_controller)); - } - - set_validator_count { - let validator_count = MAX_VALIDATORS; - }: _(RawOrigin::Root, validator_count) - verify { - assert_eq!(ValidatorCount::::get(), validator_count); - } - - force_no_eras {}: _(RawOrigin::Root) - verify { assert_eq!(ForceEra::::get(), Forcing::ForceNone); } - - force_new_era {}: _(RawOrigin::Root) - verify { assert_eq!(ForceEra::::get(), Forcing::ForceNew); } - - force_new_era_always {}: _(RawOrigin::Root) - verify { assert_eq!(ForceEra::::get(), Forcing::ForceAlways); } - - // Worst case scenario, the list of invulnerables is very long. - set_invulnerables { - let v in 0 .. MAX_VALIDATORS; - let mut invulnerables = Vec::new(); - for i in 0 .. v { - invulnerables.push(account("invulnerable", i, SEED)); - } - }: _(RawOrigin::Root, invulnerables) - verify { - assert_eq!(Invulnerables::::get().len(), v as usize); - } - - force_unstake { - // Slashing Spans - let s in 0 .. MAX_SPANS; - let (stash, controller) = create_stash_controller::(0, 100, Default::default())?; - add_slashing_spans::(&stash, s); - }: _(RawOrigin::Root, stash, s) - verify { - assert!(!Ledger::::contains_key(&controller)); - } - - cancel_deferred_slash { - let s in 1 .. MAX_SLASHES; - let mut unapplied_slashes = Vec::new(); - let era = EraIndex::one(); - for _ in 0 .. MAX_SLASHES { - unapplied_slashes.push(UnappliedSlash::>::default()); - } - UnappliedSlashes::::insert(era, &unapplied_slashes); - - let slash_indices: Vec = (0 .. s).collect(); - }: _(RawOrigin::Root, era, slash_indices) - verify { - assert_eq!(UnappliedSlashes::::get(&era).len(), (MAX_SLASHES - s) as usize); - } - - payout_stakers_dead_controller { - let n in 1 .. T::MaxNominatorRewardedPerValidator::get() as u32; - let (validator, nominators) = create_validator_with_nominators::( - n, - T::MaxNominatorRewardedPerValidator::get() as u32, - true, - RewardDestination::Controller, - )?; - - let current_era = CurrentEra::::get().unwrap(); - // set the commission for this particular era as well. - >::insert(current_era, validator.clone(), >::validators(&validator)); - - let caller = whitelisted_caller(); - let validator_controller = >::get(&validator).unwrap(); - let balance_before = T::Currency::free_balance(&validator_controller); - for (_, controller) in &nominators { - let balance = T::Currency::free_balance(&controller); - ensure!(balance.is_zero(), "Controller has balance, but should be dead."); - } - }: payout_stakers(RawOrigin::Signed(caller), validator.clone(), current_era) - verify { - let balance_after = T::Currency::free_balance(&validator_controller); - ensure!( - balance_before < balance_after, - "Balance of validator controller should have increased after payout.", - ); - for (_, controller) in &nominators { - let balance = T::Currency::free_balance(&controller); - ensure!(!balance.is_zero(), "Payout not given to controller."); - } - } - - payout_stakers_alive_staked { - let n in 1 .. T::MaxNominatorRewardedPerValidator::get() as u32; - let (validator, nominators) = create_validator_with_nominators::( - n, - T::MaxNominatorRewardedPerValidator::get() as u32, - false, - RewardDestination::Staked, - )?; - - let current_era = CurrentEra::::get().unwrap(); - // set the commission for this particular era as well. - >::insert(current_era, validator.clone(), >::validators(&validator)); - - let caller = whitelisted_caller(); - let balance_before = T::Currency::free_balance(&validator); - let mut nominator_balances_before = Vec::new(); - for (stash, _) in &nominators { - let balance = T::Currency::free_balance(&stash); - nominator_balances_before.push(balance); - } - }: payout_stakers(RawOrigin::Signed(caller), validator.clone(), current_era) - verify { - let balance_after = T::Currency::free_balance(&validator); - ensure!( - balance_before < balance_after, - "Balance of validator stash should have increased after payout.", - ); - for ((stash, _), balance_before) in nominators.iter().zip(nominator_balances_before.iter()) { - let balance_after = T::Currency::free_balance(&stash); - ensure!( - balance_before < &balance_after, - "Balance of nominator stash should have increased after payout.", - ); - } - } - - rebond { - let l in 1 .. MAX_UNLOCKING_CHUNKS as u32; - let (_, controller) = create_stash_controller::(USER_SEED, 100, Default::default())?; - let mut staking_ledger = Ledger::::get(controller.clone()).unwrap(); - let unlock_chunk = UnlockChunk::> { - value: 1u32.into(), - era: EraIndex::zero(), - }; - for _ in 0 .. l { - staking_ledger.unlocking.push(unlock_chunk.clone()) - } - Ledger::::insert(controller.clone(), staking_ledger.clone()); - let original_bonded: BalanceOf = staking_ledger.active; - whitelist_account!(controller); - }: _(RawOrigin::Signed(controller.clone()), (l + 100).into()) - verify { - let ledger = Ledger::::get(&controller).ok_or("ledger not created after")?; - let new_bonded: BalanceOf = ledger.active; - assert!(original_bonded < new_bonded); - } - - set_history_depth { - let e in 1 .. 100; - HistoryDepth::::put(e); - CurrentEra::::put(e); - for i in 0 .. e { - >::insert(i, T::AccountId::default(), Exposure::>::default()); - >::insert(i, T::AccountId::default(), Exposure::>::default()); - >::insert(i, T::AccountId::default(), ValidatorPrefs::default()); - >::insert(i, BalanceOf::::one()); - >::insert(i, EraRewardPoints::::default()); - >::insert(i, BalanceOf::::one()); - ErasStartSessionIndex::::insert(i, i); - } - }: _(RawOrigin::Root, EraIndex::zero(), u32::MAX) - verify { - assert_eq!(HistoryDepth::::get(), 0); - } - - reap_stash { - let s in 1 .. MAX_SPANS; - let (stash, controller) = create_stash_controller::(0, 100, Default::default())?; - Staking::::validate(RawOrigin::Signed(controller.clone()).into(), ValidatorPrefs::default())?; - add_slashing_spans::(&stash, s); - T::Currency::make_free_balance_be(&stash, T::Currency::minimum_balance()); - whitelist_account!(controller); - - assert!(Bonded::::contains_key(&stash)); - assert!(Validators::::contains_key(&stash)); - - }: _(RawOrigin::Signed(controller), stash.clone(), s) - verify { - assert!(!Bonded::::contains_key(&stash)); - assert!(!Validators::::contains_key(&stash)); - } - - new_era { - let v in 1 .. 10; - let n in 1 .. 100; - - create_validators_with_nominators_for_era::( - v, - n, - ::MAX_NOMINATIONS as usize, - false, - None, - )?; - let session_index = SessionIndex::one(); - }: { - let validators = Staking::::try_trigger_new_era(session_index, true) - .ok_or("`new_era` failed")?; - assert!(validators.len() == v as usize); - } - - #[extra] - payout_all { - let v in 1 .. 10; - let n in 1 .. 100; - create_validators_with_nominators_for_era::( - v, - n, - ::MAX_NOMINATIONS as usize, - false, - None, - )?; - // Start a new Era - let new_validators = Staking::::try_trigger_new_era(SessionIndex::one(), true).unwrap(); - assert!(new_validators.len() == v as usize); - - let current_era = CurrentEra::::get().unwrap(); - let mut points_total = 0; - let mut points_individual = Vec::new(); - let mut payout_calls_arg = Vec::new(); - - for validator in new_validators.iter() { - points_total += 10; - points_individual.push((validator.clone(), 10)); - payout_calls_arg.push((validator.clone(), current_era)); - } - - // Give Era Points - let reward = EraRewardPoints:: { - total: points_total, - individual: points_individual.into_iter().collect(), - }; - - ErasRewardPoints::::insert(current_era, reward); - - // Create reward pool - let total_payout = T::Currency::minimum_balance() * 1000u32.into(); - >::insert(current_era, total_payout); - - let caller: T::AccountId = whitelisted_caller(); - }: { - for arg in payout_calls_arg { - >::payout_stakers(RawOrigin::Signed(caller.clone()).into(), arg.0, arg.1)?; - } - } - - #[extra] - do_slash { - let l in 1 .. MAX_UNLOCKING_CHUNKS as u32; - let (stash, controller) = create_stash_controller::(0, 100, Default::default())?; - let mut staking_ledger = Ledger::::get(controller.clone()).unwrap(); - let unlock_chunk = UnlockChunk::> { - value: 1u32.into(), - era: EraIndex::zero(), - }; - for _ in 0 .. l { - staking_ledger.unlocking.push(unlock_chunk.clone()) - } - Ledger::::insert(controller, staking_ledger); - let slash_amount = T::Currency::minimum_balance() * 10u32.into(); - let balance_before = T::Currency::free_balance(&stash); - }: { - crate::slashing::do_slash::( - &stash, - slash_amount, - &mut BalanceOf::::zero(), - &mut NegativeImbalanceOf::::zero() - ); - } verify { - let balance_after = T::Currency::free_balance(&stash); - assert!(balance_before > balance_after); - } - - get_npos_voters { - // number of validator intention. - let v in (MAX_VALIDATORS / 2) .. MAX_VALIDATORS; - // number of nominator intention. - let n in (MAX_NOMINATORS / 2) .. MAX_NOMINATORS; - // total number of slashing spans. Assigned to validators randomly. - let s in 1 .. 20; - - let validators = create_validators_with_nominators_for_era::(v, n, T::MAX_NOMINATIONS as usize, false, None)? - .into_iter() - .map(|v| T::Lookup::lookup(v).unwrap()) - .collect::>(); - - (0..s).for_each(|index| { - add_slashing_spans::(&validators[index as usize], 10); - }); - }: { - let voters = >::get_npos_voters(); - assert_eq!(voters.len() as u32, v + n); - } - - get_npos_targets { - // number of validator intention. - let v in (MAX_VALIDATORS / 2) .. MAX_VALIDATORS; - // number of nominator intention. - let n = MAX_NOMINATORS; - - let _ = create_validators_with_nominators_for_era::(v, n, T::MAX_NOMINATIONS as usize, false, None)?; - }: { - let targets = >::get_npos_targets(); - assert_eq!(targets.len() as u32, v); - } - - set_staking_limits { - // This function always does the same thing... just write to 4 storage items. - }: _( - RawOrigin::Root, - BalanceOf::::max_value(), - BalanceOf::::max_value(), - Some(u32::MAX), - Some(u32::MAX), - Some(Percent::max_value()) - ) verify { - assert_eq!(MinNominatorBond::::get(), BalanceOf::::max_value()); - assert_eq!(MinValidatorBond::::get(), BalanceOf::::max_value()); - assert_eq!(MaxNominatorsCount::::get(), Some(u32::MAX)); - assert_eq!(MaxValidatorsCount::::get(), Some(u32::MAX)); - assert_eq!(ChillThreshold::::get(), Some(Percent::from_percent(100))); - } - - chill_other { - let (_, controller) = create_stash_controller::(USER_SEED, 100, Default::default())?; - Staking::::validate(RawOrigin::Signed(controller.clone()).into(), ValidatorPrefs::default())?; - Staking::::set_staking_limits( - RawOrigin::Root.into(), - BalanceOf::::max_value(), - BalanceOf::::max_value(), - Some(0), - Some(0), - Some(Percent::from_percent(0)) - )?; - let caller = whitelisted_caller(); - }: _(RawOrigin::Signed(caller), controller.clone()) - verify { - assert!(!Validators::::contains_key(controller)); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::mock::{Balances, ExtBuilder, Origin, Staking, Test}; - use frame_support::assert_ok; - - #[test] - fn create_validators_with_nominators_for_era_works() { - ExtBuilder::default().has_stakers(true).build_and_execute(|| { - let v = 10; - let n = 100; - - create_validators_with_nominators_for_era::( - v, - n, - ::MAX_NOMINATIONS as usize, - false, - None, - ) - .unwrap(); - - let count_validators = Validators::::iter().count(); - let count_nominators = Nominators::::iter().count(); - - assert_eq!(count_validators, v as usize); - assert_eq!(count_nominators, n as usize); - }); - } - - #[test] - fn create_validator_with_nominators_works() { - ExtBuilder::default().has_stakers(true).build_and_execute(|| { - let n = 10; - - let (validator_stash, nominators) = create_validator_with_nominators::( - n, - ::MaxNominatorRewardedPerValidator::get() as u32, - false, - RewardDestination::Staked, - ) - .unwrap(); - - assert_eq!(nominators.len() as u32, n); - - let current_era = CurrentEra::::get().unwrap(); - - let original_free_balance = Balances::free_balance(&validator_stash); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), validator_stash, current_era)); - let new_free_balance = Balances::free_balance(&validator_stash); - - assert!(original_free_balance < new_free_balance); - }); - } - - #[test] - fn add_slashing_spans_works() { - ExtBuilder::default().has_stakers(true).build_and_execute(|| { - let n = 10; - - let (validator_stash, _nominators) = create_validator_with_nominators::( - n, - ::MaxNominatorRewardedPerValidator::get() as u32, - false, - RewardDestination::Staked, - ) - .unwrap(); - - // Add 20 slashing spans - let num_of_slashing_spans = 20; - add_slashing_spans::(&validator_stash, num_of_slashing_spans); - - let slashing_spans = SlashingSpans::::get(&validator_stash).unwrap(); - assert_eq!(slashing_spans.iter().count(), num_of_slashing_spans as usize); - for i in 0..num_of_slashing_spans { - assert!(SpanSlash::::contains_key((&validator_stash, i))); - } - - // Test everything is cleaned up - assert_ok!(Staking::kill_stash(&validator_stash, num_of_slashing_spans)); - assert!(SlashingSpans::::get(&validator_stash).is_none()); - for i in 0..num_of_slashing_spans { - assert!(!SpanSlash::::contains_key((&validator_stash, i))); - } - }); - } - - #[test] - fn test_payout_all() { - ExtBuilder::default().has_stakers(true).build_and_execute(|| { - let v = 10; - let n = 100; - - let selected_benchmark = SelectedBenchmark::payout_all; - let c = vec![ - (frame_benchmarking::BenchmarkParameter::v, v), - (frame_benchmarking::BenchmarkParameter::n, n), - ]; - let closure_to_benchmark = - >::instance( - &selected_benchmark, - &c, - true, - ) - .unwrap(); - - assert_ok!(closure_to_benchmark()); - }); - } -} - -impl_benchmark_test_suite!( - Staking, - crate::mock::ExtBuilder::default().has_stakers(true), - crate::mock::Test, - exec_name = build_and_execute -); diff --git a/lib-serml/serp/serp-staking/src/inflation.rs b/lib-serml/serp/serp-staking/src/inflation.rs deleted file mode 100644 index 03b700f84..000000000 --- a/lib-serml/serp/serp-staking/src/inflation.rs +++ /dev/null @@ -1,108 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! This module expose one function `P_NPoS` (Payout NPoS) or `compute_total_payout` which returns -//! the total payout for the era given the era duration and the staking rate in NPoS. -//! The staking rate in NPoS is the total amount of tokens staked by nominators and validators, -//! divided by the total token supply. - -use sp_runtime::{curve::PiecewiseLinear, traits::AtLeast32BitUnsigned, Perbill}; - -/// The total payout to all validators (and their nominators) per era and maximum payout. -/// -/// Defined as such: -/// `staker-payout = yearly_inflation(npos_token_staked / total_tokens) * total_tokens / era_per_year` -/// `maximum-payout = max_yearly_inflation * total_tokens / era_per_year` -/// -/// `era_duration` is expressed in millisecond. -pub fn compute_total_payout( - yearly_inflation: &PiecewiseLinear<'static>, - npos_token_staked: N, - total_tokens: N, - era_duration: u64, -) -> (N, N) -where - N: AtLeast32BitUnsigned + Clone, -{ - // Milliseconds per year for the Julian year (365.25 days). - const MILLISECONDS_PER_YEAR: u64 = 1000 * 3600 * 24 * 36525 / 100; - - let portion = Perbill::from_rational(era_duration as u64, MILLISECONDS_PER_YEAR); - let payout = portion * - yearly_inflation - .calculate_for_fraction_times_denominator(npos_token_staked, total_tokens.clone()); - let maximum = portion * (yearly_inflation.maximum * total_tokens); - (payout, maximum) -} - -#[cfg(test)] -mod test { - use sp_runtime::curve::PiecewiseLinear; - - serp_staking_reward_curve::build! { - const I_NPOS: PiecewiseLinear<'static> = curve!( - min_inflation: 0_025_000, - max_inflation: 0_100_000, - ideal_stake: 0_500_000, - falloff: 0_050_000, - max_piece_count: 40, - test_precision: 0_005_000, - ); - } - - #[test] - fn npos_curve_is_sensible() { - const YEAR: u64 = 365 * 24 * 60 * 60 * 1000; - - // check maximum inflation. - // not 10_000 due to rounding error. - assert_eq!(super::compute_total_payout(&I_NPOS, 0, 100_000u64, YEAR).1, 9_993); - - // super::I_NPOS.calculate_for_fraction_times_denominator(25, 100) - assert_eq!(super::compute_total_payout(&I_NPOS, 0, 100_000u64, YEAR).0, 2_498); - assert_eq!(super::compute_total_payout(&I_NPOS, 5_000, 100_000u64, YEAR).0, 3_248); - assert_eq!(super::compute_total_payout(&I_NPOS, 25_000, 100_000u64, YEAR).0, 6_246); - assert_eq!(super::compute_total_payout(&I_NPOS, 40_000, 100_000u64, YEAR).0, 8_494); - assert_eq!(super::compute_total_payout(&I_NPOS, 50_000, 100_000u64, YEAR).0, 9_993); - assert_eq!(super::compute_total_payout(&I_NPOS, 60_000, 100_000u64, YEAR).0, 4_379); - assert_eq!(super::compute_total_payout(&I_NPOS, 75_000, 100_000u64, YEAR).0, 2_733); - assert_eq!(super::compute_total_payout(&I_NPOS, 95_000, 100_000u64, YEAR).0, 2_513); - assert_eq!(super::compute_total_payout(&I_NPOS, 100_000, 100_000u64, YEAR).0, 2_505); - - const DAY: u64 = 24 * 60 * 60 * 1000; - assert_eq!(super::compute_total_payout(&I_NPOS, 25_000, 100_000u64, DAY).0, 17); - assert_eq!(super::compute_total_payout(&I_NPOS, 50_000, 100_000u64, DAY).0, 27); - assert_eq!(super::compute_total_payout(&I_NPOS, 75_000, 100_000u64, DAY).0, 7); - - const SIX_HOURS: u64 = 6 * 60 * 60 * 1000; - assert_eq!(super::compute_total_payout(&I_NPOS, 25_000, 100_000u64, SIX_HOURS).0, 4); - assert_eq!(super::compute_total_payout(&I_NPOS, 50_000, 100_000u64, SIX_HOURS).0, 7); - assert_eq!(super::compute_total_payout(&I_NPOS, 75_000, 100_000u64, SIX_HOURS).0, 2); - - const HOUR: u64 = 60 * 60 * 1000; - assert_eq!( - super::compute_total_payout( - &I_NPOS, - 2_500_000_000_000_000_000_000_000_000u128, - 5_000_000_000_000_000_000_000_000_000u128, - HOUR - ) - .0, - 57_038_500_000_000_000_000_000 - ); - } -} diff --git a/lib-serml/serp/serp-staking/src/lib.rs b/lib-serml/serp/serp-staking/src/lib.rs deleted file mode 100644 index 37545f921..000000000 --- a/lib-serml/serp/serp-staking/src/lib.rs +++ /dev/null @@ -1,3489 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! # Staking Pallet -//! -//! The Staking pallet is used to manage funds at stake by network maintainers. -//! -//! - [`Config`] -//! - [`Call`] -//! - [`Pallet`] -//! -//! ## Overview -//! -//! The Staking pallet is the means by which a set of network maintainers (known as _authorities_ in -//! some contexts and _validators_ in others) are chosen based upon those who voluntarily place -//! funds under deposit. Under deposit, those funds are rewarded under normal operation but are held -//! at pain of _slash_ (expropriation) should the staked maintainer be found not to be discharging -//! its duties properly. -//! -//! ### Terminology -//! -//! -//! - Staking: The process of locking up funds for some time, placing them at risk of slashing -//! (loss) in order to become a rewarded maintainer of the network. -//! - Validating: The process of running a node to actively maintain the network, either by -//! producing blocks or guaranteeing finality of the chain. -//! - Nominating: The process of placing staked funds behind one or more validators in order to -//! share in any reward, and punishment, they take. -//! - Stash account: The account holding an owner's funds used for staking. -//! - Controller account: The account that controls an owner's funds for staking. -//! - Era: A (whole) number of sessions, which is the period that the validator set (and each -//! validator's active nominator set) is recalculated and where rewards are paid out. -//! - Slash: The punishment of a staker by reducing its funds. -//! -//! ### Goals -//! -//! -//! The staking system in Substrate NPoS is designed to make the following possible: -//! -//! - Stake funds that are controlled by a cold wallet. -//! - Withdraw some, or deposit more, funds without interrupting the role of an entity. -//! - Switch between roles (nominator, validator, idle) with minimal overhead. -//! -//! ### Scenarios -//! -//! #### Staking -//! -//! Almost any interaction with the Staking pallet requires a process of _**bonding**_ (also known -//! as being a _staker_). To become *bonded*, a fund-holding account known as the _stash account_, -//! which holds some or all of the funds that become frozen in place as part of the staking process, -//! is paired with an active **controller** account, which issues instructions on how they shall be -//! used. -//! -//! An account pair can become bonded using the [`bond`](Call::bond) call. -//! -//! Stash accounts can change their associated controller using the -//! [`set_controller`](Call::set_controller) call. -//! -//! There are three possible roles that any staked account pair can be in: `Validator`, `Nominator` -//! and `Idle` (defined in [`StakerStatus`]). There are three -//! corresponding instructions to change between roles, namely: -//! [`validate`](Call::validate), -//! [`nominate`](Call::nominate), and [`chill`](Call::chill). -//! -//! #### Validating -//! -//! A **validator** takes the role of either validating blocks or ensuring their finality, -//! maintaining the veracity of the network. A validator should avoid both any sort of malicious -//! misbehavior and going offline. Bonded accounts that state interest in being a validator do NOT -//! get immediately chosen as a validator. Instead, they are declared as a _candidate_ and they -//! _might_ get elected at the _next era_ as a validator. The result of the election is determined -//! by nominators and their votes. -//! -//! An account can become a validator candidate via the -//! [`validate`](Call::validate) call. -//! -//! #### Nomination -//! -//! A **nominator** does not take any _direct_ role in maintaining the network, instead, it votes on -//! a set of validators to be elected. Once interest in nomination is stated by an account, it -//! takes effect at the next election round. The funds in the nominator's stash account indicate the -//! _weight_ of its vote. Both the rewards and any punishment that a validator earns are shared -//! between the validator and its nominators. This rule incentivizes the nominators to NOT vote for -//! the misbehaving/offline validators as much as possible, simply because the nominators will also -//! lose funds if they vote poorly. -//! -//! An account can become a nominator via the [`nominate`](Call::nominate) call. -//! -//! #### Rewards and Slash -//! -//! The **reward and slashing** procedure is the core of the Staking pallet, attempting to _embrace -//! valid behavior_ while _punishing any misbehavior or lack of availability_. -//! -//! Rewards must be claimed for each era before it gets too old by `$HISTORY_DEPTH` using the -//! `payout_stakers` call. Any account can call `payout_stakers`, which pays the reward to the -//! validator as well as its nominators. Only the [`Config::MaxNominatorRewardedPerValidator`] -//! biggest stakers can claim their reward. This is to limit the i/o cost to mutate storage for each -//! nominator's account. -//! -//! Slashing can occur at any point in time, once misbehavior is reported. Once slashing is -//! determined, a value is deducted from the balance of the validator and all the nominators who -//! voted for this validator (values are deducted from the _stash_ account of the slashed entity). -//! -//! Slashing logic is further described in the documentation of the `slashing` pallet. -//! -//! Similar to slashing, rewards are also shared among a validator and its associated nominators. -//! Yet, the reward funds are not always transferred to the stash account and can be configured. See -//! [Reward Calculation](#reward-calculation) for more details. -//! -//! #### Chilling -//! -//! Finally, any of the roles above can choose to step back temporarily and just chill for a while. -//! This means that if they are a nominator, they will not be considered as voters anymore and if -//! they are validators, they will no longer be a candidate for the next election. -//! -//! An account can step back via the [`chill`](Call::chill) call. -//! -//! ### Session managing -//! -//! The pallet implement the trait `SessionManager`. Which is the only API to query new validator -//! set and allowing these validator set to be rewarded once their era is ended. -//! -//! ## Interface -//! -//! ### Dispatchable Functions -//! -//! The dispatchable functions of the Staking pallet enable the steps needed for entities to accept -//! and change their role, alongside some helper functions to get/set the metadata of the pallet. -//! -//! ### Public Functions -//! -//! The Staking pallet contains many public storage items and (im)mutable functions. -//! -//! ## Usage -//! -//! ### Example: Rewarding a validator by id. -//! -//! ``` -//! use frame_support::{decl_module, dispatch}; -//! use frame_system::ensure_signed; -//! use serp_staking::{self as staking}; -//! -//! pub trait Config: staking::Config {} -//! -//! decl_module! { -//! pub struct Module for enum Call where origin: T::Origin { -//! /// Reward a validator. -//! #[weight = 0] -//! pub fn reward_myself(origin) -> dispatch::DispatchResult { -//! let reported = ensure_signed(origin)?; -//! >::reward_by_ids(vec![(reported, 10)]); -//! Ok(()) -//! } -//! } -//! } -//! # fn main() { } -//! ``` -//! -//! ## Implementation Details -//! -//! ### Era payout -//! -//! The era payout is computed using yearly inflation curve defined at -//! [`Config::EraPayout`] as such: -//! -//! ```nocompile -//! staker_payout = yearly_inflation(npos_token_staked / total_tokens) * total_tokens / era_per_year -//! ``` -//! This payout is used to reward stakers as defined in next section -//! -//! ### Reward Calculation -//! -//! Validators and nominators are rewarded at the end of each era. The total reward of an era is -//! calculated using the era duration and the staking rate (the total amount of tokens staked by -//! nominators and validators, divided by the total token supply). It aims to incentivize toward a -//! defined staking rate. The full specification can be found -//! [here](https://research.web3.foundation/en/latest/polkadot/Token%20Economics.html#inflation-model). -//! -//! Total reward is split among validators and their nominators depending on the number of points -//! they received during the era. Points are added to a validator using -//! [`reward_by_ids`](Pallet::reward_by_ids). -//! -//! [`Pallet`] implements -//! [`pallet_authorship::EventHandler`] to add reward -//! points to block producer and block producer of referenced uncles. -//! -//! The validator and its nominator split their reward as following: -//! -//! The validator can declare an amount, named -//! [`commission`](ValidatorPrefs::commission), that does not get shared -//! with the nominators at each reward payout through its -//! [`ValidatorPrefs`]. This value gets deducted from the total reward -//! that is paid to the validator and its nominators. The remaining portion is split among the -//! validator and all of the nominators that nominated the validator, proportional to the value -//! staked behind this validator (_i.e._ dividing the -//! [`own`](Exposure::own) or -//! [`others`](Exposure::others) by -//! [`total`](Exposure::total) in [`Exposure`]). -//! -//! All entities who receive a reward have the option to choose their reward destination through the -//! [`Payee`] storage item (see -//! [`set_payee`](Call::set_payee)), to be one of the following: -//! -//! - Controller account, (obviously) not increasing the staked value. -//! - Stash account, not increasing the staked value. -//! - Stash account, also increasing the staked value. -//! -//! ### Additional Fund Management Operations -//! -//! Any funds already placed into stash can be the target of the following operations: -//! -//! The controller account can free a portion (or all) of the funds using the -//! [`unbond`](Call::unbond) call. Note that the funds are not immediately -//! accessible. Instead, a duration denoted by -//! [`Config::BondingDuration`] (in number of eras) must -//! pass until the funds can actually be removed. Once the `BondingDuration` is over, the -//! [`withdraw_unbonded`](Call::withdraw_unbonded) call can be used to actually -//! withdraw the funds. -//! -//! Note that there is a limitation to the number of fund-chunks that can be scheduled to be -//! unlocked in the future via [`unbond`](Call::unbond). In case this maximum -//! (`MAX_UNLOCKING_CHUNKS`) is reached, the bonded account _must_ first wait until a successful -//! call to `withdraw_unbonded` to remove some of the chunks. -//! -//! ### Election Algorithm -//! -//! The current election algorithm is implemented based on Phragmén. The reference implementation -//! can be found [here](https://github.com/w3f/consensus/tree/master/NPoS). -//! -//! The election algorithm, aside from electing the validators with the most stake value and votes, -//! tries to divide the nominator votes among candidates in an equal manner. To further assure this, -//! an optional post-processing can be applied that iteratively normalizes the nominator staked -//! values until the total difference among votes of a particular nominator are less than a -//! threshold. -//! -//! ## GenesisConfig -//! -//! The Staking pallet depends on the [`GenesisConfig`]. The -//! `GenesisConfig` is optional and allow to set some initial stakers. -//! -//! ## Related Modules -//! -//! - [Balances](../pallet_balances/index.html): Used to manage values at stake. -//! - [Session](../pallet_session/index.html): Used to manage sessions. Also, a list of new -//! validators is stored in the Session pallet's `Validators` at the end of each era. - -#![recursion_limit = "128"] -#![cfg_attr(not(feature = "std"), no_std)] - -#[cfg(any(feature = "runtime-benchmarks", test))] -pub mod benchmarking; -#[cfg(test)] -mod mock; -#[cfg(any(feature = "runtime-benchmarks", test))] -pub mod testing_utils; -#[cfg(test)] -mod tests; - -pub mod inflation; -pub mod slashing; -pub mod weights; - -use codec::{Decode, Encode, HasCompact}; -use frame_election_provider_support::{data_provider, ElectionProvider, Supports, VoteWeight}; -use frame_support::{ - pallet_prelude::*, - traits::{ - Currency, CurrencyToVote, EnsureOrigin, EstimateNextNewSession, Get, Imbalance, - LockIdentifier, LockableCurrency, OnUnbalanced, UnixTime, WithdrawReasons, - }, - weights::{ - constants::{WEIGHT_PER_MICROS, WEIGHT_PER_NANOS}, - Weight, WithPostDispatchInfo, - }, -}; -use frame_system::{ensure_root, ensure_signed, offchain::SendTransactionTypes, pallet_prelude::*}; -pub use pallet::*; -use pallet_session::historical; -use sp_runtime::{ - curve::PiecewiseLinear, - traits::{ - AtLeast32BitUnsigned, Bounded, CheckedSub, Convert, SaturatedConversion, Saturating, - StaticLookup, Zero, - }, - DispatchError, Perbill, Percent, RuntimeDebug, -}; -use sp_staking::{ - offence::{Offence, OffenceDetails, OffenceError, OnOffenceHandler, ReportOffence}, - SessionIndex, -}; -use sp_std::{collections::btree_map::BTreeMap, convert::From, prelude::*, result}; -pub use weights::WeightInfo; - -use orml_traits::{GetByKey, MultiCurrency, MultiCurrencyExtended}; -use prices::*; -use primitives::{Amount, Balance, BlockNumber, CurrencyId}; -use support::{ - Price, PriceProvider, Rate, Ratio, -}; - -const STAKING_ID: LockIdentifier = *b"staking "; -pub(crate) const LOG_TARGET: &'static str = "runtime::staking"; - -// syntactic sugar for logging. -#[macro_export] -macro_rules! log { - ($level:tt, $patter:expr $(, $values:expr)* $(,)?) => { - log::$level!( - target: crate::LOG_TARGET, - concat!("[{:?}] 💸 ", $patter), >::block_number() $(, $values)* - ) - }; -} - -pub const MAX_UNLOCKING_CHUNKS: usize = 32; - -/// Counter for the number of eras that have passed. -pub type EraIndex = u32; - -/// Counter for the number of "reward" points earned by a given validator. -pub type RewardPoint = u32; - -/// The balance type of this pallet. -pub type BalanceOf = - <::Currency as Currency<::AccountId>>::Balance; - -type PositiveImbalanceOf = <::Currency as Currency< - ::AccountId, ->>::PositiveImbalance; -type NegativeImbalanceOf = <::Currency as Currency< - ::AccountId, ->>::NegativeImbalance; - -/// Information regarding the active era (era in used in session). -#[derive(Encode, Decode, RuntimeDebug)] -pub struct ActiveEraInfo { - /// Index of era. - pub index: EraIndex, - /// Moment of start expressed as millisecond from `$UNIX_EPOCH`. - /// - /// Start can be none if start hasn't been set for the era yet, - /// Start is set on the first on_finalize of the era to guarantee usage of `Time`. - start: Option, -} - -/// Reward points of an era. Used to split era total payout between validators. -/// -/// This points will be used to reward validators and their respective nominators. -#[derive(PartialEq, Encode, Decode, Default, RuntimeDebug)] -pub struct EraRewardPoints { - /// Total number of points. Equals the sum of reward points for each validator. - total: RewardPoint, - /// The reward points earned by a given validator. - individual: BTreeMap, -} - -/// Indicates the initial status of the staker. -#[derive(RuntimeDebug)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -pub enum StakerStatus { - /// Chilling. - Idle, - /// Declared desire in validating or already participating in it. - Validator, - /// Nominating for a group of other stakers. - Nominator(Vec), -} - -/// A destination account for payment. -#[derive(PartialEq, Eq, Copy, Clone, Encode, Decode, RuntimeDebug)] -pub enum RewardDestination { - /// Pay into the stash account, increasing the amount at stake accordingly. - Staked, - /// Pay into the stash account, not increasing the amount at stake. - Stash, - /// Pay into the controller account. - Controller, - /// Pay into a specified account. - Account(AccountId), - /// Receive no reward. - None, -} - -impl Default for RewardDestination { - fn default() -> Self { - RewardDestination::Staked - } -} - -/// Preference of what happens regarding validation. -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] -pub struct ValidatorPrefs { - /// Reward that validator takes up-front; only the rest is split between themselves and - /// nominators. - #[codec(compact)] - pub commission: Perbill, - /// Whether or not this validator is accepting more nominations. If `true`, then no nominator - /// who is not already nominating this validator may nominate them. By default, validators - /// are accepting nominations. - pub blocked: bool, -} - -impl Default for ValidatorPrefs { - fn default() -> Self { - ValidatorPrefs { commission: Default::default(), blocked: false } - } -} - -/// Just a Balance/BlockNumber tuple to encode when a chunk of funds will be unlocked. -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] -pub struct UnlockChunk { - /// Amount of funds to be unlocked. - #[codec(compact)] - value: Balance, - /// Era number at which point it'll be unlocked. - #[codec(compact)] - era: EraIndex, -} - -/// The ledger of a (bonded) stash. -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] -pub struct StakingLedger { - /// The stash account whose balance is actually locked and at stake. - pub stash: AccountId, - /// The total amount of the stash's balance that we are currently accounting for. - /// It's just `active` plus all the `unlocking` balances. - #[codec(compact)] - pub total: Balance, - /// The total amount of the stash's balance that will be at stake in any forthcoming - /// rounds. - #[codec(compact)] - pub active: Balance, - /// Any balance that is becoming free, which may eventually be transferred out - /// of the stash (assuming it doesn't get slashed first). - pub unlocking: Vec>, - /// List of eras for which the stakers behind a validator have claimed rewards. Only updated - /// for validators. - pub claimed_rewards: Vec, -} - -impl - StakingLedger -{ - /// Remove entries from `unlocking` that are sufficiently old and reduce the - /// total by the sum of their balances. - fn consolidate_unlocked(self, current_era: EraIndex) -> Self { - let mut total = self.total; - let unlocking = self - .unlocking - .into_iter() - .filter(|chunk| { - if chunk.era > current_era { - true - } else { - total = total.saturating_sub(chunk.value); - false - } - }) - .collect(); - - Self { - stash: self.stash, - total, - active: self.active, - unlocking, - claimed_rewards: self.claimed_rewards, - } - } - - /// Re-bond funds that were scheduled for unlocking. - fn rebond(mut self, value: Balance) -> Self { - let mut unlocking_balance: Balance = Zero::zero(); - - while let Some(last) = self.unlocking.last_mut() { - if unlocking_balance + last.value <= value { - unlocking_balance += last.value; - self.active += last.value; - self.unlocking.pop(); - } else { - let diff = value - unlocking_balance; - - unlocking_balance += diff; - self.active += diff; - last.value -= diff; - } - - if unlocking_balance >= value { - break - } - } - - self - } -} - -impl StakingLedger -where - Balance: AtLeast32BitUnsigned + Saturating + Copy, -{ - /// Slash the validator for a given amount of balance. This can grow the value - /// of the slash in the case that the validator has less than `minimum_balance` - /// active funds. Returns the amount of funds actually slashed. - /// - /// Slashes from `active` funds first, and then `unlocking`, starting with the - /// chunks that are closest to unlocking. - fn slash(&mut self, mut value: Balance, minimum_balance: Balance) -> Balance { - let pre_total = self.total; - let total = &mut self.total; - let active = &mut self.active; - - let slash_out_of = - |total_remaining: &mut Balance, target: &mut Balance, value: &mut Balance| { - let mut slash_from_target = (*value).min(*target); - - if !slash_from_target.is_zero() { - *target -= slash_from_target; - - // Don't leave a dust balance in the staking system. - if *target <= minimum_balance { - slash_from_target += *target; - *value += sp_std::mem::replace(target, Zero::zero()); - } - - *total_remaining = total_remaining.saturating_sub(slash_from_target); - *value -= slash_from_target; - } - }; - - slash_out_of(total, active, &mut value); - - let i = self - .unlocking - .iter_mut() - .map(|chunk| { - slash_out_of(total, &mut chunk.value, &mut value); - chunk.value - }) - .take_while(|value| value.is_zero()) // Take all fully-consumed chunks out. - .count(); - - // Kill all drained chunks. - let _ = self.unlocking.drain(..i); - - pre_total.saturating_sub(*total) - } -} - -/// A record of the nominations made by a specific account. -#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] -pub struct Nominations { - /// The targets of nomination. - pub targets: Vec, - /// The era the nominations were submitted. - /// - /// Except for initial nominations which are considered submitted at era 0. - pub submitted_in: EraIndex, - /// Whether the nominations have been suppressed. This can happen due to slashing of the - /// validators, or other events that might invalidate the nomination. - /// - /// NOTE: this for future proofing and is thus far not used. - pub suppressed: bool, -} - -/// The amount of exposure (to slashing) than an individual nominator has. -#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, RuntimeDebug)] -pub struct IndividualExposure { - /// The stash account of the nominator in question. - pub who: AccountId, - /// Amount of funds exposed. - #[codec(compact)] - pub value: Balance, -} - -/// A snapshot of the stake backing a single validator in the system. -#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, Default, RuntimeDebug)] -pub struct Exposure { - /// The total balance backing this validator. - #[codec(compact)] - pub total: Balance, - /// The validator's own stash that is exposed. - #[codec(compact)] - pub own: Balance, - /// The portions of nominators stashes that are exposed. - pub others: Vec>, -} - -/// A pending slash record. The value of the slash has been computed but not applied yet, -/// rather deferred for several eras. -#[derive(Encode, Decode, Default, RuntimeDebug)] -pub struct UnappliedSlash { - /// The stash ID of the offending validator. - validator: AccountId, - /// The validator's own slash. - own: Balance, - /// All other slashed stakers and amounts. - others: Vec<(AccountId, Balance)>, - /// Reporters of the offence; bounty payout recipients. - reporters: Vec, - /// The amount of payout. - payout: Balance, -} - -/// Means for interacting with a specialized version of the `session` trait. -/// -/// This is needed because `Staking` sets the `ValidatorIdOf` of the `pallet_session::Config` -pub trait SessionInterface: frame_system::Config { - /// Disable a given validator by stash ID. - /// - /// Returns `true` if new era should be forced at the end of this session. - /// This allows preventing a situation where there is too many validators - /// disabled and block production stalls. - fn disable_validator(validator: &AccountId) -> Result; - /// Get the validators from session. - fn validators() -> Vec; - /// Prune historical session tries up to but not including the given index. - fn prune_historical_up_to(up_to: SessionIndex); -} - -impl SessionInterface<::AccountId> for T -where - T: pallet_session::Config::AccountId>, - T: pallet_session::historical::Config< - FullIdentification = Exposure<::AccountId, BalanceOf>, - FullIdentificationOf = ExposureOf, - >, - T::SessionHandler: pallet_session::SessionHandler<::AccountId>, - T::SessionManager: pallet_session::SessionManager<::AccountId>, - T::ValidatorIdOf: Convert< - ::AccountId, - Option<::AccountId>, - >, -{ - fn disable_validator(validator: &::AccountId) -> Result { - >::disable(validator) - } - - fn validators() -> Vec<::AccountId> { - >::validators() - } - - fn prune_historical_up_to(up_to: SessionIndex) { - >::prune_up_to(up_to); - } -} - -/// Handler for determining how much of a balance should be paid out on the current era. -pub trait EraPayout { - /// Determine the payout for this era. - /// - /// Returns the amount to be paid to stakers in this era, as well as whatever else should be - /// paid out ("the rest"). - fn era_payout( - total_staked: Balance, - total_issuance: Balance, - era_duration_millis: u64, - ) -> (Balance, Balance); -} - -impl EraPayout for () { - fn era_payout( - _total_staked: Balance, - _total_issuance: Balance, - _era_duration_millis: u64, - ) -> (Balance, Balance) { - (Default::default(), Default::default()) - } -} - -/// Adaptor to turn a `PiecewiseLinear` curve definition into an `EraPayout` impl, used for -/// backwards compatibility. -pub struct ConvertCurve(sp_std::marker::PhantomData); -impl>> - EraPayout for ConvertCurve -{ - fn era_payout( - total_staked: Balance, - total_issuance: Balance, - era_duration_millis: u64, - ) -> (Balance, Balance) { - let (validator_payout, max_payout) = inflation::compute_total_payout( - &T::get(), - total_staked, - total_issuance, - // Duration of era; more than u64::MAX is rewarded as u64::MAX. - era_duration_millis, - ); - let rest = max_payout.saturating_sub(validator_payout.clone()); - (validator_payout, rest) - } -} - -/// Mode of era-forcing. -#[derive(Copy, Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -pub enum Forcing { - /// Not forcing anything - just let whatever happen. - NotForcing, - /// Force a new era, then reset to `NotForcing` as soon as it is done. - /// Note that this will force to trigger an election until a new era is triggered, if the - /// election failed, the next session end will trigger a new election again, until success. - ForceNew, - /// Avoid a new era indefinitely. - ForceNone, - /// Force a new era at the end of all sessions indefinitely. - ForceAlways, -} - -impl Default for Forcing { - fn default() -> Self { - Forcing::NotForcing - } -} - -// A value placed in storage that represents the current version of the Staking storage. This value -// is used by the `on_runtime_upgrade` logic to determine whether we run storage migration logic. -// This should match directly with the semantic versions of the Rust crate. -#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug)] -enum Releases { - V1_0_0Ancient, - V2_0_0, - V3_0_0, - V4_0_0, - V5_0_0, // blockable validators. - V6_0_0, // removal of all storage associated with offchain phragmen. - V7_0_0, // keep track of number of nominators / validators in map -} - -impl Default for Releases { - fn default() -> Self { - Releases::V7_0_0 - } -} - -pub mod migrations { - use super::*; - - pub mod v7 { - use super::*; - - pub fn pre_migrate() -> Result<(), &'static str> { - assert!( - CounterForValidators::::get().is_zero(), - "CounterForValidators already set." - ); - assert!( - CounterForNominators::::get().is_zero(), - "CounterForNominators already set." - ); - assert!(StorageVersion::::get() == Releases::V6_0_0); - Ok(()) - } - - pub fn migrate() -> Weight { - log!(info, "Migrating staking to Releases::V7_0_0"); - let validator_count = Validators::::iter().count() as u32; - let nominator_count = Nominators::::iter().count() as u32; - - CounterForValidators::::put(validator_count); - CounterForNominators::::put(nominator_count); - - StorageVersion::::put(Releases::V7_0_0); - log!(info, "Completed staking migration to Releases::V7_0_0"); - - T::DbWeight::get() - .reads_writes(validator_count.saturating_add(nominator_count).into(), 2) - } - } - - pub mod v6 { - use super::*; - use frame_support::{generate_storage_alias, traits::Get, weights::Weight}; - - // NOTE: value type doesn't matter, we just set it to () here. - generate_storage_alias!(Staking, SnapshotValidators => Value<()>); - generate_storage_alias!(Staking, SnapshotNominators => Value<()>); - generate_storage_alias!(Staking, QueuedElected => Value<()>); - generate_storage_alias!(Staking, QueuedScore => Value<()>); - generate_storage_alias!(Staking, EraElectionStatus => Value<()>); - generate_storage_alias!(Staking, IsCurrentSessionFinal => Value<()>); - - /// check to execute prior to migration. - pub fn pre_migrate() -> Result<(), &'static str> { - // these may or may not exist. - log!(info, "SnapshotValidators.exits()? {:?}", SnapshotValidators::exists()); - log!(info, "SnapshotNominators.exits()? {:?}", SnapshotNominators::exists()); - log!(info, "QueuedElected.exits()? {:?}", QueuedElected::exists()); - log!(info, "QueuedScore.exits()? {:?}", QueuedScore::exists()); - // these must exist. - assert!( - IsCurrentSessionFinal::exists(), - "IsCurrentSessionFinal storage item not found!" - ); - assert!(EraElectionStatus::exists(), "EraElectionStatus storage item not found!"); - Ok(()) - } - - /// Migrate storage to v6. - pub fn migrate() -> Weight { - log!(info, "Migrating staking to Releases::V6_0_0"); - - SnapshotValidators::kill(); - SnapshotNominators::kill(); - QueuedElected::kill(); - QueuedScore::kill(); - EraElectionStatus::kill(); - IsCurrentSessionFinal::kill(); - - StorageVersion::::put(Releases::V6_0_0); - log!(info, "Done."); - T::DbWeight::get().writes(6 + 1) - } - } -} - -#[frame_support::pallet] -pub mod pallet { - use super::*; - - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - pub struct Pallet(_); - - #[pallet::config] - pub trait Config: frame_system::Config + SendTransactionTypes> { - /// The staking balance. - type Currency: LockableCurrency; - - /// The Currency for managing assets related to the SERP (Setheum Elastic Reserve Protocol). - type MultiCurrency: MultiCurrencyExtended; - - /// The Incentive reward type (SETR) - /// SETR in Setheum. - #[pallet::constant] - type SetterCurrencyId: Get; - - /// The Premium reward type (DRAM) - /// DRAM in Setheum. - #[pallet::constant] - type DirhamCurrencyId: Get; - - /// The Native Currency type (DNAR) - /// DNAR in Setheum. - #[pallet::constant] - type NativeCurrencyId: Get; - - /// The price source of all types of currencies related to Settmint - type PriceSource: PriceProvider; - - /// Time used for computing era duration. - /// - /// It is guaranteed to start being called from the first `on_finalize`. Thus value at genesis - /// is not used. - type UnixTime: UnixTime; - - /// Convert a balance into a number used for election calculation. This must fit into a `u64` - /// but is allowed to be sensibly lossy. The `u64` is used to communicate with the - /// [`sp_npos_elections`] crate which accepts u64 numbers and does operations in 128. - /// Consequently, the backward convert is used convert the u128s from sp-elections back to a - /// [`BalanceOf`]. - type CurrencyToVote: CurrencyToVote>; - - /// Something that provides the election functionality. - type ElectionProvider: frame_election_provider_support::ElectionProvider< - Self::AccountId, - Self::BlockNumber, - // we only accept an election provider that has staking as data provider. - DataProvider = Pallet, - >; - - /// Something that provides the election functionality at genesis. - type GenesisElectionProvider: frame_election_provider_support::ElectionProvider< - Self::AccountId, - Self::BlockNumber, - DataProvider = Pallet, - >; - - /// Maximum number of nominations per nominator. - const MAX_NOMINATIONS: u32; - - /// The overarching event type. - type Event: From> + IsType<::Event>; - - /// Handler for the unbalanced reduction when slashing a staker. - type Slash: OnUnbalanced>; - - /// Handler for the unbalanced increment when rewarding a staker. - type Reward: OnUnbalanced>; - - /// Number of sessions per era. - #[pallet::constant] - type SessionsPerEra: Get; - - /// Number of eras that staked funds must remain bonded for. - #[pallet::constant] - type BondingDuration: Get; - - /// Number of eras that slashes are deferred by, after computation. - /// - /// This should be less than the bonding duration. Set to 0 if slashes - /// should be applied immediately, without opportunity for intervention. - #[pallet::constant] - type SlashDeferDuration: Get; - - /// The origin which can cancel a deferred slash. Root can always do this. - type SlashCancelOrigin: EnsureOrigin; - - /// Interface for interacting with a session pallet. - type SessionInterface: self::SessionInterface; - - /// The payout for validators and the system for the current era. - /// See [Era payout](./index.html#era-payout). - type EraPayout: EraPayout>; - - /// Something that can estimate the next session change, accurately or as a best effort guess. - type NextNewSession: EstimateNextNewSession; - - /// The maximum number of nominators rewarded for each validator. - /// - /// For each validator only the `$MaxNominatorRewardedPerValidator` biggest stakers can claim - /// their reward. This used to limit the i/o cost for the nominator payout. - #[pallet::constant] - type MaxNominatorRewardedPerValidator: Get; - - /// Weight information for extrinsics in this pallet. - type WeightInfo: WeightInfo; - } - - #[pallet::extra_constants] - impl Pallet { - // TODO: rename to snake case after https://github.com/paritytech/substrate/issues/8826 fixed. - #[allow(non_snake_case)] - fn MaxNominations() -> u32 { - T::MAX_NOMINATIONS - } - } - - #[pallet::type_value] - pub(crate) fn HistoryDepthOnEmpty() -> u32 { - 84u32 - } - - /// Number of eras to keep in history. - /// - /// Information is kept for eras in `[current_era - history_depth; current_era]`. - /// - /// Must be more than the number of eras delayed by session otherwise. I.e. active era must - /// always be in history. I.e. `active_era > current_era - history_depth` must be - /// guaranteed. - #[pallet::storage] - #[pallet::getter(fn history_depth)] - pub(crate) type HistoryDepth = StorageValue<_, u32, ValueQuery, HistoryDepthOnEmpty>; - - /// The ideal number of staking participants. - #[pallet::storage] - #[pallet::getter(fn validator_count)] - pub type ValidatorCount = StorageValue<_, u32, ValueQuery>; - - /// Minimum number of staking participants before emergency conditions are imposed. - #[pallet::storage] - #[pallet::getter(fn minimum_validator_count)] - pub type MinimumValidatorCount = StorageValue<_, u32, ValueQuery>; - - /// Any validators that may never be slashed or forcibly kicked. It's a Vec since they're - /// easy to initialize and the performance hit is minimal (we expect no more than four - /// invulnerables) and restricted to testnets. - #[pallet::storage] - #[pallet::getter(fn invulnerables)] - pub type Invulnerables = StorageValue<_, Vec, ValueQuery>; - - /// Map from all locked "stash" accounts to the controller account. - #[pallet::storage] - #[pallet::getter(fn bonded)] - pub type Bonded = StorageMap<_, Twox64Concat, T::AccountId, T::AccountId>; - - /// The minimum active bond to become and maintain the role of a nominator. - #[pallet::storage] - pub type MinNominatorBond = StorageValue<_, BalanceOf, ValueQuery>; - - /// The minimum active bond to become and maintain the role of a validator. - #[pallet::storage] - pub type MinValidatorBond = StorageValue<_, BalanceOf, ValueQuery>; - - /// Map from all (unlocked) "controller" accounts to the info regarding the staking. - #[pallet::storage] - #[pallet::getter(fn ledger)] - pub type Ledger = - StorageMap<_, Blake2_128Concat, T::AccountId, StakingLedger>>; - - /// Where the reward payment should be made. Keyed by stash. - #[pallet::storage] - #[pallet::getter(fn payee)] - pub type Payee = - StorageMap<_, Twox64Concat, T::AccountId, RewardDestination, ValueQuery>; - - /// The map from (wannabe) validator stash key to the preferences of that validator. - /// - /// When updating this storage item, you must also update the `CounterForValidators`. - #[pallet::storage] - #[pallet::getter(fn validators)] - pub type Validators = - StorageMap<_, Twox64Concat, T::AccountId, ValidatorPrefs, ValueQuery>; - - /// A tracker to keep count of the number of items in the `Validators` map. - #[pallet::storage] - pub type CounterForValidators = StorageValue<_, u32, ValueQuery>; - - /// The maximum validator count before we stop allowing new validators to join. - /// - /// When this value is not set, no limits are enforced. - #[pallet::storage] - pub type MaxValidatorsCount = StorageValue<_, u32, OptionQuery>; - - /// The map from nominator stash key to the set of stash keys of all validators to nominate. - /// - /// When updating this storage item, you must also update the `CounterForNominators`. - #[pallet::storage] - #[pallet::getter(fn nominators)] - pub type Nominators = - StorageMap<_, Twox64Concat, T::AccountId, Nominations>; - - /// A tracker to keep count of the number of items in the `Nominators` map. - #[pallet::storage] - pub type CounterForNominators = StorageValue<_, u32, ValueQuery>; - - /// The maximum nominator count before we stop allowing new validators to join. - /// - /// When this value is not set, no limits are enforced. - #[pallet::storage] - pub type MaxNominatorsCount = StorageValue<_, u32, OptionQuery>; - - /// The current era index. - /// - /// This is the latest planned era, depending on how the Session pallet queues the validator - /// set, it might be active or not. - #[pallet::storage] - #[pallet::getter(fn current_era)] - pub type CurrentEra = StorageValue<_, EraIndex>; - - /// The active era information, it holds index and start. - /// - /// The active era is the era being currently rewarded. Validator set of this era must be - /// equal to [`SessionInterface::validators`]. - #[pallet::storage] - #[pallet::getter(fn active_era)] - pub type ActiveEra = StorageValue<_, ActiveEraInfo>; - - /// The session index at which the era start for the last `HISTORY_DEPTH` eras. - /// - /// Note: This tracks the starting session (i.e. session index when era start being active) - /// for the eras in `[CurrentEra - HISTORY_DEPTH, CurrentEra]`. - #[pallet::storage] - #[pallet::getter(fn eras_start_session_index)] - pub type ErasStartSessionIndex = StorageMap<_, Twox64Concat, EraIndex, SessionIndex>; - - /// Exposure of validator at era. - /// - /// This is keyed first by the era index to allow bulk deletion and then the stash account. - /// - /// Is it removed after `HISTORY_DEPTH` eras. - /// If stakers hasn't been set or has been removed then empty exposure is returned. - #[pallet::storage] - #[pallet::getter(fn eras_stakers)] - pub type ErasStakers = StorageDoubleMap< - _, - Twox64Concat, - EraIndex, - Twox64Concat, - T::AccountId, - Exposure>, - ValueQuery, - >; - - /// Clipped Exposure of validator at era. - /// - /// This is similar to [`ErasStakers`] but number of nominators exposed is reduced to the - /// `T::MaxNominatorRewardedPerValidator` biggest stakers. - /// (Note: the field `total` and `own` of the exposure remains unchanged). - /// This is used to limit the i/o cost for the nominator payout. - /// - /// This is keyed fist by the era index to allow bulk deletion and then the stash account. - /// - /// Is it removed after `HISTORY_DEPTH` eras. - /// If stakers hasn't been set or has been removed then empty exposure is returned. - #[pallet::storage] - #[pallet::getter(fn eras_stakers_clipped)] - pub type ErasStakersClipped = StorageDoubleMap< - _, - Twox64Concat, - EraIndex, - Twox64Concat, - T::AccountId, - Exposure>, - ValueQuery, - >; - - /// Similar to `ErasStakers`, this holds the preferences of validators. - /// - /// This is keyed first by the era index to allow bulk deletion and then the stash account. - /// - /// Is it removed after `HISTORY_DEPTH` eras. - // If prefs hasn't been set or has been removed then 0 commission is returned. - #[pallet::storage] - #[pallet::getter(fn eras_validator_prefs)] - pub type ErasValidatorPrefs = StorageDoubleMap< - _, - Twox64Concat, - EraIndex, - Twox64Concat, - T::AccountId, - ValidatorPrefs, - ValueQuery, - >; - - /// The total validator era payout for the last `HISTORY_DEPTH` eras. - /// - /// Eras that haven't finished yet or has been removed doesn't have reward. - #[pallet::storage] - #[pallet::getter(fn eras_validator_reward)] - pub type ErasValidatorReward = StorageMap<_, Twox64Concat, EraIndex, BalanceOf>; - - /// Rewards for the last `HISTORY_DEPTH` eras. - /// If reward hasn't been set or has been removed then 0 reward is returned. - #[pallet::storage] - #[pallet::getter(fn eras_reward_points)] - pub type ErasRewardPoints = - StorageMap<_, Twox64Concat, EraIndex, EraRewardPoints, ValueQuery>; - - /// The total amount staked for the last `HISTORY_DEPTH` eras. - /// If total hasn't been set or has been removed then 0 stake is returned. - #[pallet::storage] - #[pallet::getter(fn eras_total_stake)] - pub type ErasTotalStake = - StorageMap<_, Twox64Concat, EraIndex, BalanceOf, ValueQuery>; - - /// Mode of era forcing. - #[pallet::storage] - #[pallet::getter(fn force_era)] - pub type ForceEra = StorageValue<_, Forcing, ValueQuery>; - - /// The percentage of the slash that is distributed to reporters. - /// - /// The rest of the slashed value is handled by the `Slash`. - #[pallet::storage] - #[pallet::getter(fn slash_reward_fraction)] - pub type SlashRewardFraction = StorageValue<_, Perbill, ValueQuery>; - - /// The amount of currency given to reporters of a slash event which was - /// canceled by extraordinary circumstances (e.g. governance). - #[pallet::storage] - #[pallet::getter(fn canceled_payout)] - pub type CanceledSlashPayout = StorageValue<_, BalanceOf, ValueQuery>; - - /// All unapplied slashes that are queued for later. - #[pallet::storage] - pub type UnappliedSlashes = StorageMap< - _, - Twox64Concat, - EraIndex, - Vec>>, - ValueQuery, - >; - - /// A mapping from still-bonded eras to the first session index of that era. - /// - /// Must contains information for eras for the range: - /// `[active_era - bounding_duration; active_era]` - #[pallet::storage] - pub(crate) type BondedEras = - StorageValue<_, Vec<(EraIndex, SessionIndex)>, ValueQuery>; - - /// All slashing events on validators, mapped by era to the highest slash proportion - /// and slash value of the era. - #[pallet::storage] - pub(crate) type ValidatorSlashInEra = StorageDoubleMap< - _, - Twox64Concat, - EraIndex, - Twox64Concat, - T::AccountId, - (Perbill, BalanceOf), - >; - - /// All slashing events on nominators, mapped by era to the highest slash value of the era. - #[pallet::storage] - pub(crate) type NominatorSlashInEra = - StorageDoubleMap<_, Twox64Concat, EraIndex, Twox64Concat, T::AccountId, BalanceOf>; - - /// Slashing spans for stash accounts. - #[pallet::storage] - pub(crate) type SlashingSpans = - StorageMap<_, Twox64Concat, T::AccountId, slashing::SlashingSpans>; - - /// Records information about the maximum slash of a stash within a slashing span, - /// as well as how much reward has been paid out. - #[pallet::storage] - pub(crate) type SpanSlash = StorageMap< - _, - Twox64Concat, - (T::AccountId, slashing::SpanIndex), - slashing::SpanRecord>, - ValueQuery, - >; - - /// The earliest era for which we have a pending, unapplied slash. - #[pallet::storage] - pub(crate) type EarliestUnappliedSlash = StorageValue<_, EraIndex>; - - /// The last planned session scheduled by the session pallet. - /// - /// This is basically in sync with the call to [`pallet_session::SessionManager::new_session`]. - #[pallet::storage] - #[pallet::getter(fn current_planned_session)] - pub type CurrentPlannedSession = StorageValue<_, SessionIndex, ValueQuery>; - - /// True if network has been upgraded to this version. - /// Storage version of the pallet. - /// - /// This is set to v7.0.0 for new networks. - #[pallet::storage] - pub(crate) type StorageVersion = StorageValue<_, Releases, ValueQuery>; - - /// The threshold for when users can start calling `chill_other` for other validators / nominators. - /// The threshold is compared to the actual number of validators / nominators (`CountFor*`) in - /// the system compared to the configured max (`Max*Count`). - #[pallet::storage] - pub(crate) type ChillThreshold = StorageValue<_, Percent, OptionQuery>; - - #[pallet::genesis_config] - pub struct GenesisConfig { - pub history_depth: u32, - pub validator_count: u32, - pub minimum_validator_count: u32, - pub invulnerables: Vec, - pub force_era: Forcing, - pub slash_reward_fraction: Perbill, - pub canceled_payout: BalanceOf, - pub stakers: Vec<(T::AccountId, T::AccountId, BalanceOf, StakerStatus)>, - pub min_nominator_bond: BalanceOf, - pub min_validator_bond: BalanceOf, - } - - #[cfg(feature = "std")] - impl Default for GenesisConfig { - fn default() -> Self { - GenesisConfig { - history_depth: 84u32, - validator_count: Default::default(), - minimum_validator_count: Default::default(), - invulnerables: Default::default(), - force_era: Default::default(), - slash_reward_fraction: Default::default(), - canceled_payout: Default::default(), - stakers: Default::default(), - min_nominator_bond: Default::default(), - min_validator_bond: Default::default(), - } - } - } - - #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { - fn build(&self) { - HistoryDepth::::put(self.history_depth); - ValidatorCount::::put(self.validator_count); - MinimumValidatorCount::::put(self.minimum_validator_count); - Invulnerables::::put(&self.invulnerables); - ForceEra::::put(self.force_era); - CanceledSlashPayout::::put(self.canceled_payout); - SlashRewardFraction::::put(self.slash_reward_fraction); - StorageVersion::::put(Releases::V7_0_0); - MinNominatorBond::::put(self.min_nominator_bond); - MinValidatorBond::::put(self.min_validator_bond); - - for &(ref stash, ref controller, balance, ref status) in &self.stakers { - assert!( - T::Currency::free_balance(&stash) >= balance, - "Stash does not have enough balance to bond." - ); - let _ = >::bond( - T::Origin::from(Some(stash.clone()).into()), - T::Lookup::unlookup(controller.clone()), - balance, - RewardDestination::Staked, - ); - let _ = match status { - StakerStatus::Validator => >::validate( - T::Origin::from(Some(controller.clone()).into()), - Default::default(), - ), - StakerStatus::Nominator(votes) => >::nominate( - T::Origin::from(Some(controller.clone()).into()), - votes.iter().map(|l| T::Lookup::unlookup(l.clone())).collect(), - ), - _ => Ok(()), - }; - } - } - } - - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - #[pallet::metadata(T::AccountId = "AccountId", BalanceOf = "Balance")] - pub enum Event { - /// The era payout has been set; the first balance is the validator-payout; the second is - /// the remainder from the maximum amount of reward. - /// \[era_index, validator_payout, remainder\] - EraPayout(EraIndex, BalanceOf, BalanceOf), - /// The staker has been rewarded by this amount. \[stash, amount\] - Reward(T::AccountId, BalanceOf), - /// One validator (and its nominators) has been slashed by the given amount. - /// \[validator, amount\] - Slash(T::AccountId, BalanceOf), - /// An old slashing report from a prior era was discarded because it could - /// not be processed. \[session_index\] - OldSlashingReportDiscarded(SessionIndex), - /// A new set of stakers was elected. - StakingElection, - /// An account has bonded this amount. \[stash, amount\] - /// - /// NOTE: This event is only emitted when funds are bonded via a dispatchable. Notably, - /// it will not be emitted for staking rewards when they are added to stake. - Bonded(T::AccountId, BalanceOf), - /// An account has unbonded this amount. \[stash, amount\] - Unbonded(T::AccountId, BalanceOf), - /// An account has called `withdraw_unbonded` and removed unbonding chunks worth `Balance` - /// from the unlocking queue. \[stash, amount\] - Withdrawn(T::AccountId, BalanceOf), - /// A nominator has been kicked from a validator. \[nominator, stash\] - Kicked(T::AccountId, T::AccountId), - /// The election failed. No new era is planned. - StakingElectionFailed, - /// An account has stopped participating as either a validator or nominator. - /// \[stash\] - Chilled(T::AccountId), - } - - #[pallet::error] - pub enum Error { - /// Not a controller account. - NotController, - /// Not a stash account. - NotStash, - /// Stash is already bonded. - AlreadyBonded, - /// Controller is already paired. - AlreadyPaired, - /// Targets cannot be empty. - EmptyTargets, - /// Duplicate index. - DuplicateIndex, - /// Slash record index out of bounds. - InvalidSlashIndex, - /// Can not bond with value less than minimum required. - InsufficientBond, - /// Can not schedule more unlock chunks. - NoMoreChunks, - /// Can not rebond without unlocking chunks. - NoUnlockChunk, - /// Attempting to target a stash that still has funds. - FundedTarget, - /// Invalid era to reward. - InvalidEraToReward, - /// Invalid number of nominations. - InvalidNumberOfNominations, - /// Items are not sorted and unique. - NotSortedAndUnique, - /// Rewards for this era have already been claimed for this validator. - AlreadyClaimed, - /// Incorrect previous history depth input provided. - IncorrectHistoryDepth, - /// Incorrect number of slashing spans provided. - IncorrectSlashingSpans, - /// Internal state has become somehow corrupted and the operation cannot continue. - BadState, - /// Too many nomination targets supplied. - TooManyTargets, - /// A nomination target was supplied that was blocked or otherwise not a validator. - BadTarget, - /// The user has enough bond and thus cannot be chilled forcefully by an external person. - CannotChillOther, - /// There are too many nominators in the system. Governance needs to adjust the staking settings - /// to keep things safe for the runtime. - TooManyNominators, - /// There are too many validators in the system. Governance needs to adjust the staking settings - /// to keep things safe for the runtime. - TooManyValidators, - } - - #[pallet::hooks] - impl Hooks> for Pallet { - fn on_runtime_upgrade() -> Weight { - if StorageVersion::::get() == Releases::V6_0_0 { - migrations::v7::migrate::() - } else { - T::DbWeight::get().reads(1) - } - } - - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result<(), &'static str> { - if StorageVersion::::get() == Releases::V6_0_0 { - migrations::v7::pre_migrate::() - } else { - Ok(()) - } - } - - fn on_initialize(_now: BlockNumberFor) -> Weight { - // just return the weight of the on_finalize. - T::DbWeight::get().reads(1) - } - - fn on_finalize(_n: BlockNumberFor) { - // Set the start of the first era. - if let Some(mut active_era) = Self::active_era() { - if active_era.start.is_none() { - let now_as_millis_u64 = T::UnixTime::now().as_millis().saturated_into::(); - active_era.start = Some(now_as_millis_u64); - // This write only ever happens once, we don't include it in the weight in general - ActiveEra::::put(active_era); - } - } - // `on_finalize` weight is tracked in `on_initialize` - } - - fn integrity_test() { - sp_std::if_std! { - sp_io::TestExternalities::new_empty().execute_with(|| - assert!( - T::SlashDeferDuration::get() < T::BondingDuration::get() || T::BondingDuration::get() == 0, - "As per documentation, slash defer duration ({}) should be less than bonding duration ({}).", - T::SlashDeferDuration::get(), - T::BondingDuration::get(), - ) - ); - } - } - } - - #[pallet::call] - impl Pallet { - /// Take the origin account as a stash and lock up `value` of its balance. `controller` will - /// be the account that controls it. - /// - /// `value` must be more than the `minimum_balance` specified by `T::Currency`. - /// - /// The dispatch origin for this call must be _Signed_ by the stash account. - /// - /// Emits `Bonded`. - /// # - /// - Independent of the arguments. Moderate complexity. - /// - O(1). - /// - Three extra DB entries. - /// - /// NOTE: Two of the storage writes (`Self::bonded`, `Self::payee`) are _never_ cleaned - /// unless the `origin` falls below _existential deposit_ and gets removed as dust. - /// ------------------ - /// # - #[pallet::weight(T::WeightInfo::bond())] - pub fn bond( - origin: OriginFor, - controller: ::Source, - #[pallet::compact] value: BalanceOf, - payee: RewardDestination, - ) -> DispatchResult { - let stash = ensure_signed(origin)?; - - if >::contains_key(&stash) { - Err(Error::::AlreadyBonded)? - } - - let controller = T::Lookup::lookup(controller)?; - - if >::contains_key(&controller) { - Err(Error::::AlreadyPaired)? - } - - // Reject a bond which is considered to be _dust_. - if value < T::Currency::minimum_balance() { - Err(Error::::InsufficientBond)? - } - - frame_system::Pallet::::inc_consumers(&stash).map_err(|_| Error::::BadState)?; - - // You're auto-bonded forever, here. We might improve this by only bonding when - // you actually validate/nominate and remove once you unbond __everything__. - >::insert(&stash, &controller); - >::insert(&stash, payee); - - let current_era = CurrentEra::::get().unwrap_or(0); - let history_depth = Self::history_depth(); - let last_reward_era = current_era.saturating_sub(history_depth); - - let stash_balance = T::Currency::free_balance(&stash); - let value = value.min(stash_balance); - Self::deposit_event(Event::::Bonded(stash.clone(), value)); - let item = StakingLedger { - stash, - total: value, - active: value, - unlocking: vec![], - claimed_rewards: (last_reward_era..current_era).collect(), - }; - Self::update_ledger(&controller, &item); - Ok(()) - } - - /// Add some extra amount that have appeared in the stash `free_balance` into the balance up - /// for staking. - /// - /// The dispatch origin for this call must be _Signed_ by the stash, not the controller. - /// - /// Use this if there are additional funds in your stash account that you wish to bond. - /// Unlike [`bond`](Self::bond) or [`unbond`](Self::unbond) this function does not impose any limitation - /// on the amount that can be added. - /// - /// Emits `Bonded`. - /// - /// # - /// - Independent of the arguments. Insignificant complexity. - /// - O(1). - /// # - #[pallet::weight(T::WeightInfo::bond_extra())] - pub fn bond_extra( - origin: OriginFor, - #[pallet::compact] max_additional: BalanceOf, - ) -> DispatchResult { - let stash = ensure_signed(origin)?; - - let controller = Self::bonded(&stash).ok_or(Error::::NotStash)?; - let mut ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - - let stash_balance = T::Currency::free_balance(&stash); - if let Some(extra) = stash_balance.checked_sub(&ledger.total) { - let extra = extra.min(max_additional); - ledger.total += extra; - ledger.active += extra; - // Last check: the new active amount of ledger must be more than ED. - ensure!( - ledger.active >= T::Currency::minimum_balance(), - Error::::InsufficientBond - ); - - Self::deposit_event(Event::::Bonded(stash, extra)); - Self::update_ledger(&controller, &ledger); - } - Ok(()) - } - - /// Schedule a portion of the stash to be unlocked ready for transfer out after the bond - /// period ends. If this leaves an amount actively bonded less than - /// T::Currency::minimum_balance(), then it is increased to the full amount. - /// - /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. - /// - /// Once the unlock period is done, you can call `withdraw_unbonded` to actually move - /// the funds out of management ready for transfer. - /// - /// No more than a limited number of unlocking chunks (see `MAX_UNLOCKING_CHUNKS`) - /// can co-exists at the same time. In that case, [`Call::withdraw_unbonded`] need - /// to be called first to remove some of the chunks (if possible). - /// - /// If a user encounters the `InsufficientBond` error when calling this extrinsic, - /// they should call `chill` first in order to free up their bonded funds. - /// - /// Emits `Unbonded`. - /// - /// See also [`Call::withdraw_unbonded`]. - #[pallet::weight(T::WeightInfo::unbond())] - pub fn unbond( - origin: OriginFor, - #[pallet::compact] value: BalanceOf, - ) -> DispatchResult { - let controller = ensure_signed(origin)?; - let mut ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - ensure!(ledger.unlocking.len() < MAX_UNLOCKING_CHUNKS, Error::::NoMoreChunks); - - let mut value = value.min(ledger.active); - - if !value.is_zero() { - ledger.active -= value; - - // Avoid there being a dust balance left in the staking system. - if ledger.active < T::Currency::minimum_balance() { - value += ledger.active; - ledger.active = Zero::zero(); - } - - let min_active_bond = if Nominators::::contains_key(&ledger.stash) { - MinNominatorBond::::get() - } else if Validators::::contains_key(&ledger.stash) { - MinValidatorBond::::get() - } else { - Zero::zero() - }; - - // Make sure that the user maintains enough active bond for their role. - // If a user runs into this error, they should chill first. - ensure!(ledger.active >= min_active_bond, Error::::InsufficientBond); - - // Note: in case there is no current era it is fine to bond one era more. - let era = Self::current_era().unwrap_or(0) + T::BondingDuration::get(); - ledger.unlocking.push(UnlockChunk { value, era }); - Self::update_ledger(&controller, &ledger); - Self::deposit_event(Event::::Unbonded(ledger.stash, value)); - } - Ok(()) - } - - /// Remove any unlocked chunks from the `unlocking` queue from our management. - /// - /// This essentially frees up that balance to be used by the stash account to do - /// whatever it wants. - /// - /// The dispatch origin for this call must be _Signed_ by the controller. - /// - /// Emits `Withdrawn`. - /// - /// See also [`Call::unbond`]. - /// - /// # - /// Complexity O(S) where S is the number of slashing spans to remove - /// NOTE: Weight annotation is the kill scenario, we refund otherwise. - /// # - #[pallet::weight(T::WeightInfo::withdraw_unbonded_kill(*num_slashing_spans))] - pub fn withdraw_unbonded( - origin: OriginFor, - num_slashing_spans: u32, - ) -> DispatchResultWithPostInfo { - let controller = ensure_signed(origin)?; - let mut ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - let (stash, old_total) = (ledger.stash.clone(), ledger.total); - if let Some(current_era) = Self::current_era() { - ledger = ledger.consolidate_unlocked(current_era) - } - - let post_info_weight = - if ledger.unlocking.is_empty() && ledger.active < T::Currency::minimum_balance() { - // This account must have called `unbond()` with some value that caused the active - // portion to fall below existential deposit + will have no more unlocking chunks - // left. We can now safely remove all staking-related information. - Self::kill_stash(&stash, num_slashing_spans)?; - // Remove the lock. - T::Currency::remove_lock(STAKING_ID, &stash); - // This is worst case scenario, so we use the full weight and return None - None - } else { - // This was the consequence of a partial unbond. just update the ledger and move on. - Self::update_ledger(&controller, &ledger); - - // This is only an update, so we use less overall weight. - Some(T::WeightInfo::withdraw_unbonded_update(num_slashing_spans)) - }; - - // `old_total` should never be less than the new total because - // `consolidate_unlocked` strictly subtracts balance. - if ledger.total < old_total { - // Already checked that this won't overflow by entry condition. - let value = old_total - ledger.total; - Self::deposit_event(Event::::Withdrawn(stash, value)); - } - - Ok(post_info_weight.into()) - } - - /// Declare the desire to validate for the origin controller. - /// - /// Effects will be felt at the beginning of the next era. - /// - /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. - #[pallet::weight(T::WeightInfo::validate())] - pub fn validate(origin: OriginFor, prefs: ValidatorPrefs) -> DispatchResult { - let controller = ensure_signed(origin)?; - - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - ensure!(ledger.active >= MinValidatorBond::::get(), Error::::InsufficientBond); - let stash = &ledger.stash; - - // Only check limits if they are not already a validator. - if !Validators::::contains_key(stash) { - // If this error is reached, we need to adjust the `MinValidatorBond` and start calling `chill_other`. - // Until then, we explicitly block new validators to protect the runtime. - if let Some(max_validators) = MaxValidatorsCount::::get() { - ensure!( - CounterForValidators::::get() < max_validators, - Error::::TooManyValidators - ); - } - } - - Self::do_remove_nominator(stash); - Self::do_add_validator(stash, prefs); - Ok(()) - } - - /// Declare the desire to nominate `targets` for the origin controller. - /// - /// Effects will be felt at the beginning of the next era. - /// - /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. - /// - /// # - /// - The transaction's complexity is proportional to the size of `targets` (N) - /// which is capped at CompactAssignments::LIMIT (MAX_NOMINATIONS). - /// - Both the reads and writes follow a similar pattern. - /// # - #[pallet::weight(T::WeightInfo::nominate(targets.len() as u32))] - pub fn nominate( - origin: OriginFor, - targets: Vec<::Source>, - ) -> DispatchResult { - let controller = ensure_signed(origin)?; - - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - ensure!(ledger.active >= MinNominatorBond::::get(), Error::::InsufficientBond); - let stash = &ledger.stash; - - // Only check limits if they are not already a nominator. - if !Nominators::::contains_key(stash) { - // If this error is reached, we need to adjust the `MinNominatorBond` and start calling `chill_other`. - // Until then, we explicitly block new nominators to protect the runtime. - if let Some(max_nominators) = MaxNominatorsCount::::get() { - ensure!( - CounterForNominators::::get() < max_nominators, - Error::::TooManyNominators - ); - } - } - - ensure!(!targets.is_empty(), Error::::EmptyTargets); - ensure!(targets.len() <= T::MAX_NOMINATIONS as usize, Error::::TooManyTargets); - - let old = Nominators::::get(stash).map_or_else(Vec::new, |x| x.targets); - - let targets = targets - .into_iter() - .map(|t| T::Lookup::lookup(t).map_err(DispatchError::from)) - .map(|n| { - n.and_then(|n| { - if old.contains(&n) || !Validators::::get(&n).blocked { - Ok(n) - } else { - Err(Error::::BadTarget.into()) - } - }) - }) - .collect::, _>>()?; - - let nominations = Nominations { - targets, - // Initial nominations are considered submitted at era 0. See `Nominations` doc - submitted_in: Self::current_era().unwrap_or(0), - suppressed: false, - }; - - Self::do_remove_validator(stash); - Self::do_add_nominator(stash, nominations); - Ok(()) - } - - /// Declare no desire to either validate or nominate. - /// - /// Effects will be felt at the beginning of the next era. - /// - /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. - /// - /// # - /// - Independent of the arguments. Insignificant complexity. - /// - Contains one read. - /// - Writes are limited to the `origin` account key. - /// # - #[pallet::weight(T::WeightInfo::chill())] - pub fn chill(origin: OriginFor) -> DispatchResult { - let controller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - Self::chill_stash(&ledger.stash); - Ok(()) - } - - /// (Re-)set the payment target for a controller. - /// - /// Effects will be felt at the beginning of the next era. - /// - /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. - /// - /// # - /// - Independent of the arguments. Insignificant complexity. - /// - Contains a limited number of reads. - /// - Writes are limited to the `origin` account key. - /// --------- - /// - Weight: O(1) - /// - DB Weight: - /// - Read: Ledger - /// - Write: Payee - /// # - #[pallet::weight(T::WeightInfo::set_payee())] - pub fn set_payee( - origin: OriginFor, - payee: RewardDestination, - ) -> DispatchResult { - let controller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - let stash = &ledger.stash; - >::insert(stash, payee); - Ok(()) - } - - /// (Re-)set the controller of a stash. - /// - /// Effects will be felt at the beginning of the next era. - /// - /// The dispatch origin for this call must be _Signed_ by the stash, not the controller. - /// - /// # - /// - Independent of the arguments. Insignificant complexity. - /// - Contains a limited number of reads. - /// - Writes are limited to the `origin` account key. - /// ---------- - /// Weight: O(1) - /// DB Weight: - /// - Read: Bonded, Ledger New Controller, Ledger Old Controller - /// - Write: Bonded, Ledger New Controller, Ledger Old Controller - /// # - #[pallet::weight(T::WeightInfo::set_controller())] - pub fn set_controller( - origin: OriginFor, - controller: ::Source, - ) -> DispatchResult { - let stash = ensure_signed(origin)?; - let old_controller = Self::bonded(&stash).ok_or(Error::::NotStash)?; - let controller = T::Lookup::lookup(controller)?; - if >::contains_key(&controller) { - Err(Error::::AlreadyPaired)? - } - if controller != old_controller { - >::insert(&stash, &controller); - if let Some(l) = >::take(&old_controller) { - >::insert(&controller, l); - } - } - Ok(()) - } - - /// Sets the ideal number of validators. - /// - /// The dispatch origin must be Root. - /// - /// # - /// Weight: O(1) - /// Write: Validator Count - /// # - #[pallet::weight(T::WeightInfo::set_validator_count())] - pub fn set_validator_count( - origin: OriginFor, - #[pallet::compact] new: u32, - ) -> DispatchResult { - ensure_root(origin)?; - ValidatorCount::::put(new); - Ok(()) - } - - /// Increments the ideal number of validators. - /// - /// The dispatch origin must be Root. - /// - /// # - /// Same as [`Self::set_validator_count`]. - /// # - #[pallet::weight(T::WeightInfo::set_validator_count())] - pub fn increase_validator_count( - origin: OriginFor, - #[pallet::compact] additional: u32, - ) -> DispatchResult { - ensure_root(origin)?; - ValidatorCount::::mutate(|n| *n += additional); - Ok(()) - } - - /// Scale up the ideal number of validators by a factor. - /// - /// The dispatch origin must be Root. - /// - /// # - /// Same as [`Self::set_validator_count`]. - /// # - #[pallet::weight(T::WeightInfo::set_validator_count())] - pub fn scale_validator_count(origin: OriginFor, factor: Percent) -> DispatchResult { - ensure_root(origin)?; - ValidatorCount::::mutate(|n| *n += factor * *n); - Ok(()) - } - - /// Force there to be no new eras indefinitely. - /// - /// The dispatch origin must be Root. - /// - /// # Warning - /// - /// The election process starts multiple blocks before the end of the era. - /// Thus the election process may be ongoing when this is called. In this case the - /// election will continue until the next era is triggered. - /// - /// # - /// - No arguments. - /// - Weight: O(1) - /// - Write: ForceEra - /// # - #[pallet::weight(T::WeightInfo::force_no_eras())] - pub fn force_no_eras(origin: OriginFor) -> DispatchResult { - ensure_root(origin)?; - ForceEra::::put(Forcing::ForceNone); - Ok(()) - } - - /// Force there to be a new era at the end of the next session. After this, it will be - /// reset to normal (non-forced) behaviour. - /// - /// The dispatch origin must be Root. - /// - /// # Warning - /// - /// The election process starts multiple blocks before the end of the era. - /// If this is called just before a new era is triggered, the election process may not - /// have enough blocks to get a result. - /// - /// # - /// - No arguments. - /// - Weight: O(1) - /// - Write ForceEra - /// # - #[pallet::weight(T::WeightInfo::force_new_era())] - pub fn force_new_era(origin: OriginFor) -> DispatchResult { - ensure_root(origin)?; - ForceEra::::put(Forcing::ForceNew); - Ok(()) - } - - /// Set the validators who cannot be slashed (if any). - /// - /// The dispatch origin must be Root. - /// - /// # - /// - O(V) - /// - Write: Invulnerables - /// # - #[pallet::weight(T::WeightInfo::set_invulnerables(invulnerables.len() as u32))] - pub fn set_invulnerables( - origin: OriginFor, - invulnerables: Vec, - ) -> DispatchResult { - ensure_root(origin)?; - >::put(invulnerables); - Ok(()) - } - - /// Force a current staker to become completely unstaked, immediately. - /// - /// The dispatch origin must be Root. - /// - /// # - /// O(S) where S is the number of slashing spans to be removed - /// Reads: Bonded, Slashing Spans, Account, Locks - /// Writes: Bonded, Slashing Spans (if S > 0), Ledger, Payee, Validators, Nominators, Account, Locks - /// Writes Each: SpanSlash * S - /// # - #[pallet::weight(T::WeightInfo::force_unstake(*num_slashing_spans))] - pub fn force_unstake( - origin: OriginFor, - stash: T::AccountId, - num_slashing_spans: u32, - ) -> DispatchResult { - ensure_root(origin)?; - - // Remove all staking-related information. - Self::kill_stash(&stash, num_slashing_spans)?; - - // Remove the lock. - T::Currency::remove_lock(STAKING_ID, &stash); - Ok(()) - } - - /// Force there to be a new era at the end of sessions indefinitely. - /// - /// The dispatch origin must be Root. - /// - /// # Warning - /// - /// The election process starts multiple blocks before the end of the era. - /// If this is called just before a new era is triggered, the election process may not - /// have enough blocks to get a result. - /// - /// # - /// - Weight: O(1) - /// - Write: ForceEra - /// # - #[pallet::weight(T::WeightInfo::force_new_era_always())] - pub fn force_new_era_always(origin: OriginFor) -> DispatchResult { - ensure_root(origin)?; - ForceEra::::put(Forcing::ForceAlways); - Ok(()) - } - - /// Cancel enactment of a deferred slash. - /// - /// Can be called by the `T::SlashCancelOrigin`. - /// - /// Parameters: era and indices of the slashes for that era to kill. - /// - /// # - /// Complexity: O(U + S) - /// with U unapplied slashes weighted with U=1000 - /// and S is the number of slash indices to be canceled. - /// - Read: Unapplied Slashes - /// - Write: Unapplied Slashes - /// # - #[pallet::weight(T::WeightInfo::cancel_deferred_slash(slash_indices.len() as u32))] - pub fn cancel_deferred_slash( - origin: OriginFor, - era: EraIndex, - slash_indices: Vec, - ) -> DispatchResult { - T::SlashCancelOrigin::ensure_origin(origin)?; - - ensure!(!slash_indices.is_empty(), Error::::EmptyTargets); - ensure!(is_sorted_and_unique(&slash_indices), Error::::NotSortedAndUnique); - - let mut unapplied = ::UnappliedSlashes::get(&era); - let last_item = slash_indices[slash_indices.len() - 1]; - ensure!((last_item as usize) < unapplied.len(), Error::::InvalidSlashIndex); - - for (removed, index) in slash_indices.into_iter().enumerate() { - let index = (index as usize) - removed; - unapplied.remove(index); - } - - ::UnappliedSlashes::insert(&era, &unapplied); - Ok(()) - } - - /// Pay out all the stakers behind a single validator for a single era. - /// - /// - `validator_stash` is the stash account of the validator. Their nominators, up to - /// `T::MaxNominatorRewardedPerValidator`, will also receive their rewards. - /// - `era` may be any era between `[current_era - history_depth; current_era]`. - /// - /// The origin of this call must be _Signed_. Any account can call this function, even if - /// it is not one of the stakers. - /// - /// # - /// - Time complexity: at most O(MaxNominatorRewardedPerValidator). - /// - Contains a limited number of reads and writes. - /// ----------- - /// N is the Number of payouts for the validator (including the validator) - /// Weight: - /// - Reward Destination Staked: O(N) - /// - Reward Destination Controller (Creating): O(N) - /// - /// NOTE: weights are assuming that payouts are made to alive stash account (Staked). - /// Paying even a dead controller is cheaper weight-wise. We don't do any refunds here. - /// # - #[pallet::weight(T::WeightInfo::payout_stakers_alive_staked( - T::MaxNominatorRewardedPerValidator::get() - ))] - pub fn payout_stakers( - origin: OriginFor, - validator_stash: T::AccountId, - era: EraIndex, - ) -> DispatchResultWithPostInfo { - ensure_signed(origin)?; - Self::do_payout_stakers(validator_stash, era) - } - - /// Rebond a portion of the stash scheduled to be unlocked. - /// - /// The dispatch origin must be signed by the controller. - /// - /// # - /// - Time complexity: O(L), where L is unlocking chunks - /// - Bounded by `MAX_UNLOCKING_CHUNKS`. - /// - Storage changes: Can't increase storage, only decrease it. - /// # - #[pallet::weight(T::WeightInfo::rebond(MAX_UNLOCKING_CHUNKS as u32))] - pub fn rebond( - origin: OriginFor, - #[pallet::compact] value: BalanceOf, - ) -> DispatchResultWithPostInfo { - let controller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - ensure!(!ledger.unlocking.is_empty(), Error::::NoUnlockChunk); - - let ledger = ledger.rebond(value); - // Last check: the new active amount of ledger must be more than ED. - ensure!(ledger.active >= T::Currency::minimum_balance(), Error::::InsufficientBond); - - Self::deposit_event(Event::::Bonded(ledger.stash.clone(), value)); - Self::update_ledger(&controller, &ledger); - Ok(Some( - 35 * WEIGHT_PER_MICROS + - 50 * WEIGHT_PER_NANOS * (ledger.unlocking.len() as Weight) + - T::DbWeight::get().reads_writes(3, 2), - ) - .into()) - } - - /// Set `HistoryDepth` value. This function will delete any history information - /// when `HistoryDepth` is reduced. - /// - /// Parameters: - /// - `new_history_depth`: The new history depth you would like to set. - /// - `era_items_deleted`: The number of items that will be deleted by this dispatch. - /// This should report all the storage items that will be deleted by clearing old - /// era history. Needed to report an accurate weight for the dispatch. Trusted by - /// `Root` to report an accurate number. - /// - /// Origin must be root. - /// - /// # - /// - E: Number of history depths removed, i.e. 10 -> 7 = 3 - /// - Weight: O(E) - /// - DB Weight: - /// - Reads: Current Era, History Depth - /// - Writes: History Depth - /// - Clear Prefix Each: Era Stakers, EraStakersClipped, ErasValidatorPrefs - /// - Writes Each: ErasValidatorReward, ErasRewardPoints, ErasTotalStake, ErasStartSessionIndex - /// # - #[pallet::weight(T::WeightInfo::set_history_depth(*_era_items_deleted))] - pub fn set_history_depth( - origin: OriginFor, - #[pallet::compact] new_history_depth: EraIndex, - #[pallet::compact] _era_items_deleted: u32, - ) -> DispatchResult { - ensure_root(origin)?; - if let Some(current_era) = Self::current_era() { - HistoryDepth::::mutate(|history_depth| { - let last_kept = current_era.checked_sub(*history_depth).unwrap_or(0); - let new_last_kept = current_era.checked_sub(new_history_depth).unwrap_or(0); - for era_index in last_kept..new_last_kept { - Self::clear_era_information(era_index); - } - *history_depth = new_history_depth - }) - } - Ok(()) - } - - /// Remove all data structure concerning a staker/stash once its balance is at the minimum. - /// This is essentially equivalent to `withdraw_unbonded` except it can be called by anyone - /// and the target `stash` must have no funds left beyond the ED. - /// - /// This can be called from any origin. - /// - /// - `stash`: The stash account to reap. Its balance must be zero. - /// - /// # - /// Complexity: O(S) where S is the number of slashing spans on the account. - /// DB Weight: - /// - Reads: Stash Account, Bonded, Slashing Spans, Locks - /// - Writes: Bonded, Slashing Spans (if S > 0), Ledger, Payee, Validators, Nominators, Stash Account, Locks - /// - Writes Each: SpanSlash * S - /// # - #[pallet::weight(T::WeightInfo::reap_stash(*num_slashing_spans))] - pub fn reap_stash( - _origin: OriginFor, - stash: T::AccountId, - num_slashing_spans: u32, - ) -> DispatchResult { - let at_minimum = T::Currency::total_balance(&stash) == T::Currency::minimum_balance(); - ensure!(at_minimum, Error::::FundedTarget); - Self::kill_stash(&stash, num_slashing_spans)?; - T::Currency::remove_lock(STAKING_ID, &stash); - Ok(()) - } - - /// Remove the given nominations from the calling validator. - /// - /// Effects will be felt at the beginning of the next era. - /// - /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. - /// - /// - `who`: A list of nominator stash accounts who are nominating this validator which - /// should no longer be nominating this validator. - /// - /// Note: Making this call only makes sense if you first set the validator preferences to - /// block any further nominations. - #[pallet::weight(T::WeightInfo::kick(who.len() as u32))] - pub fn kick( - origin: OriginFor, - who: Vec<::Source>, - ) -> DispatchResult { - let controller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - let stash = &ledger.stash; - - for nom_stash in who - .into_iter() - .map(T::Lookup::lookup) - .collect::, _>>()? - .into_iter() - { - Nominators::::mutate(&nom_stash, |maybe_nom| { - if let Some(ref mut nom) = maybe_nom { - if let Some(pos) = nom.targets.iter().position(|v| v == stash) { - nom.targets.swap_remove(pos); - Self::deposit_event(Event::::Kicked( - nom_stash.clone(), - stash.clone(), - )); - } - } - }); - } - - Ok(()) - } - - /// Update the various staking limits this pallet. - /// - /// * `min_nominator_bond`: The minimum active bond needed to be a nominator. - /// * `min_validator_bond`: The minimum active bond needed to be a validator. - /// * `max_nominator_count`: The max number of users who can be a nominator at once. - /// When set to `None`, no limit is enforced. - /// * `max_validator_count`: The max number of users who can be a validator at once. - /// When set to `None`, no limit is enforced. - /// - /// Origin must be Root to call this function. - /// - /// NOTE: Existing nominators and validators will not be affected by this update. - /// to kick people under the new limits, `chill_other` should be called. - #[pallet::weight(T::WeightInfo::set_staking_limits())] - pub fn set_staking_limits( - origin: OriginFor, - min_nominator_bond: BalanceOf, - min_validator_bond: BalanceOf, - max_nominator_count: Option, - max_validator_count: Option, - threshold: Option, - ) -> DispatchResult { - ensure_root(origin)?; - MinNominatorBond::::set(min_nominator_bond); - MinValidatorBond::::set(min_validator_bond); - MaxNominatorsCount::::set(max_nominator_count); - MaxValidatorsCount::::set(max_validator_count); - ChillThreshold::::set(threshold); - Ok(()) - } - - /// Declare a `controller` to stop participating as either a validator or nominator. - /// - /// Effects will be felt at the beginning of the next era. - /// - /// The dispatch origin for this call must be _Signed_, but can be called by anyone. - /// - /// If the caller is the same as the controller being targeted, then no further checks are - /// enforced, and this function behaves just like `chill`. - /// - /// If the caller is different than the controller being targeted, the following conditions - /// must be met: - /// * A `ChillThreshold` must be set and checked which defines how close to the max - /// nominators or validators we must reach before users can start chilling one-another. - /// * A `MaxNominatorCount` and `MaxValidatorCount` must be set which is used to determine - /// how close we are to the threshold. - /// * A `MinNominatorBond` and `MinValidatorBond` must be set and checked, which determines - /// if this is a person that should be chilled because they have not met the threshold - /// bond required. - /// - /// This can be helpful if bond requirements are updated, and we need to remove old users - /// who do not satisfy these requirements. - // TODO: Maybe we can deprecate `chill` in the future. - // https://github.com/paritytech/substrate/issues/9111 - #[pallet::weight(T::WeightInfo::chill_other())] - pub fn chill_other(origin: OriginFor, controller: T::AccountId) -> DispatchResult { - // Anyone can call this function. - let caller = ensure_signed(origin)?; - let ledger = Self::ledger(&controller).ok_or(Error::::NotController)?; - let stash = ledger.stash; - - // In order for one user to chill another user, the following conditions must be met: - // * A `ChillThreshold` is set which defines how close to the max nominators or - // validators we must reach before users can start chilling one-another. - // * A `MaxNominatorCount` and `MaxValidatorCount` which is used to determine how close - // we are to the threshold. - // * A `MinNominatorBond` and `MinValidatorBond` which is the final condition checked to - // determine this is a person that should be chilled because they have not met the - // threshold bond required. - // - // Otherwise, if caller is the same as the controller, this is just like `chill`. - if caller != controller { - let threshold = ChillThreshold::::get().ok_or(Error::::CannotChillOther)?; - let min_active_bond = if Nominators::::contains_key(&stash) { - let max_nominator_count = - MaxNominatorsCount::::get().ok_or(Error::::CannotChillOther)?; - let current_nominator_count = CounterForNominators::::get(); - ensure!( - threshold * max_nominator_count < current_nominator_count, - Error::::CannotChillOther - ); - MinNominatorBond::::get() - } else if Validators::::contains_key(&stash) { - let max_validator_count = - MaxValidatorsCount::::get().ok_or(Error::::CannotChillOther)?; - let current_validator_count = CounterForValidators::::get(); - ensure!( - threshold * max_validator_count < current_validator_count, - Error::::CannotChillOther - ); - MinValidatorBond::::get() - } else { - Zero::zero() - }; - - ensure!(ledger.active < min_active_bond, Error::::CannotChillOther); - } - - Self::chill_stash(&stash); - Ok(()) - } - } -} - -impl Pallet { - /// The total balance that can be slashed from a stash account as of right now. - pub fn slashable_balance_of(stash: &T::AccountId) -> BalanceOf { - // Weight note: consider making the stake accessible through stash. - Self::bonded(stash).and_then(Self::ledger).map(|l| l.active).unwrap_or_default() - } - - /// Internal impl of [`Self::slashable_balance_of`] that returns [`VoteWeight`]. - pub fn slashable_balance_of_vote_weight( - stash: &T::AccountId, - issuance: BalanceOf, - ) -> VoteWeight { - T::CurrencyToVote::to_vote(Self::slashable_balance_of(stash), issuance) - } - - /// Returns a closure around `slashable_balance_of_vote_weight` that can be passed around. - /// - /// This prevents call sites from repeatedly requesting `total_issuance` from backend. But it is - /// important to be only used while the total issuance is not changing. - pub fn slashable_balance_of_fn() -> Box VoteWeight> { - // NOTE: changing this to unboxed `impl Fn(..)` return type and the pallet will still - // compile, while some types in mock fail to resolve. - let issuance = T::Currency::total_issuance(); - Box::new(move |who: &T::AccountId| -> VoteWeight { - Self::slashable_balance_of_vote_weight(who, issuance) - }) - } - - fn do_payout_stakers( - validator_stash: T::AccountId, - era: EraIndex, - ) -> DispatchResultWithPostInfo { - // Validate input data - let current_era = CurrentEra::::get().ok_or_else(|| { - Error::::InvalidEraToReward - .with_weight(T::WeightInfo::payout_stakers_alive_staked(0)) - })?; - let history_depth = Self::history_depth(); - ensure!( - era <= current_era && era >= current_era.saturating_sub(history_depth), - Error::::InvalidEraToReward - .with_weight(T::WeightInfo::payout_stakers_alive_staked(0)) - ); - - // Note: if era has no reward to be claimed, era may be future. better not to update - // `ledger.claimed_rewards` in this case. - let era_payout = >::get(&era).ok_or_else(|| { - Error::::InvalidEraToReward - .with_weight(T::WeightInfo::payout_stakers_alive_staked(0)) - })?; - - let controller = Self::bonded(&validator_stash).ok_or_else(|| { - Error::::NotStash.with_weight(T::WeightInfo::payout_stakers_alive_staked(0)) - })?; - let mut ledger = >::get(&controller).ok_or(Error::::NotController)?; - - ledger - .claimed_rewards - .retain(|&x| x >= current_era.saturating_sub(history_depth)); - match ledger.claimed_rewards.binary_search(&era) { - Ok(_) => Err(Error::::AlreadyClaimed - .with_weight(T::WeightInfo::payout_stakers_alive_staked(0)))?, - Err(pos) => ledger.claimed_rewards.insert(pos, era), - } - - let exposure = >::get(&era, &ledger.stash); - - // Input data seems good, no errors allowed after this point - - >::insert(&controller, &ledger); - - // Get Era reward points. It has TOTAL and INDIVIDUAL - // Find the fraction of the era reward that belongs to the validator - // Take that fraction of the eras rewards to split to nominator and validator - // - // Then look at the validator, figure out the proportion of their reward - // which goes to them and each of their nominators. - - let era_reward_points = >::get(&era); - let total_reward_points = era_reward_points.total; - let validator_reward_points = era_reward_points - .individual - .get(&ledger.stash) - .map(|points| *points) - .unwrap_or_else(|| Zero::zero()); - - // Nothing to do if they have no reward points. - if validator_reward_points.is_zero() { - return Ok(Some(T::WeightInfo::payout_stakers_alive_staked(0)).into()) - } - - // This is the fraction of the total reward that the validator and the - // nominators will get. - let validator_total_reward_part = - Perbill::from_rational(validator_reward_points, total_reward_points); - - // This is how much validator + nominators are entitled to. - let validator_total_payout = validator_total_reward_part * era_payout; - - let validator_prefs = Self::eras_validator_prefs(&era, &validator_stash); - // Validator first gets a cut off the top. - let validator_commission = validator_prefs.commission; - let validator_commission_payout = validator_commission * validator_total_payout; - - let validator_leftover_payout = validator_total_payout - validator_commission_payout; - // Now let's calculate how this is split to the validator. - let validator_exposure_part = Perbill::from_rational(exposure.own, exposure.total); - let validator_staking_payout = validator_exposure_part * validator_leftover_payout; - - // We can now make total validator payout: - Self::make_payout(&ledger.stash, validator_staking_payout + validator_commission_payout) - Self::deposit_event(Event::::Reward(ledger.stash, validator_staking_payout + validator_commission_payout)); - - // Track the number of payout ops to nominators. Note: `WeightInfo::payout_stakers_alive_staked` - // always assumes at least a validator is paid out, so we do not need to count their payout op. - let mut nominator_payout_count: u32 = 0; - - // Lets now calculate how this is split to the nominators. - // Reward only the clipped exposures. Note this is not necessarily sorted. - for nominator in exposure.others.iter() { - let nominator_exposure_part = Perbill::from_rational(nominator.value, exposure.total); - - let nominator_reward: BalanceOf = - nominator_exposure_part * validator_leftover_payout; - // We can now make nominator payout: - Self::make_payout(&nominator.who, nominator_reward); - // Note: this logic does not count payouts for `RewardDestination::None`. - nominator_payout_count += 1; - Self::deposit_event(Event::::Reward(nominator.who.clone(), nominator_reward)); - } - - debug_assert!(nominator_payout_count <= T::MaxNominatorRewardedPerValidator::get()); - Ok(Some(T::WeightInfo::payout_stakers_alive_staked(nominator_payout_count)).into()) - } - - /// Update the ledger for a controller. - /// - /// This will also update the stash lock. - fn update_ledger( - controller: &T::AccountId, - ledger: &StakingLedger>, - ) { - T::Currency::set_lock(STAKING_ID, &ledger.stash, ledger.total, WithdrawReasons::all()); - >::insert(controller, ledger); - } - - /// Chill a stash account. - fn chill_stash(stash: &T::AccountId) { - let chilled_as_validator = Self::do_remove_validator(stash); - let chilled_as_nominator = Self::do_remove_nominator(stash); - if chilled_as_validator || chilled_as_nominator { - Self::deposit_event(Event::::Chilled(stash.clone())); - } - } - - /// Actually make a payment to a staker. This uses the currency's reward function - /// to pay the right payee for the given staker account. - fn make_payout(stash: &T::AccountId, amount: BalanceOf) -> DispatchResult { - let two: Balance = 2; - let halved_amount = amount.saturating_div(&two); - let dirham_value = ::PriceSource::get_relative_price(T::NativeCurrencyId::get(), T::DirhamCurrencyId::get()) - .ok_or(Error::::InvalidFeedPrice)?; - let setter_value = ::PriceSource::get_relative_price(T::DirhamCurrencyId::get(), T::SetterCurrencyId::get()) - .ok_or(Error::::InvalidFeedPrice)?; - let dirham_amount = &halved_amount.saturating_mul(&dirham_value) - let setter_amount = &halved_amount.saturating_mul(&setter_value) - Self::make_dirham_payout(stash, &dirham_amount).ok(); - Self::make_setter_payout(stash, &setter_amount).ok(); - Ok(()) - } - - /// Actually make a payment to a staker. This uses the currency's reward function - /// to pay the right payee for the given staker account. - fn make_dirham_payout(stash: &T::AccountId, amount: BalanceOf) -> DispatchResult { - let dest = Self::payee(stash); - let dirham = T::DirhamCurrencyId::get(); - match dest { - RewardDestination::Controller => Self::bonded(stash) - .and_then(|controller| Some(T::MultiCurrency::deposit(&dirham, &controller, amount).ok(), - RewardDestination::Stash => T::MultiCurrency::deposit(&dirham, stash, amount).ok(), - RewardDestination::Account(dest_account) => - Some(T::MultiCurrency::deposit(&dirham, &dest_account, amount)), - RewardDestination::None => None, - } - Ok(()) - } - - /// Actually make a payment to a staker. This uses the currency's reward function - /// to pay the right payee for the given staker account. - fn make_setter_payout(stash: &T::AccountId, amount: BalanceOf) -> DispatchResult { - let dest = Self::payee(stash); - let setter = T::SetterCurrencyId::get(); - match dest { - RewardDestination::Controller => Self::bonded(stash) - .and_then(|controller| Some(T::MultiCurrency::deposit(&setter, &controller, amount).ok(), - RewardDestination::Stash => T::MultiCurrency::deposit(&setter, stash, amount).ok(), - RewardDestination::Account(dest_account) => - Some(T::MultiCurrency::deposit(&setter, &dest_account, amount)), - RewardDestination::None => None, - } - Ok(()) - } - - /// Plan a new session potentially trigger a new era. - fn new_session(session_index: SessionIndex, is_genesis: bool) -> Option> { - if let Some(current_era) = Self::current_era() { - // Initial era has been set. - let current_era_start_session_index = Self::eras_start_session_index(current_era) - .unwrap_or_else(|| { - frame_support::print("Error: start_session_index must be set for current_era"); - 0 - }); - - let era_length = - session_index.checked_sub(current_era_start_session_index).unwrap_or(0); // Must never happen. - - match ForceEra::::get() { - // Will be set to `NotForcing` again if a new era has been triggered. - Forcing::ForceNew => (), - // Short circuit to `try_trigger_new_era`. - Forcing::ForceAlways => (), - // Only go to `try_trigger_new_era` if deadline reached. - Forcing::NotForcing if era_length >= T::SessionsPerEra::get() => (), - _ => { - // Either `Forcing::ForceNone`, - // or `Forcing::NotForcing if era_length >= T::SessionsPerEra::get()`. - return None - }, - } - - // New era. - let maybe_new_era_validators = Self::try_trigger_new_era(session_index, is_genesis); - if maybe_new_era_validators.is_some() && - matches!(ForceEra::::get(), Forcing::ForceNew) - { - ForceEra::::put(Forcing::NotForcing); - } - - maybe_new_era_validators - } else { - // Set initial era. - log!(debug, "Starting the first era."); - Self::try_trigger_new_era(session_index, is_genesis) - } - } - - /// Start a session potentially starting an era. - fn start_session(start_session: SessionIndex) { - let next_active_era = Self::active_era().map(|e| e.index + 1).unwrap_or(0); - // This is only `Some` when current era has already progressed to the next era, while the - // active era is one behind (i.e. in the *last session of the active era*, or *first session - // of the new current era*, depending on how you look at it). - if let Some(next_active_era_start_session_index) = - Self::eras_start_session_index(next_active_era) - { - if next_active_era_start_session_index == start_session { - Self::start_era(start_session); - } else if next_active_era_start_session_index < start_session { - // This arm should never happen, but better handle it than to stall the staking - // pallet. - frame_support::print("Warning: A session appears to have been skipped."); - Self::start_era(start_session); - } - } - } - - /// End a session potentially ending an era. - fn end_session(session_index: SessionIndex) { - if let Some(active_era) = Self::active_era() { - if let Some(next_active_era_start_session_index) = - Self::eras_start_session_index(active_era.index + 1) - { - if next_active_era_start_session_index == session_index + 1 { - Self::end_era(active_era, session_index); - } - } - } - } - - /// * Increment `active_era.index`, - /// * reset `active_era.start`, - /// * update `BondedEras` and apply slashes. - fn start_era(start_session: SessionIndex) { - let active_era = ActiveEra::::mutate(|active_era| { - let new_index = active_era.as_ref().map(|info| info.index + 1).unwrap_or(0); - *active_era = Some(ActiveEraInfo { - index: new_index, - // Set new active era start in next `on_finalize`. To guarantee usage of `Time` - start: None, - }); - new_index - }); - - let bonding_duration = T::BondingDuration::get(); - - BondedEras::::mutate(|bonded| { - bonded.push((active_era, start_session)); - - if active_era > bonding_duration { - let first_kept = active_era - bonding_duration; - - // Prune out everything that's from before the first-kept index. - let n_to_prune = - bonded.iter().take_while(|&&(era_idx, _)| era_idx < first_kept).count(); - - // Kill slashing metadata. - for (pruned_era, _) in bonded.drain(..n_to_prune) { - slashing::clear_era_metadata::(pruned_era); - } - - if let Some(&(_, first_session)) = bonded.first() { - T::SessionInterface::prune_historical_up_to(first_session); - } - } - }); - - Self::apply_unapplied_slashes(active_era); - } - - /// Compute payout for era. - fn end_era(active_era: ActiveEraInfo, _session_index: SessionIndex) { - // Note: active_era_start can be None if end era is called during genesis config. - if let Some(active_era_start) = active_era.start { - let now_as_millis_u64 = T::UnixTime::now().as_millis().saturated_into::(); - - let era_duration = (now_as_millis_u64 - active_era_start).saturated_into::(); - let staked = Self::eras_total_stake(&active_era.index); - let issuance = T::Currency::total_issuance(); - let (validator_payout, rest) = T::EraPayout::era_payout(staked, issuance, era_duration); - - Self::deposit_event(Event::::EraPayout(active_era.index, validator_payout, rest)); - - // Set ending era reward. - >::insert(&active_era.index, validator_payout); - } - } - - /// Plan a new era. - /// - /// * Bump the current era storage (which holds the latest planned era). - /// * Store start session index for the new planned era. - /// * Clean old era information. - /// * Store staking information for the new planned era - /// - /// Returns the new validator set. - pub fn trigger_new_era( - start_session_index: SessionIndex, - exposures: Vec<(T::AccountId, Exposure>)>, - ) -> Vec { - // Increment or set current era. - let new_planned_era = CurrentEra::::mutate(|s| { - *s = Some(s.map(|s| s + 1).unwrap_or(0)); - s.unwrap() - }); - ErasStartSessionIndex::::insert(&new_planned_era, &start_session_index); - - // Clean old era information. - if let Some(old_era) = new_planned_era.checked_sub(Self::history_depth() + 1) { - Self::clear_era_information(old_era); - } - - // Set staking information for the new era. - Self::store_stakers_info(exposures, new_planned_era) - } - - /// Potentially plan a new era. - /// - /// Get election result from `T::ElectionProvider`. - /// In case election result has more than [`MinimumValidatorCount`] validator trigger a new era. - /// - /// In case a new era is planned, the new validator set is returned. - fn try_trigger_new_era( - start_session_index: SessionIndex, - is_genesis: bool, - ) -> Option> { - let (election_result, weight) = if is_genesis { - T::GenesisElectionProvider::elect().map_err(|e| { - log!(warn, "genesis election provider failed due to {:?}", e); - Self::deposit_event(Event::StakingElectionFailed); - }) - } else { - T::ElectionProvider::elect().map_err(|e| { - log!(warn, "election provider failed due to {:?}", e); - Self::deposit_event(Event::StakingElectionFailed); - }) - } - .ok()?; - - >::register_extra_weight_unchecked( - weight, - frame_support::weights::DispatchClass::Mandatory, - ); - - let exposures = Self::collect_exposures(election_result); - - if (exposures.len() as u32) < Self::minimum_validator_count().max(1) { - // Session will panic if we ever return an empty validator set, thus max(1) ^^. - match CurrentEra::::get() { - Some(current_era) if current_era > 0 => log!( - warn, - "chain does not have enough staking candidates to operate for era {:?} ({} \ - elected, minimum is {})", - CurrentEra::::get().unwrap_or(0), - exposures.len(), - Self::minimum_validator_count(), - ), - None => { - // The initial era is allowed to have no exposures. - // In this case the SessionManager is expected to choose a sensible validator - // set. - // TODO: this should be simplified #8911 - CurrentEra::::put(0); - ErasStartSessionIndex::::insert(&0, &start_session_index); - }, - _ => (), - } - - Self::deposit_event(Event::StakingElectionFailed); - return None - } - - Self::deposit_event(Event::StakingElection); - Some(Self::trigger_new_era(start_session_index, exposures)) - } - - /// Process the output of the election. - /// - /// Store staking information for the new planned era - pub fn store_stakers_info( - exposures: Vec<(T::AccountId, Exposure>)>, - new_planned_era: EraIndex, - ) -> Vec { - let elected_stashes = exposures.iter().cloned().map(|(x, _)| x).collect::>(); - - // Populate stakers, exposures, and the snapshot of validator prefs. - let mut total_stake: BalanceOf = Zero::zero(); - exposures.into_iter().for_each(|(stash, exposure)| { - total_stake = total_stake.saturating_add(exposure.total); - >::insert(new_planned_era, &stash, &exposure); - - let mut exposure_clipped = exposure; - let clipped_max_len = T::MaxNominatorRewardedPerValidator::get() as usize; - if exposure_clipped.others.len() > clipped_max_len { - exposure_clipped.others.sort_by(|a, b| a.value.cmp(&b.value).reverse()); - exposure_clipped.others.truncate(clipped_max_len); - } - >::insert(&new_planned_era, &stash, exposure_clipped); - }); - - // Insert current era staking information - >::insert(&new_planned_era, total_stake); - - // Collect the pref of all winners. - for stash in &elected_stashes { - let pref = Self::validators(stash); - >::insert(&new_planned_era, stash, pref); - } - - if new_planned_era > 0 { - log!( - info, - "new validator set of size {:?} has been processed for era {:?}", - elected_stashes.len(), - new_planned_era, - ); - } - - elected_stashes - } - - /// Consume a set of [`Supports`] from [`sp_npos_elections`] and collect them into a - /// [`Exposure`]. - fn collect_exposures( - supports: Supports, - ) -> Vec<(T::AccountId, Exposure>)> { - let total_issuance = T::Currency::total_issuance(); - let to_currency = |e: frame_election_provider_support::ExtendedBalance| { - T::CurrencyToVote::to_currency(e, total_issuance) - }; - - supports - .into_iter() - .map(|(validator, support)| { - // Build `struct exposure` from `support`. - let mut others = Vec::with_capacity(support.voters.len()); - let mut own: BalanceOf = Zero::zero(); - let mut total: BalanceOf = Zero::zero(); - support - .voters - .into_iter() - .map(|(nominator, weight)| (nominator, to_currency(weight))) - .for_each(|(nominator, stake)| { - if nominator == validator { - own = own.saturating_add(stake); - } else { - others.push(IndividualExposure { who: nominator, value: stake }); - } - total = total.saturating_add(stake); - }); - - let exposure = Exposure { own, others, total }; - (validator, exposure) - }) - .collect::)>>() - } - - /// Remove all associated data of a stash account from the staking system. - /// - /// Assumes storage is upgraded before calling. - /// - /// This is called: - /// - after a `withdraw_unbonded()` call that frees all of a stash's bonded balance. - /// - through `reap_stash()` if the balance has fallen to zero (through slashing). - fn kill_stash(stash: &T::AccountId, num_slashing_spans: u32) -> DispatchResult { - let controller = >::get(stash).ok_or(Error::::NotStash)?; - - slashing::clear_stash_metadata::(stash, num_slashing_spans)?; - - >::remove(stash); - >::remove(&controller); - - >::remove(stash); - Self::do_remove_validator(stash); - Self::do_remove_nominator(stash); - - frame_system::Pallet::::dec_consumers(stash); - - Ok(()) - } - - /// Clear all era information for given era. - fn clear_era_information(era_index: EraIndex) { - >::remove_prefix(era_index, None); - >::remove_prefix(era_index, None); - >::remove_prefix(era_index, None); - >::remove(era_index); - >::remove(era_index); - >::remove(era_index); - ErasStartSessionIndex::::remove(era_index); - } - - /// Apply previously-unapplied slashes on the beginning of a new era, after a delay. - fn apply_unapplied_slashes(active_era: EraIndex) { - let slash_defer_duration = T::SlashDeferDuration::get(); - ::EarliestUnappliedSlash::mutate(|earliest| { - if let Some(ref mut earliest) = earliest { - let keep_from = active_era.saturating_sub(slash_defer_duration); - for era in (*earliest)..keep_from { - let era_slashes = ::UnappliedSlashes::take(&era); - for slash in era_slashes { - slashing::apply_slash::(slash); - } - } - - *earliest = (*earliest).max(keep_from) - } - }) - } - - /// Add reward points to validators using their stash account ID. - /// - /// Validators are keyed by stash account ID and must be in the current elected set. - /// - /// For each element in the iterator the given number of points in u32 is added to the - /// validator, thus duplicates are handled. - /// - /// At the end of the era each the total payout will be distributed among validator - /// relatively to their points. - /// - /// COMPLEXITY: Complexity is `number_of_validator_to_reward x current_elected_len`. - pub fn reward_by_ids(validators_points: impl IntoIterator) { - if let Some(active_era) = Self::active_era() { - >::mutate(active_era.index, |era_rewards| { - for (validator, points) in validators_points.into_iter() { - *era_rewards.individual.entry(validator).or_default() += points; - era_rewards.total += points; - } - }); - } - } - - /// Ensures that at the end of the current session there will be a new era. - fn ensure_new_era() { - match ForceEra::::get() { - Forcing::ForceAlways | Forcing::ForceNew => (), - _ => ForceEra::::put(Forcing::ForceNew), - } - } - - #[cfg(feature = "runtime-benchmarks")] - pub fn add_era_stakers( - current_era: EraIndex, - controller: T::AccountId, - exposure: Exposure>, - ) { - >::insert(¤t_era, &controller, &exposure); - } - - #[cfg(feature = "runtime-benchmarks")] - pub fn set_slash_reward_fraction(fraction: Perbill) { - SlashRewardFraction::::put(fraction); - } - - /// Get all of the voters that are eligible for the npos election. - /// - /// This will use all on-chain nominators, and all the validators will inject a self vote. - /// - /// ### Slashing - /// - /// All nominations that have been submitted before the last non-zero slash of the validator are - /// auto-chilled. - /// - /// Note that this is VERY expensive. Use with care. - pub fn get_npos_voters() -> Vec<(T::AccountId, VoteWeight, Vec)> { - let weight_of = Self::slashable_balance_of_fn(); - let mut all_voters = Vec::new(); - - for (validator, _) in >::iter() { - // Append self vote. - let self_vote = (validator.clone(), weight_of(&validator), vec![validator.clone()]); - all_voters.push(self_vote); - } - - // Collect all slashing spans into a BTreeMap for further queries. - let slashing_spans = >::iter().collect::>(); - - for (nominator, nominations) in Nominators::::iter() { - let Nominations { submitted_in, mut targets, suppressed: _ } = nominations; - - // Filter out nomination targets which were nominated before the most recent - // slashing span. - targets.retain(|stash| { - slashing_spans - .get(stash) - .map_or(true, |spans| submitted_in >= spans.last_nonzero_slash()) - }); - - if !targets.is_empty() { - let vote_weight = weight_of(&nominator); - all_voters.push((nominator, vote_weight, targets)) - } - } - - all_voters - } - - /// This is a very expensive function and result should be cached versus being called multiple times. - pub fn get_npos_targets() -> Vec { - Validators::::iter().map(|(v, _)| v).collect::>() - } - - /// This function will add a nominator to the `Nominators` storage map, - /// and keep track of the `CounterForNominators`. - /// - /// If the nominator already exists, their nominations will be updated. - pub fn do_add_nominator(who: &T::AccountId, nominations: Nominations) { - if !Nominators::::contains_key(who) { - CounterForNominators::::mutate(|x| x.saturating_inc()) - } - Nominators::::insert(who, nominations); - } - - /// This function will remove a nominator from the `Nominators` storage map, - /// and keep track of the `CounterForNominators`. - /// - /// Returns true if `who` was removed from `Nominators`, otherwise false. - pub fn do_remove_nominator(who: &T::AccountId) -> bool { - if Nominators::::contains_key(who) { - Nominators::::remove(who); - CounterForNominators::::mutate(|x| x.saturating_dec()); - true - } else { - false - } - } - - /// This function will add a validator to the `Validators` storage map, - /// and keep track of the `CounterForValidators`. - /// - /// If the validator already exists, their preferences will be updated. - pub fn do_add_validator(who: &T::AccountId, prefs: ValidatorPrefs) { - if !Validators::::contains_key(who) { - CounterForValidators::::mutate(|x| x.saturating_inc()) - } - Validators::::insert(who, prefs); - } - - /// This function will remove a validator from the `Validators` storage map, - /// and keep track of the `CounterForValidators`. - /// - /// Returns true if `who` was removed from `Validators`, otherwise false. - pub fn do_remove_validator(who: &T::AccountId) -> bool { - if Validators::::contains_key(who) { - Validators::::remove(who); - CounterForValidators::::mutate(|x| x.saturating_dec()); - true - } else { - false - } - } -} - -impl frame_election_provider_support::ElectionDataProvider - for Pallet -{ - const MAXIMUM_VOTES_PER_VOTER: u32 = T::MAX_NOMINATIONS; - fn desired_targets() -> data_provider::Result<(u32, Weight)> { - Ok((Self::validator_count(), ::DbWeight::get().reads(1))) - } - - fn voters( - maybe_max_len: Option, - ) -> data_provider::Result<(Vec<(T::AccountId, VoteWeight, Vec)>, Weight)> { - let nominator_count = CounterForNominators::::get(); - let validator_count = CounterForValidators::::get(); - let voter_count = nominator_count.saturating_add(validator_count) as usize; - debug_assert!(>::iter().count() as u32 == CounterForNominators::::get()); - debug_assert!(>::iter().count() as u32 == CounterForValidators::::get()); - - if maybe_max_len.map_or(false, |max_len| voter_count > max_len) { - return Err("Voter snapshot too big") - } - - let slashing_span_count = >::iter().count(); - let weight = T::WeightInfo::get_npos_voters( - nominator_count, - validator_count, - slashing_span_count as u32, - ); - Ok((Self::get_npos_voters(), weight)) - } - - fn targets(maybe_max_len: Option) -> data_provider::Result<(Vec, Weight)> { - let target_count = CounterForValidators::::get() as usize; - - if maybe_max_len.map_or(false, |max_len| target_count > max_len) { - return Err("Target snapshot too big") - } - - let weight = ::DbWeight::get().reads(target_count as u64); - Ok((Self::get_npos_targets(), weight)) - } - - fn next_election_prediction(now: T::BlockNumber) -> T::BlockNumber { - let current_era = Self::current_era().unwrap_or(0); - let current_session = Self::current_planned_session(); - let current_era_start_session_index = - Self::eras_start_session_index(current_era).unwrap_or(0); - // Number of session in the current era or the maximum session per era if reached. - let era_progress = current_session - .saturating_sub(current_era_start_session_index) - .min(T::SessionsPerEra::get()); - - let until_this_session_end = T::NextNewSession::estimate_next_new_session(now) - .0 - .unwrap_or_default() - .saturating_sub(now); - - let session_length = T::NextNewSession::average_session_length(); - - let sessions_left: T::BlockNumber = match ForceEra::::get() { - Forcing::ForceNone => Bounded::max_value(), - Forcing::ForceNew | Forcing::ForceAlways => Zero::zero(), - Forcing::NotForcing if era_progress >= T::SessionsPerEra::get() => Zero::zero(), - Forcing::NotForcing => T::SessionsPerEra::get() - .saturating_sub(era_progress) - // One session is computed in this_session_end. - .saturating_sub(1) - .into(), - }; - - now.saturating_add( - until_this_session_end.saturating_add(sessions_left.saturating_mul(session_length)), - ) - } - - #[cfg(any(feature = "runtime-benchmarks", test))] - fn add_voter(voter: T::AccountId, weight: VoteWeight, targets: Vec) { - use sp_std::convert::TryFrom; - let stake = >::try_from(weight).unwrap_or_else(|_| { - panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.") - }); - >::insert(voter.clone(), voter.clone()); - >::insert( - voter.clone(), - StakingLedger { - stash: voter.clone(), - active: stake, - total: stake, - unlocking: vec![], - claimed_rewards: vec![], - }, - ); - Self::do_add_nominator(&voter, Nominations { targets, submitted_in: 0, suppressed: false }); - } - - #[cfg(any(feature = "runtime-benchmarks", test))] - fn add_target(target: T::AccountId) { - let stake = MinValidatorBond::::get() * 100u32.into(); - >::insert(target.clone(), target.clone()); - >::insert( - target.clone(), - StakingLedger { - stash: target.clone(), - active: stake, - total: stake, - unlocking: vec![], - claimed_rewards: vec![], - }, - ); - Self::do_add_validator( - &target, - ValidatorPrefs { commission: Perbill::zero(), blocked: false }, - ); - } - - #[cfg(any(feature = "runtime-benchmarks", test))] - fn clear() { - >::remove_all(None); - >::remove_all(None); - >::remove_all(None); - >::remove_all(None); - } - - #[cfg(any(feature = "runtime-benchmarks", test))] - fn put_snapshot( - voters: Vec<(T::AccountId, VoteWeight, Vec)>, - targets: Vec, - target_stake: Option, - ) { - use sp_std::convert::TryFrom; - targets.into_iter().for_each(|v| { - let stake: BalanceOf = target_stake - .and_then(|w| >::try_from(w).ok()) - .unwrap_or_else(|| MinNominatorBond::::get() * 100u32.into()); - >::insert(v.clone(), v.clone()); - >::insert( - v.clone(), - StakingLedger { - stash: v.clone(), - active: stake, - total: stake, - unlocking: vec![], - claimed_rewards: vec![], - }, - ); - Self::do_add_validator( - &v, - ValidatorPrefs { commission: Perbill::zero(), blocked: false }, - ); - }); - - voters.into_iter().for_each(|(v, s, t)| { - let stake = >::try_from(s).unwrap_or_else(|_| { - panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.") - }); - >::insert(v.clone(), v.clone()); - >::insert( - v.clone(), - StakingLedger { - stash: v.clone(), - active: stake, - total: stake, - unlocking: vec![], - claimed_rewards: vec![], - }, - ); - Self::do_add_nominator( - &v, - Nominations { targets: t, submitted_in: 0, suppressed: false }, - ); - }); - } -} - -/// In this implementation `new_session(session)` must be called before `end_session(session-1)` -/// i.e. the new session must be planned before the ending of the previous session. -/// -/// Once the first new_session is planned, all session must start and then end in order, though -/// some session can lag in between the newest session planned and the latest session started. -impl pallet_session::SessionManager for Pallet { - fn new_session(new_index: SessionIndex) -> Option> { - log!(trace, "planning new session {}", new_index); - CurrentPlannedSession::::put(new_index); - Self::new_session(new_index, false) - } - fn new_session_genesis(new_index: SessionIndex) -> Option> { - log!(trace, "planning new session {} at genesis", new_index); - CurrentPlannedSession::::put(new_index); - Self::new_session(new_index, true) - } - fn start_session(start_index: SessionIndex) { - log!(trace, "starting session {}", start_index); - Self::start_session(start_index) - } - fn end_session(end_index: SessionIndex) { - log!(trace, "ending session {}", end_index); - Self::end_session(end_index) - } -} - -impl historical::SessionManager>> - for Pallet -{ - fn new_session( - new_index: SessionIndex, - ) -> Option>)>> { - >::new_session(new_index).map(|validators| { - let current_era = Self::current_era() - // Must be some as a new era has been created. - .unwrap_or(0); - - validators - .into_iter() - .map(|v| { - let exposure = Self::eras_stakers(current_era, &v); - (v, exposure) - }) - .collect() - }) - } - fn new_session_genesis( - new_index: SessionIndex, - ) -> Option>)>> { - >::new_session_genesis(new_index).map( - |validators| { - let current_era = Self::current_era() - // Must be some as a new era has been created. - .unwrap_or(0); - - validators - .into_iter() - .map(|v| { - let exposure = Self::eras_stakers(current_era, &v); - (v, exposure) - }) - .collect() - }, - ) - } - fn start_session(start_index: SessionIndex) { - >::start_session(start_index) - } - fn end_session(end_index: SessionIndex) { - >::end_session(end_index) - } -} - -/// Add reward points to block authors: -/// * 20 points to the block producer for producing a (non-uncle) block in the relay chain, -/// * 2 points to the block producer for each reference to a previously unreferenced uncle, and -/// * 1 point to the producer of each referenced uncle block. -impl pallet_authorship::EventHandler for Pallet -where - T: Config + pallet_authorship::Config + pallet_session::Config, -{ - fn note_author(author: T::AccountId) { - Self::reward_by_ids(vec![(author, 20)]) - } - fn note_uncle(author: T::AccountId, _age: T::BlockNumber) { - Self::reward_by_ids(vec![(>::author(), 2), (author, 1)]) - } -} - -/// A `Convert` implementation that finds the stash of the given controller account, -/// if any. -pub struct StashOf(sp_std::marker::PhantomData); - -impl Convert> for StashOf { - fn convert(controller: T::AccountId) -> Option { - >::ledger(&controller).map(|l| l.stash) - } -} - -/// A typed conversion from stash account ID to the active exposure of nominators -/// on that account. -/// -/// Active exposure is the exposure of the validator set currently validating, i.e. in -/// `active_era`. It can differ from the latest planned exposure in `current_era`. -pub struct ExposureOf(sp_std::marker::PhantomData); - -impl Convert>>> - for ExposureOf -{ - fn convert(validator: T::AccountId) -> Option>> { - >::active_era() - .map(|active_era| >::eras_stakers(active_era.index, &validator)) - } -} - -/// This is intended to be used with `FilterHistoricalOffences`. -impl - OnOffenceHandler, Weight> - for Pallet -where - T: pallet_session::Config::AccountId>, - T: pallet_session::historical::Config< - FullIdentification = Exposure<::AccountId, BalanceOf>, - FullIdentificationOf = ExposureOf, - >, - T::SessionHandler: pallet_session::SessionHandler<::AccountId>, - T::SessionManager: pallet_session::SessionManager<::AccountId>, - T::ValidatorIdOf: Convert< - ::AccountId, - Option<::AccountId>, - >, -{ - fn on_offence( - offenders: &[OffenceDetails< - T::AccountId, - pallet_session::historical::IdentificationTuple, - >], - slash_fraction: &[Perbill], - slash_session: SessionIndex, - ) -> Weight { - let reward_proportion = SlashRewardFraction::::get(); - let mut consumed_weight: Weight = 0; - let mut add_db_reads_writes = |reads, writes| { - consumed_weight += T::DbWeight::get().reads_writes(reads, writes); - }; - - let active_era = { - let active_era = Self::active_era(); - add_db_reads_writes(1, 0); - if active_era.is_none() { - // This offence need not be re-submitted. - return consumed_weight - } - active_era.expect("value checked not to be `None`; qed").index - }; - let active_era_start_session_index = Self::eras_start_session_index(active_era) - .unwrap_or_else(|| { - frame_support::print("Error: start_session_index must be set for current_era"); - 0 - }); - add_db_reads_writes(1, 0); - - let window_start = active_era.saturating_sub(T::BondingDuration::get()); - - // Fast path for active-era report - most likely. - // `slash_session` cannot be in a future active era. It must be in `active_era` or before. - let slash_era = if slash_session >= active_era_start_session_index { - active_era - } else { - let eras = BondedEras::::get(); - add_db_reads_writes(1, 0); - - // Reverse because it's more likely to find reports from recent eras. - match eras.iter().rev().filter(|&&(_, ref sesh)| sesh <= &slash_session).next() { - Some(&(ref slash_era, _)) => *slash_era, - // Before bonding period. defensive - should be filtered out. - None => return consumed_weight, - } - }; - - ::EarliestUnappliedSlash::mutate(|earliest| { - if earliest.is_none() { - *earliest = Some(active_era) - } - }); - add_db_reads_writes(1, 1); - - let slash_defer_duration = T::SlashDeferDuration::get(); - - let invulnerables = Self::invulnerables(); - add_db_reads_writes(1, 0); - - for (details, slash_fraction) in offenders.iter().zip(slash_fraction) { - let (stash, exposure) = &details.offender; - - // Skip if the validator is invulnerable. - if invulnerables.contains(stash) { - continue - } - - let unapplied = slashing::compute_slash::(slashing::SlashParams { - stash, - slash: *slash_fraction, - exposure, - slash_era, - window_start, - now: active_era, - reward_proportion, - }); - - if let Some(mut unapplied) = unapplied { - let nominators_len = unapplied.others.len() as u64; - let reporters_len = details.reporters.len() as u64; - - { - let upper_bound = 1 /* Validator/NominatorSlashInEra */ + 2 /* fetch_spans */; - let rw = upper_bound + nominators_len * upper_bound; - add_db_reads_writes(rw, rw); - } - unapplied.reporters = details.reporters.clone(); - if slash_defer_duration == 0 { - // Apply right away. - slashing::apply_slash::(unapplied); - { - let slash_cost = (6, 5); - let reward_cost = (2, 2); - add_db_reads_writes( - (1 + nominators_len) * slash_cost.0 + reward_cost.0 * reporters_len, - (1 + nominators_len) * slash_cost.1 + reward_cost.1 * reporters_len, - ); - } - } else { - // Defer to end of some `slash_defer_duration` from now. - ::UnappliedSlashes::mutate(active_era, move |for_later| { - for_later.push(unapplied) - }); - add_db_reads_writes(1, 1); - } - } else { - add_db_reads_writes(4 /* fetch_spans */, 5 /* kick_out_if_recent */) - } - } - - consumed_weight - } -} - -/// Filter historical offences out and only allow those from the bonding period. -pub struct FilterHistoricalOffences { - _inner: sp_std::marker::PhantomData<(T, R)>, -} - -impl ReportOffence - for FilterHistoricalOffences, R> -where - T: Config, - R: ReportOffence, - O: Offence, -{ - fn report_offence(reporters: Vec, offence: O) -> Result<(), OffenceError> { - // Disallow any slashing from before the current bonding period. - let offence_session = offence.session_index(); - let bonded_eras = BondedEras::::get(); - - if bonded_eras.first().filter(|(_, start)| offence_session >= *start).is_some() { - R::report_offence(reporters, offence) - } else { - >::deposit_event(Event::::OldSlashingReportDiscarded(offence_session)); - Ok(()) - } - } - - fn is_known_offence(offenders: &[Offender], time_slot: &O::TimeSlot) -> bool { - R::is_known_offence(offenders, time_slot) - } -} - -/// Check that list is sorted and has no duplicates. -fn is_sorted_and_unique(list: &[u32]) -> bool { - list.windows(2).all(|w| w[0] < w[1]) -} diff --git a/lib-serml/serp/serp-staking/src/mock.rs b/lib-serml/serp/serp-staking/src/mock.rs deleted file mode 100644 index 7544d6820..000000000 --- a/lib-serml/serp/serp-staking/src/mock.rs +++ /dev/null @@ -1,839 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2018-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Test utilities - -use crate as staking; -use crate::*; -use frame_election_provider_support::onchain; -use frame_support::{ - assert_ok, parameter_types, - traits::{Currency, FindAuthor, Get, OnInitialize, OneSessionHandler}, - weights::constants::RocksDbWeight, -}; -use orml_traits::parameter_type_with_key; -use primitives::{TokenSymbol, TradingPair}; -use sp_core::H256; -use sp_io; -use sp_runtime::{ - curve::PiecewiseLinear, - testing::{Header, TestXt, UintAuthorityId}, - traits::{IdentityLookup, Zero}, -}; -use sp_staking::offence::{OffenceDetails, OnOffenceHandler}; -use std::{cell::RefCell, collections::HashSet}; - -pub const INIT_TIMESTAMP: u64 = 30_000; -pub const BLOCK_TIME: u64 = 1000; - -// Currencies constants - CurrencyId/TokenSymbol -pub const DNAR: CurrencyId = CurrencyId::Token(TokenSymbol::DNAR); -pub const DRAM: CurrencyId = CurrencyId::Token(TokenSymbol::DRAM); -pub const SETR: CurrencyId = CurrencyId::Token(TokenSymbol::SETR); - -/// The AccountId alias in this test module. -pub(crate) type AccountId = u64; -pub(crate) type AccountIndex = u64; -pub(crate) type BlockNumber = u64; -pub(crate) type Balance = u128; - -thread_local! { - static SESSION: RefCell<(Vec, HashSet)> = RefCell::new(Default::default()); -} - -/// Another session handler struct to test on_disabled. -pub struct OtherSessionHandler; -impl OneSessionHandler for OtherSessionHandler { - type Key = UintAuthorityId; - - fn on_genesis_session<'a, I: 'a>(_: I) - where - I: Iterator, - AccountId: 'a, - { - } - - fn on_new_session<'a, I: 'a>(_: bool, validators: I, _: I) - where - I: Iterator, - AccountId: 'a, - { - SESSION.with(|x| { - *x.borrow_mut() = (validators.map(|x| x.0.clone()).collect(), HashSet::new()) - }); - } - - fn on_disabled(validator_index: usize) { - SESSION.with(|d| { - let mut d = d.borrow_mut(); - let value = d.0[validator_index]; - d.1.insert(value); - }) - } -} - -impl sp_runtime::BoundToRuntimeAppPublic for OtherSessionHandler { - type Public = UintAuthorityId; -} - -pub fn is_disabled(controller: AccountId) -> bool { - let stash = Staking::ledger(&controller).unwrap().stash; - SESSION.with(|d| d.borrow().1.contains(&stash)) -} - -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; -type Block = frame_system::mocking::MockBlock; - -frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - Authorship: pallet_authorship::{Pallet, Call, Storage, Inherent}, - Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, - Currencies: orml_currencies::{Pallet, Call, Event}, - Tokens: orml_tokens::{Pallet, Storage, Event, Config}, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Staking: staking::{Pallet, Call, Config, Storage, Event}, - Session: pallet_session::{Pallet, Call, Storage, Event, Config}, - } -); - -/// Author of block is always 11 -pub struct Author11; -impl FindAuthor for Author11 { - fn find_author<'a, I>(_digests: I) -> Option - where - I: 'a + IntoIterator, - { - Some(11) - } -} - -parameter_types! { - pub const BlockHashCount: u64 = 250; - pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::simple_max( - frame_support::weights::constants::WEIGHT_PER_SECOND * 2 - ); - pub const MaxLocks: u32 = 1024; - pub static SessionsPerEra: SessionIndex = 3; - pub static ExistentialDeposit: Balance = 1; - pub static SlashDeferDuration: EraIndex = 0; - pub static Period: BlockNumber = 5; - pub static Offset: BlockNumber = 0; -} - -impl frame_system::Config for Test { - type BaseCallFilter = frame_support::traits::AllowAll; - type BlockWeights = (); - type BlockLength = (); - type DbWeight = RocksDbWeight; - type Origin = Origin; - type Index = AccountIndex; - type BlockNumber = BlockNumber; - type Call = Call; - type Hash = H256; - type Hashing = ::sp_runtime::traits::BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; - type Header = Header; - type Event = Event; - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); -} -parameter_type_with_key! { - pub ExistentialDeposits: |_currency_id: CurrencyId| -> Balance { - Default::default() - }; -} -impl orml_tokens::Config for Runtime { - type Event = Event; - type Balance = Balance; - type Amount = Amount; - type CurrencyId = CurrencyId; - type WeightInfo = (); - type ExistentialDeposits = ExistentialDeposits; - type OnDust = (); - type MaxLocks = (); - type DustRemovalWhitelist = (); -} -impl pallet_balances::Config for Test { - type MaxLocks = MaxLocks; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = Balance; - type Event = Event; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type WeightInfo = (); -} -pub type AdaptedBasicCurrency = orml_currencies::BasicCurrencyAdapter; - -parameter_types! { - pub const GetNativeCurrencyId: CurrencyId = DNAR; - pub const SetterCurrencyId: CurrencyId = SETR; - pub const DirhamCurrencyId: CurrencyId = DRAM; -} -impl orml_currencies::Config for Runtime { - type Event = Event; - type MultiCurrency = Tokens; - type NativeCurrency = AdaptedBasicCurrency; - type GetNativeCurrencyId = GetNativeCurrencyId; - type WeightInfo = (); -} -parameter_types! { - pub const UncleGenerations: u64 = 0; - pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(25); -} -sp_runtime::impl_opaque_keys! { - pub struct SessionKeys { - pub other: OtherSessionHandler, - } -} -impl pallet_session::Config for Test { - type SessionManager = pallet_session::historical::NoteHistoricalRoot; - type Keys = SessionKeys; - type ShouldEndSession = pallet_session::PeriodicSessions; - type SessionHandler = (OtherSessionHandler,); - type Event = Event; - type ValidatorId = AccountId; - type ValidatorIdOf = crate::StashOf; - type DisabledValidatorsThreshold = DisabledValidatorsThreshold; - type NextSessionRotation = pallet_session::PeriodicSessions; - type WeightInfo = (); -} - -impl pallet_session::historical::Config for Test { - type FullIdentification = crate::Exposure; - type FullIdentificationOf = crate::ExposureOf; -} -impl pallet_authorship::Config for Test { - type FindAuthor = Author11; - type UncleGenerations = UncleGenerations; - type FilterUncle = (); - type EventHandler = Pallet; -} -parameter_types! { - pub const MinimumPeriod: u64 = 5; -} -impl pallet_timestamp::Config for Test { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = MinimumPeriod; - type WeightInfo = (); -} -serp_staking_reward_curve::build! { - const I_NPOS: PiecewiseLinear<'static> = curve!( - min_inflation: 0_025_000, - max_inflation: 0_100_000, - ideal_stake: 0_500_000, - falloff: 0_050_000, - max_piece_count: 40, - test_precision: 0_005_000, - ); -} -parameter_types! { - pub const BondingDuration: EraIndex = 3; - pub const RewardCurve: &'static PiecewiseLinear<'static> = &I_NPOS; - pub const MaxNominatorRewardedPerValidator: u32 = 64; -} - -impl onchain::Config for Test { - type AccountId = AccountId; - type BlockNumber = BlockNumber; - type BlockWeights = BlockWeights; - type Accuracy = Perbill; - type DataProvider = Staking; -} - -impl Config for Test { - const MAX_NOMINATIONS: u32 = 16; - type Currency = Balances; - type MultiCurrency = Tokens; - type SetterCurrencyId = SetterCurrencyId; - type DirhamCurrencyId = DirhamCurrencyId; - type NativeCurrencyId = NativeCurrencyId; - type PriceSource = MockPriceSource; - type UnixTime = Timestamp; - type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote; - type Event = Event; - type Slash = (); - type Reward = (); - type SessionsPerEra = SessionsPerEra; - type SlashDeferDuration = SlashDeferDuration; - type SlashCancelOrigin = frame_system::EnsureRoot; - type BondingDuration = BondingDuration; - type SessionInterface = Self; - type EraPayout = ConvertCurve; - type NextNewSession = Session; - type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; - type ElectionProvider = onchain::OnChainSequentialPhragmen; - type GenesisElectionProvider = Self::ElectionProvider; - type WeightInfo = (); -} - -impl frame_system::offchain::SendTransactionTypes for Test -where - Call: From, -{ - type OverarchingCall = Call; - type Extrinsic = Extrinsic; -} - -pub type Extrinsic = TestXt; -pub(crate) type StakingCall = crate::Call; -pub(crate) type TestRuntimeCall = ::Call; - -pub struct ExtBuilder { - validator_pool: bool, - nominate: bool, - validator_count: u32, - minimum_validator_count: u32, - fair: bool, - num_validators: Option, - invulnerables: Vec, - has_stakers: bool, - initialize_first_session: bool, - min_nominator_bond: Balance, - min_validator_bond: Balance, -} - -impl Default for ExtBuilder { - fn default() -> Self { - Self { - validator_pool: false, - nominate: true, - validator_count: 2, - minimum_validator_count: 0, - fair: true, - num_validators: None, - invulnerables: vec![], - has_stakers: true, - initialize_first_session: true, - min_nominator_bond: ExistentialDeposit::get(), - min_validator_bond: ExistentialDeposit::get(), - } - } -} - -impl ExtBuilder { - pub fn existential_deposit(self, existential_deposit: Balance) -> Self { - EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = existential_deposit); - self - } - pub fn validator_pool(mut self, validator_pool: bool) -> Self { - self.validator_pool = validator_pool; - self - } - pub fn nominate(mut self, nominate: bool) -> Self { - self.nominate = nominate; - self - } - pub fn validator_count(mut self, count: u32) -> Self { - self.validator_count = count; - self - } - pub fn minimum_validator_count(mut self, count: u32) -> Self { - self.minimum_validator_count = count; - self - } - pub fn slash_defer_duration(self, eras: EraIndex) -> Self { - SLASH_DEFER_DURATION.with(|v| *v.borrow_mut() = eras); - self - } - pub fn fair(mut self, is_fair: bool) -> Self { - self.fair = is_fair; - self - } - pub fn num_validators(mut self, num_validators: u32) -> Self { - self.num_validators = Some(num_validators); - self - } - pub fn invulnerables(mut self, invulnerables: Vec) -> Self { - self.invulnerables = invulnerables; - self - } - pub fn session_per_era(self, length: SessionIndex) -> Self { - SESSIONS_PER_ERA.with(|v| *v.borrow_mut() = length); - self - } - pub fn period(self, length: BlockNumber) -> Self { - PERIOD.with(|v| *v.borrow_mut() = length); - self - } - pub fn has_stakers(mut self, has: bool) -> Self { - self.has_stakers = has; - self - } - pub fn initialize_first_session(mut self, init: bool) -> Self { - self.initialize_first_session = init; - self - } - pub fn offset(self, offset: BlockNumber) -> Self { - OFFSET.with(|v| *v.borrow_mut() = offset); - self - } - pub fn min_nominator_bond(mut self, amount: Balance) -> Self { - self.min_nominator_bond = amount; - self - } - pub fn min_validator_bond(mut self, amount: Balance) -> Self { - self.min_validator_bond = amount; - self - } - fn build(self) -> sp_io::TestExternalities { - sp_tracing::try_init_simple(); - let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); - let balance_factor = if ExistentialDeposit::get() > 1 { 256 } else { 1 }; - - let num_validators = self.num_validators.unwrap_or(self.validator_count); - // Check that the number of validators is sensible. - assert!(num_validators <= 8); - let validators = - (0..num_validators).map(|x| ((x + 1) * 10 + 1) as AccountId).collect::>(); - - let _ = pallet_balances::GenesisConfig:: { - balances: vec![ - (1, 10 * balance_factor), - (2, 20 * balance_factor), - (3, 300 * balance_factor), - (4, 400 * balance_factor), - (10, balance_factor), - (11, balance_factor * 1000), - (20, balance_factor), - (21, balance_factor * 2000), - (30, balance_factor), - (31, balance_factor * 2000), - (40, balance_factor), - (41, balance_factor * 2000), - (50, balance_factor), - (51, balance_factor * 2000), - (60, balance_factor), - (61, balance_factor * 2000), - (70, balance_factor), - (71, balance_factor * 2000), - (80, balance_factor), - (81, balance_factor * 2000), - (100, 2000 * balance_factor), - (101, 2000 * balance_factor), - // This allows us to have a total_payout different from 0. - (999, 1_000_000_000_000), - ], - } - .assimilate_storage(&mut storage); - - let mut stakers = vec![]; - if self.has_stakers { - let stake_21 = if self.fair { 1000 } else { 2000 }; - let stake_31 = if self.validator_pool { balance_factor * 1000 } else { 1 }; - let status_41 = if self.validator_pool { - StakerStatus::::Validator - } else { - StakerStatus::::Idle - }; - let nominated = if self.nominate { vec![11, 21] } else { vec![] }; - stakers = vec![ - // (stash, controller, staked_amount, status) - (11, 10, balance_factor * 1000, StakerStatus::::Validator), - (21, 20, stake_21, StakerStatus::::Validator), - (31, 30, stake_31, StakerStatus::::Validator), - (41, 40, balance_factor * 1000, status_41), - // nominator - (101, 100, balance_factor * 500, StakerStatus::::Nominator(nominated)), - ]; - } - let _ = staking::GenesisConfig:: { - stakers, - validator_count: self.validator_count, - minimum_validator_count: self.minimum_validator_count, - invulnerables: self.invulnerables, - slash_reward_fraction: Perbill::from_percent(10), - min_nominator_bond: self.min_nominator_bond, - min_validator_bond: self.min_validator_bond, - ..Default::default() - } - .assimilate_storage(&mut storage); - - let _ = pallet_session::GenesisConfig:: { - keys: validators - .iter() - .map(|x| (*x, *x, SessionKeys { other: UintAuthorityId(*x as u64) })) - .collect(), - } - .assimilate_storage(&mut storage); - - let mut ext = sp_io::TestExternalities::from(storage); - ext.execute_with(|| { - let validators = Session::validators(); - SESSION.with(|x| *x.borrow_mut() = (validators.clone(), HashSet::new())); - }); - - if self.initialize_first_session { - // We consider all test to start after timestamp is initialized This must be ensured by - // having `timestamp::on_initialize` called before `staking::on_initialize`. Also, if - // session length is 1, then it is already triggered. - ext.execute_with(|| { - System::set_block_number(1); - Session::on_initialize(1); - >::on_initialize(1); - Timestamp::set_timestamp(INIT_TIMESTAMP); - }); - } - - ext - } - pub fn build_and_execute(self, test: impl FnOnce() -> ()) { - let mut ext = self.build(); - ext.execute_with(test); - ext.execute_with(post_conditions); - } -} - -fn post_conditions() { - check_nominators(); - check_exposures(); - check_ledgers(); - check_count(); -} - -fn check_count() { - let nominator_count = Nominators::::iter().count() as u32; - let validator_count = Validators::::iter().count() as u32; - assert_eq!(nominator_count, CounterForNominators::::get()); - assert_eq!(validator_count, CounterForValidators::::get()); -} - -fn check_ledgers() { - // check the ledger of all stakers. - Bonded::::iter().for_each(|(_, ctrl)| assert_ledger_consistent(ctrl)) -} - -fn check_exposures() { - // a check per validator to ensure the exposure struct is always sane. - let era = active_era(); - ErasStakers::::iter_prefix_values(era).for_each(|expo| { - assert_eq!( - expo.total as u128, - expo.own as u128 + expo.others.iter().map(|e| e.value as u128).sum::(), - "wrong total exposure.", - ); - }) -} - -fn check_nominators() { - // a check per nominator to ensure their entire stake is correctly distributed. Will only kick- - // in if the nomination was submitted before the current era. - let era = active_era(); - >::iter() - .filter_map( - |(nominator, nomination)| { - if nomination.submitted_in > era { - Some(nominator) - } else { - None - } - }, - ) - .for_each(|nominator| { - // must be bonded. - assert_is_stash(nominator); - let mut sum = 0; - Session::validators() - .iter() - .map(|v| Staking::eras_stakers(era, v)) - .for_each(|e| { - let individual = - e.others.iter().filter(|e| e.who == nominator).collect::>(); - let len = individual.len(); - match len { - 0 => { /* not supporting this validator at all. */ }, - 1 => sum += individual[0].value, - _ => panic!("nominator cannot back a validator more than once."), - }; - }); - - let nominator_stake = Staking::slashable_balance_of(&nominator); - // a nominator cannot over-spend. - assert!( - nominator_stake >= sum, - "failed: Nominator({}) stake({}) >= sum divided({})", - nominator, - nominator_stake, - sum, - ); - - let diff = nominator_stake - sum; - assert!(diff < 100); - }); -} - -fn assert_is_stash(acc: AccountId) { - assert!(Staking::bonded(&acc).is_some(), "Not a stash."); -} - -fn assert_ledger_consistent(ctrl: AccountId) { - // ensures ledger.total == ledger.active + sum(ledger.unlocking). - let ledger = Staking::ledger(ctrl).expect("Not a controller."); - let real_total: Balance = ledger.unlocking.iter().fold(ledger.active, |a, c| a + c.value); - assert_eq!(real_total, ledger.total); - assert!( - ledger.active >= Balances::minimum_balance() || ledger.active == 0, - "{}: active ledger amount ({}) must be greater than ED {}", - ctrl, - ledger.active, - Balances::minimum_balance() - ); -} - -pub(crate) fn active_era() -> EraIndex { - Staking::active_era().unwrap().index -} - -pub(crate) fn current_era() -> EraIndex { - Staking::current_era().unwrap() -} - -pub(crate) fn bond_validator(stash: AccountId, ctrl: AccountId, val: Balance) { - let _ = Balances::make_free_balance_be(&stash, val); - let _ = Balances::make_free_balance_be(&ctrl, val); - assert_ok!(Staking::bond(Origin::signed(stash), ctrl, val, RewardDestination::Controller)); - assert_ok!(Staking::validate(Origin::signed(ctrl), ValidatorPrefs::default())); -} - -pub(crate) fn bond_nominator( - stash: AccountId, - ctrl: AccountId, - val: Balance, - target: Vec, -) { - let _ = Balances::make_free_balance_be(&stash, val); - let _ = Balances::make_free_balance_be(&ctrl, val); - assert_ok!(Staking::bond(Origin::signed(stash), ctrl, val, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(ctrl), target)); -} - -/// Progress to the given block, triggering session and era changes as we progress. -/// -/// This will finalize the previous block, initialize up to the given block, essentially simulating -/// a block import/propose process where we first initialize the block, then execute some stuff (not -/// in the function), and then finalize the block. -pub(crate) fn run_to_block(n: BlockNumber) { - Staking::on_finalize(System::block_number()); - for b in (System::block_number() + 1)..=n { - System::set_block_number(b); - Session::on_initialize(b); - >::on_initialize(b); - Timestamp::set_timestamp(System::block_number() * BLOCK_TIME + INIT_TIMESTAMP); - if b != n { - Staking::on_finalize(System::block_number()); - } - } -} - -/// Progresses from the current block number (whatever that may be) to the `P * session_index + 1`. -pub(crate) fn start_session(session_index: SessionIndex) { - let end: u64 = if Offset::get().is_zero() { - (session_index as u64) * Period::get() - } else { - Offset::get() + (session_index.saturating_sub(1) as u64) * Period::get() - }; - run_to_block(end); - // session must have progressed properly. - assert_eq!( - Session::current_index(), - session_index, - "current session index = {}, expected = {}", - Session::current_index(), - session_index, - ); -} - -/// Go one session forward. -pub(crate) fn advance_session() { - let current_index = Session::current_index(); - start_session(current_index + 1); -} - -/// Progress until the given era. -pub(crate) fn start_active_era(era_index: EraIndex) { - start_session((era_index * >::get()).into()); - assert_eq!(active_era(), era_index); - // One way or another, current_era must have changed before the active era, so they must match - // at this point. - assert_eq!(current_era(), active_era()); -} - -pub(crate) fn current_total_payout_for_duration(duration: u64) -> Balance { - let (payout, _rest) = ::EraPayout::era_payout( - Staking::eras_total_stake(active_era()), - Balances::total_issuance(), - duration, - ); - assert!(payout > 0); - payout -} - -pub(crate) fn maximum_payout_for_duration(duration: u64) -> Balance { - let (payout, rest) = ::EraPayout::era_payout( - Staking::eras_total_stake(active_era()), - Balances::total_issuance(), - duration, - ); - payout + rest -} - -/// Time it takes to finish a session. -/// -/// Note, if you see `time_per_session() - BLOCK_TIME`, it is fine. This is because we set the -/// timestamp after on_initialize, so the timestamp is always one block old. -pub(crate) fn time_per_session() -> u64 { - Period::get() * BLOCK_TIME -} - -/// Time it takes to finish an era. -/// -/// Note, if you see `time_per_era() - BLOCK_TIME`, it is fine. This is because we set the -/// timestamp after on_initialize, so the timestamp is always one block old. -pub(crate) fn time_per_era() -> u64 { - time_per_session() * SessionsPerEra::get() as u64 -} - -/// Time that will be calculated for the reward per era. -pub(crate) fn reward_time_per_era() -> u64 { - time_per_era() - BLOCK_TIME -} - -pub(crate) fn reward_all_elected() { - let rewards = ::SessionInterface::validators().into_iter().map(|v| (v, 1)); - - >::reward_by_ids(rewards) -} - -pub(crate) fn validator_controllers() -> Vec { - Session::validators() - .into_iter() - .map(|s| Staking::bonded(&s).expect("no controller for validator")) - .collect() -} - -pub(crate) fn on_offence_in_era( - offenders: &[OffenceDetails< - AccountId, - pallet_session::historical::IdentificationTuple, - >], - slash_fraction: &[Perbill], - era: EraIndex, -) { - let bonded_eras = crate::BondedEras::::get(); - for &(bonded_era, start_session) in bonded_eras.iter() { - if bonded_era == era { - let _ = Staking::on_offence(offenders, slash_fraction, start_session); - return - } else if bonded_era > era { - break - } - } - - if Staking::active_era().unwrap().index == era { - let _ = Staking::on_offence( - offenders, - slash_fraction, - Staking::eras_start_session_index(era).unwrap(), - ); - } else { - panic!("cannot slash in era {}", era); - } -} - -pub(crate) fn on_offence_now( - offenders: &[OffenceDetails< - AccountId, - pallet_session::historical::IdentificationTuple, - >], - slash_fraction: &[Perbill], -) { - let now = Staking::active_era().unwrap().index; - on_offence_in_era(offenders, slash_fraction, now) -} - -pub(crate) fn add_slash(who: &AccountId) { - on_offence_now( - &[OffenceDetails { - offender: (who.clone(), Staking::eras_stakers(active_era(), who.clone())), - reporters: vec![], - }], - &[Perbill::from_percent(10)], - ); -} - -/// Make all validator and nominator request their payment -pub(crate) fn make_all_reward_payment(era: EraIndex) { - let validators_with_reward = ErasRewardPoints::::get(era) - .individual - .keys() - .cloned() - .collect::>(); - - // reward validators - for validator_controller in validators_with_reward.iter().filter_map(Staking::bonded) { - let ledger = >::get(&validator_controller).unwrap(); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), ledger.stash, era)); - } -} - -#[macro_export] -macro_rules! assert_session_era { - ($session:expr, $era:expr) => { - assert_eq!( - Session::current_index(), - $session, - "wrong session {} != {}", - Session::current_index(), - $session, - ); - assert_eq!( - Staking::current_era().unwrap(), - $era, - "wrong current era {} != {}", - Staking::current_era().unwrap(), - $era, - ); - }; -} - -pub(crate) fn staking_events() -> Vec> { - System::events() - .into_iter() - .map(|r| r.event) - .filter_map(|e| if let Event::Staking(inner) = e { Some(inner) } else { None }) - .collect() -} - -pub(crate) fn balances(who: &AccountId) -> (Balance, Balance) { - (Balances::free_balance(who), Balances::reserved_balance(who)) -} diff --git a/lib-serml/serp/serp-staking/src/slashing.rs b/lib-serml/serp/serp-staking/src/slashing.rs deleted file mode 100644 index 227043b65..000000000 --- a/lib-serml/serp/serp-staking/src/slashing.rs +++ /dev/null @@ -1,810 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! A slashing implementation for NPoS systems. -//! -//! For the purposes of the economic model, it is easiest to think of each validator as a nominator -//! which nominates only its own identity. -//! -//! The act of nomination signals intent to unify economic identity with the validator - to take -//! part in the rewards of a job well done, and to take part in the punishment of a job done badly. -//! -//! There are 3 main difficulties to account for with slashing in NPoS: -//! - A nominator can nominate multiple validators and be slashed via any of them. -//! - Until slashed, stake is reused from era to era. Nominating with N coins for E eras in a row -//! does not mean you have N*E coins to be slashed - you've only ever had N. -//! - Slashable offences can be found after the fact and out of order. -//! -//! The algorithm implemented in this module tries to balance these 3 difficulties. -//! -//! First, we only slash participants for the _maximum_ slash they receive in some time period, -//! rather than the sum. This ensures a protection from overslashing. -//! -//! Second, we do not want the time period (or "span") that the maximum is computed -//! over to last indefinitely. That would allow participants to begin acting with -//! impunity after some point, fearing no further repercussions. For that reason, we -//! automatically "chill" validators and withdraw a nominator's nomination after a slashing event, -//! requiring them to re-enlist voluntarily (acknowledging the slash) and begin a new -//! slashing span. -//! -//! Typically, you will have a single slashing event per slashing span. Only in the case -//! where a validator releases many misbehaviors at once, or goes "back in time" to misbehave in -//! eras that have already passed, would you encounter situations where a slashing span -//! has multiple misbehaviors. However, accounting for such cases is necessary -//! to deter a class of "rage-quit" attacks. -//! -//! Based on research at - -use super::{ - BalanceOf, Config, EraIndex, Error, Exposure, NegativeImbalanceOf, Pallet, Perbill, - SessionInterface, Store, UnappliedSlash, -}; -use codec::{Decode, Encode}; -use frame_support::{ - ensure, - traits::{Currency, Imbalance, OnUnbalanced}, -}; -use sp_runtime::{ - traits::{Saturating, Zero}, - DispatchResult, RuntimeDebug, -}; -use sp_std::vec::Vec; - -/// The proportion of the slashing reward to be paid out on the first slashing detection. -/// This is f_1 in the paper. -const REWARD_F1: Perbill = Perbill::from_percent(50); - -/// The index of a slashing span - unique to each stash. -pub type SpanIndex = u32; - -// A range of start..end eras for a slashing span. -#[derive(Encode, Decode)] -#[cfg_attr(test, derive(Debug, PartialEq))] -pub(crate) struct SlashingSpan { - pub(crate) index: SpanIndex, - pub(crate) start: EraIndex, - pub(crate) length: Option, // the ongoing slashing span has indeterminate length. -} - -impl SlashingSpan { - fn contains_era(&self, era: EraIndex) -> bool { - self.start <= era && self.length.map_or(true, |l| self.start + l > era) - } -} - -/// An encoding of all of a nominator's slashing spans. -#[derive(Encode, Decode, RuntimeDebug)] -pub struct SlashingSpans { - // the index of the current slashing span of the nominator. different for - // every stash, resets when the account hits free balance 0. - span_index: SpanIndex, - // the start era of the most recent (ongoing) slashing span. - last_start: EraIndex, - // the last era at which a non-zero slash occurred. - last_nonzero_slash: EraIndex, - // all prior slashing spans' start indices, in reverse order (most recent first) - // encoded as offsets relative to the slashing span after it. - prior: Vec, -} - -impl SlashingSpans { - // creates a new record of slashing spans for a stash, starting at the beginning - // of the bonding period, relative to now. - pub(crate) fn new(window_start: EraIndex) -> Self { - SlashingSpans { - span_index: 0, - last_start: window_start, - // initialize to zero, as this structure is lazily created until - // the first slash is applied. setting equal to `window_start` would - // put a time limit on nominations. - last_nonzero_slash: 0, - prior: Vec::new(), - } - } - - // update the slashing spans to reflect the start of a new span at the era after `now` - // returns `true` if a new span was started, `false` otherwise. `false` indicates - // that internal state is unchanged. - pub(crate) fn end_span(&mut self, now: EraIndex) -> bool { - let next_start = now + 1; - if next_start <= self.last_start { - return false - } - - let last_length = next_start - self.last_start; - self.prior.insert(0, last_length); - self.last_start = next_start; - self.span_index += 1; - true - } - - // an iterator over all slashing spans in _reverse_ order - most recent first. - pub(crate) fn iter(&'_ self) -> impl Iterator + '_ { - let mut last_start = self.last_start; - let mut index = self.span_index; - let last = SlashingSpan { index, start: last_start, length: None }; - let prior = self.prior.iter().cloned().map(move |length| { - let start = last_start - length; - last_start = start; - index -= 1; - - SlashingSpan { index, start, length: Some(length) } - }); - - sp_std::iter::once(last).chain(prior) - } - - /// Yields the era index where the most recent non-zero slash occurred. - pub fn last_nonzero_slash(&self) -> EraIndex { - self.last_nonzero_slash - } - - // prune the slashing spans against a window, whose start era index is given. - // - // If this returns `Some`, then it includes a range start..end of all the span - // indices which were pruned. - fn prune(&mut self, window_start: EraIndex) -> Option<(SpanIndex, SpanIndex)> { - let old_idx = self - .iter() - .skip(1) // skip ongoing span. - .position(|span| span.length.map_or(false, |len| span.start + len <= window_start)); - - let earliest_span_index = self.span_index - self.prior.len() as SpanIndex; - let pruned = match old_idx { - Some(o) => { - self.prior.truncate(o); - let new_earliest = self.span_index - self.prior.len() as SpanIndex; - Some((earliest_span_index, new_earliest)) - }, - None => None, - }; - - // readjust the ongoing span, if it started before the beginning of the window. - self.last_start = sp_std::cmp::max(self.last_start, window_start); - pruned - } -} - -/// A slashing-span record for a particular stash. -#[derive(Encode, Decode, Default)] -pub(crate) struct SpanRecord { - slashed: Balance, - paid_out: Balance, -} - -impl SpanRecord { - /// The value of stash balance slashed in this span. - #[cfg(test)] - pub(crate) fn amount_slashed(&self) -> &Balance { - &self.slashed - } -} - -/// Parameters for performing a slash. -#[derive(Clone)] -pub(crate) struct SlashParams<'a, T: 'a + Config> { - /// The stash account being slashed. - pub(crate) stash: &'a T::AccountId, - /// The proportion of the slash. - pub(crate) slash: Perbill, - /// The exposure of the stash and all nominators. - pub(crate) exposure: &'a Exposure>, - /// The era where the offence occurred. - pub(crate) slash_era: EraIndex, - /// The first era in the current bonding period. - pub(crate) window_start: EraIndex, - /// The current era. - pub(crate) now: EraIndex, - /// The maximum percentage of a slash that ever gets paid out. - /// This is f_inf in the paper. - pub(crate) reward_proportion: Perbill, -} - -/// Computes a slash of a validator and nominators. It returns an unapplied -/// record to be applied at some later point. Slashing metadata is updated in storage, -/// since unapplied records are only rarely intended to be dropped. -/// -/// The pending slash record returned does not have initialized reporters. Those have -/// to be set at a higher level, if any. -pub(crate) fn compute_slash( - params: SlashParams, -) -> Option>> { - let SlashParams { stash, slash, exposure, slash_era, window_start, now, reward_proportion } = - params.clone(); - - let mut reward_payout = Zero::zero(); - let mut val_slashed = Zero::zero(); - - // is the slash amount here a maximum for the era? - let own_slash = slash * exposure.own; - if slash * exposure.total == Zero::zero() { - // kick out the validator even if they won't be slashed, - // as long as the misbehavior is from their most recent slashing span. - kick_out_if_recent::(params); - return None - } - - let (prior_slash_p, _era_slash) = - as Store>::ValidatorSlashInEra::get(&slash_era, stash) - .unwrap_or((Perbill::zero(), Zero::zero())); - - // compare slash proportions rather than slash values to avoid issues due to rounding - // error. - if slash.deconstruct() > prior_slash_p.deconstruct() { - as Store>::ValidatorSlashInEra::insert(&slash_era, stash, &(slash, own_slash)); - } else { - // we slash based on the max in era - this new event is not the max, - // so neither the validator or any nominators will need an update. - // - // this does lead to a divergence of our system from the paper, which - // pays out some reward even if the latest report is not max-in-era. - // we opt to avoid the nominator lookups and edits and leave more rewards - // for more drastic misbehavior. - return None - } - - // apply slash to validator. - { - let mut spans = fetch_spans::( - stash, - window_start, - &mut reward_payout, - &mut val_slashed, - reward_proportion, - ); - - let target_span = spans.compare_and_update_span_slash(slash_era, own_slash); - - if target_span == Some(spans.span_index()) { - // misbehavior occurred within the current slashing span - take appropriate - // actions. - - // chill the validator - it misbehaved in the current span and should - // not continue in the next election. also end the slashing span. - spans.end_span(now); - >::chill_stash(stash); - - // make sure to disable validator till the end of this session - if T::SessionInterface::disable_validator(stash).unwrap_or(false) { - // force a new era, to select a new validator set - >::ensure_new_era() - } - } - } - - let mut nominators_slashed = Vec::new(); - reward_payout += slash_nominators::(params, prior_slash_p, &mut nominators_slashed); - - Some(UnappliedSlash { - validator: stash.clone(), - own: val_slashed, - others: nominators_slashed, - reporters: Vec::new(), - payout: reward_payout, - }) -} - -// doesn't apply any slash, but kicks out the validator if the misbehavior is from -// the most recent slashing span. -fn kick_out_if_recent(params: SlashParams) { - // these are not updated by era-span or end-span. - let mut reward_payout = Zero::zero(); - let mut val_slashed = Zero::zero(); - let mut spans = fetch_spans::( - params.stash, - params.window_start, - &mut reward_payout, - &mut val_slashed, - params.reward_proportion, - ); - - if spans.era_span(params.slash_era).map(|s| s.index) == Some(spans.span_index()) { - spans.end_span(params.now); - >::chill_stash(params.stash); - - // make sure to disable validator till the end of this session - if T::SessionInterface::disable_validator(params.stash).unwrap_or(false) { - // force a new era, to select a new validator set - >::ensure_new_era() - } - } -} - -/// Slash nominators. Accepts general parameters and the prior slash percentage of the validator. -/// -/// Returns the amount of reward to pay out. -fn slash_nominators( - params: SlashParams, - prior_slash_p: Perbill, - nominators_slashed: &mut Vec<(T::AccountId, BalanceOf)>, -) -> BalanceOf { - let SlashParams { stash: _, slash, exposure, slash_era, window_start, now, reward_proportion } = - params; - - let mut reward_payout = Zero::zero(); - - nominators_slashed.reserve(exposure.others.len()); - for nominator in &exposure.others { - let stash = &nominator.who; - let mut nom_slashed = Zero::zero(); - - // the era slash of a nominator always grows, if the validator - // had a new max slash for the era. - let era_slash = { - let own_slash_prior = prior_slash_p * nominator.value; - let own_slash_by_validator = slash * nominator.value; - let own_slash_difference = own_slash_by_validator.saturating_sub(own_slash_prior); - - let mut era_slash = as Store>::NominatorSlashInEra::get(&slash_era, stash) - .unwrap_or_else(|| Zero::zero()); - - era_slash += own_slash_difference; - - as Store>::NominatorSlashInEra::insert(&slash_era, stash, &era_slash); - - era_slash - }; - - // compare the era slash against other eras in the same span. - { - let mut spans = fetch_spans::( - stash, - window_start, - &mut reward_payout, - &mut nom_slashed, - reward_proportion, - ); - - let target_span = spans.compare_and_update_span_slash(slash_era, era_slash); - - if target_span == Some(spans.span_index()) { - // End the span, but don't chill the nominator. its nomination - // on this validator will be ignored in the future. - spans.end_span(now); - } - } - - nominators_slashed.push((stash.clone(), nom_slashed)); - } - - reward_payout -} - -// helper struct for managing a set of spans we are currently inspecting. -// writes alterations to disk on drop, but only if a slash has been carried out. -// -// NOTE: alterations to slashing metadata should not be done after this is dropped. -// dropping this struct applies any necessary slashes, which can lead to free balance -// being 0, and the account being garbage-collected -- a dead account should get no new -// metadata. -struct InspectingSpans<'a, T: Config + 'a> { - dirty: bool, - window_start: EraIndex, - stash: &'a T::AccountId, - spans: SlashingSpans, - paid_out: &'a mut BalanceOf, - slash_of: &'a mut BalanceOf, - reward_proportion: Perbill, - _marker: sp_std::marker::PhantomData, -} - -// fetches the slashing spans record for a stash account, initializing it if necessary. -fn fetch_spans<'a, T: Config + 'a>( - stash: &'a T::AccountId, - window_start: EraIndex, - paid_out: &'a mut BalanceOf, - slash_of: &'a mut BalanceOf, - reward_proportion: Perbill, -) -> InspectingSpans<'a, T> { - let spans = as Store>::SlashingSpans::get(stash).unwrap_or_else(|| { - let spans = SlashingSpans::new(window_start); - as Store>::SlashingSpans::insert(stash, &spans); - spans - }); - - InspectingSpans { - dirty: false, - window_start, - stash, - spans, - slash_of, - paid_out, - reward_proportion, - _marker: sp_std::marker::PhantomData, - } -} - -impl<'a, T: 'a + Config> InspectingSpans<'a, T> { - fn span_index(&self) -> SpanIndex { - self.spans.span_index - } - - fn end_span(&mut self, now: EraIndex) { - self.dirty = self.spans.end_span(now) || self.dirty; - } - - // add some value to the slash of the staker. - // invariant: the staker is being slashed for non-zero value here - // although `amount` may be zero, as it is only a difference. - fn add_slash(&mut self, amount: BalanceOf, slash_era: EraIndex) { - *self.slash_of += amount; - self.spans.last_nonzero_slash = sp_std::cmp::max(self.spans.last_nonzero_slash, slash_era); - } - - // find the span index of the given era, if covered. - fn era_span(&self, era: EraIndex) -> Option { - self.spans.iter().find(|span| span.contains_era(era)) - } - - // compares the slash in an era to the overall current span slash. - // if it's higher, applies the difference of the slashes and then updates the span on disk. - // - // returns the span index of the era where the slash occurred, if any. - fn compare_and_update_span_slash( - &mut self, - slash_era: EraIndex, - slash: BalanceOf, - ) -> Option { - let target_span = self.era_span(slash_era)?; - let span_slash_key = (self.stash.clone(), target_span.index); - let mut span_record = as Store>::SpanSlash::get(&span_slash_key); - let mut changed = false; - - let reward = if span_record.slashed < slash { - // new maximum span slash. apply the difference. - let difference = slash - span_record.slashed; - span_record.slashed = slash; - - // compute reward. - let reward = - REWARD_F1 * (self.reward_proportion * slash).saturating_sub(span_record.paid_out); - - self.add_slash(difference, slash_era); - changed = true; - - reward - } else if span_record.slashed == slash { - // compute reward. no slash difference to apply. - REWARD_F1 * (self.reward_proportion * slash).saturating_sub(span_record.paid_out) - } else { - Zero::zero() - }; - - if !reward.is_zero() { - changed = true; - span_record.paid_out += reward; - *self.paid_out += reward; - } - - if changed { - self.dirty = true; - as Store>::SpanSlash::insert(&span_slash_key, &span_record); - } - - Some(target_span.index) - } -} - -impl<'a, T: 'a + Config> Drop for InspectingSpans<'a, T> { - fn drop(&mut self) { - // only update on disk if we slashed this account. - if !self.dirty { - return - } - - if let Some((start, end)) = self.spans.prune(self.window_start) { - for span_index in start..end { - as Store>::SpanSlash::remove(&(self.stash.clone(), span_index)); - } - } - - as Store>::SlashingSpans::insert(self.stash, &self.spans); - } -} - -/// Clear slashing metadata for an obsolete era. -pub(crate) fn clear_era_metadata(obsolete_era: EraIndex) { - as Store>::ValidatorSlashInEra::remove_prefix(&obsolete_era, None); - as Store>::NominatorSlashInEra::remove_prefix(&obsolete_era, None); -} - -/// Clear slashing metadata for a dead account. -pub(crate) fn clear_stash_metadata( - stash: &T::AccountId, - num_slashing_spans: u32, -) -> DispatchResult { - let spans = match as Store>::SlashingSpans::get(stash) { - None => return Ok(()), - Some(s) => s, - }; - - ensure!( - num_slashing_spans as usize >= spans.iter().count(), - Error::::IncorrectSlashingSpans - ); - - as Store>::SlashingSpans::remove(stash); - - // kill slashing-span metadata for account. - // - // this can only happen while the account is staked _if_ they are completely slashed. - // in that case, they may re-bond, but it would count again as span 0. Further ancient - // slashes would slash into this new bond, since metadata has now been cleared. - for span in spans.iter() { - as Store>::SpanSlash::remove(&(stash.clone(), span.index)); - } - - Ok(()) -} - -// apply the slash to a stash account, deducting any missing funds from the reward -// payout, saturating at 0. this is mildly unfair but also an edge-case that -// can only occur when overlapping locked funds have been slashed. -pub fn do_slash( - stash: &T::AccountId, - value: BalanceOf, - reward_payout: &mut BalanceOf, - slashed_imbalance: &mut NegativeImbalanceOf, -) { - let controller = match >::bonded(stash) { - None => return, // defensive: should always exist. - Some(c) => c, - }; - - let mut ledger = match >::ledger(&controller) { - Some(ledger) => ledger, - None => return, // nothing to do. - }; - - let value = ledger.slash(value, T::Currency::minimum_balance()); - - if !value.is_zero() { - let (imbalance, missing) = T::Currency::slash(stash, value); - slashed_imbalance.subsume(imbalance); - - if !missing.is_zero() { - // deduct overslash from the reward payout - *reward_payout = reward_payout.saturating_sub(missing); - } - - >::update_ledger(&controller, &ledger); - - // trigger the event - >::deposit_event(super::Event::::Slash(stash.clone(), value)); - } -} - -/// Apply a previously-unapplied slash. -pub(crate) fn apply_slash(unapplied_slash: UnappliedSlash>) { - let mut slashed_imbalance = NegativeImbalanceOf::::zero(); - let mut reward_payout = unapplied_slash.payout; - - do_slash::( - &unapplied_slash.validator, - unapplied_slash.own, - &mut reward_payout, - &mut slashed_imbalance, - ); - - for &(ref nominator, nominator_slash) in &unapplied_slash.others { - do_slash::(&nominator, nominator_slash, &mut reward_payout, &mut slashed_imbalance); - } - - pay_reporters::(reward_payout, slashed_imbalance, &unapplied_slash.reporters); -} - -/// Apply a reward payout to some reporters, paying the rewards out of the slashed imbalance. -fn pay_reporters( - reward_payout: BalanceOf, - slashed_imbalance: NegativeImbalanceOf, - reporters: &[T::AccountId], -) { - if reward_payout.is_zero() || reporters.is_empty() { - // nobody to pay out to or nothing to pay; - // just treat the whole value as slashed. - T::Slash::on_unbalanced(slashed_imbalance); - return - } - - // take rewards out of the slashed imbalance. - let reward_payout = reward_payout.min(slashed_imbalance.peek()); - let (mut reward_payout, mut value_slashed) = slashed_imbalance.split(reward_payout); - - let per_reporter = reward_payout.peek() / (reporters.len() as u32).into(); - for reporter in reporters { - let (reporter_reward, rest) = reward_payout.split(per_reporter); - reward_payout = rest; - - // this cancels out the reporter reward imbalance internally, leading - // to no change in total issuance. - T::Currency::resolve_creating(reporter, reporter_reward); - } - - // the rest goes to the on-slash imbalance handler (e.g. treasury) - value_slashed.subsume(reward_payout); // remainder of reward division remains. - T::Slash::on_unbalanced(value_slashed); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn span_contains_era() { - // unbounded end - let span = SlashingSpan { index: 0, start: 1000, length: None }; - assert!(!span.contains_era(0)); - assert!(!span.contains_era(999)); - - assert!(span.contains_era(1000)); - assert!(span.contains_era(1001)); - assert!(span.contains_era(10000)); - - // bounded end - non-inclusive range. - let span = SlashingSpan { index: 0, start: 1000, length: Some(10) }; - assert!(!span.contains_era(0)); - assert!(!span.contains_era(999)); - - assert!(span.contains_era(1000)); - assert!(span.contains_era(1001)); - assert!(span.contains_era(1009)); - assert!(!span.contains_era(1010)); - assert!(!span.contains_era(1011)); - } - - #[test] - fn single_slashing_span() { - let spans = SlashingSpans { - span_index: 0, - last_start: 1000, - last_nonzero_slash: 0, - prior: Vec::new(), - }; - - assert_eq!( - spans.iter().collect::>(), - vec![SlashingSpan { index: 0, start: 1000, length: None }], - ); - } - - #[test] - fn many_prior_spans() { - let spans = SlashingSpans { - span_index: 10, - last_start: 1000, - last_nonzero_slash: 0, - prior: vec![10, 9, 8, 10], - }; - - assert_eq!( - spans.iter().collect::>(), - vec![ - SlashingSpan { index: 10, start: 1000, length: None }, - SlashingSpan { index: 9, start: 990, length: Some(10) }, - SlashingSpan { index: 8, start: 981, length: Some(9) }, - SlashingSpan { index: 7, start: 973, length: Some(8) }, - SlashingSpan { index: 6, start: 963, length: Some(10) }, - ], - ) - } - - #[test] - fn pruning_spans() { - let mut spans = SlashingSpans { - span_index: 10, - last_start: 1000, - last_nonzero_slash: 0, - prior: vec![10, 9, 8, 10], - }; - - assert_eq!(spans.prune(981), Some((6, 8))); - assert_eq!( - spans.iter().collect::>(), - vec![ - SlashingSpan { index: 10, start: 1000, length: None }, - SlashingSpan { index: 9, start: 990, length: Some(10) }, - SlashingSpan { index: 8, start: 981, length: Some(9) }, - ], - ); - - assert_eq!(spans.prune(982), None); - assert_eq!( - spans.iter().collect::>(), - vec![ - SlashingSpan { index: 10, start: 1000, length: None }, - SlashingSpan { index: 9, start: 990, length: Some(10) }, - SlashingSpan { index: 8, start: 981, length: Some(9) }, - ], - ); - - assert_eq!(spans.prune(989), None); - assert_eq!( - spans.iter().collect::>(), - vec![ - SlashingSpan { index: 10, start: 1000, length: None }, - SlashingSpan { index: 9, start: 990, length: Some(10) }, - SlashingSpan { index: 8, start: 981, length: Some(9) }, - ], - ); - - assert_eq!(spans.prune(1000), Some((8, 10))); - assert_eq!( - spans.iter().collect::>(), - vec![SlashingSpan { index: 10, start: 1000, length: None },], - ); - - assert_eq!(spans.prune(2000), None); - assert_eq!( - spans.iter().collect::>(), - vec![SlashingSpan { index: 10, start: 2000, length: None },], - ); - - // now all in one shot. - let mut spans = SlashingSpans { - span_index: 10, - last_start: 1000, - last_nonzero_slash: 0, - prior: vec![10, 9, 8, 10], - }; - assert_eq!(spans.prune(2000), Some((6, 10))); - assert_eq!( - spans.iter().collect::>(), - vec![SlashingSpan { index: 10, start: 2000, length: None },], - ); - } - - #[test] - fn ending_span() { - let mut spans = SlashingSpans { - span_index: 1, - last_start: 10, - last_nonzero_slash: 0, - prior: Vec::new(), - }; - - assert!(spans.end_span(10)); - - assert_eq!( - spans.iter().collect::>(), - vec![ - SlashingSpan { index: 2, start: 11, length: None }, - SlashingSpan { index: 1, start: 10, length: Some(1) }, - ], - ); - - assert!(spans.end_span(15)); - assert_eq!( - spans.iter().collect::>(), - vec![ - SlashingSpan { index: 3, start: 16, length: None }, - SlashingSpan { index: 2, start: 11, length: Some(5) }, - SlashingSpan { index: 1, start: 10, length: Some(1) }, - ], - ); - - // does nothing if not a valid end. - assert!(!spans.end_span(15)); - assert_eq!( - spans.iter().collect::>(), - vec![ - SlashingSpan { index: 3, start: 16, length: None }, - SlashingSpan { index: 2, start: 11, length: Some(5) }, - SlashingSpan { index: 1, start: 10, length: Some(1) }, - ], - ); - } -} diff --git a/lib-serml/serp/serp-staking/src/testing_utils.rs b/lib-serml/serp/serp-staking/src/testing_utils.rs deleted file mode 100644 index 0d9ae2c8e..000000000 --- a/lib-serml/serp/serp-staking/src/testing_utils.rs +++ /dev/null @@ -1,188 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Testing utils for staking. Provides some common functions to setup staking state, such as -//! bonding validators, nominators, and generating different types of solutions. - -use crate::{Pallet as Staking, *}; -use frame_benchmarking::account; -use frame_system::RawOrigin; -use rand_chacha::{ - rand_core::{RngCore, SeedableRng}, - ChaChaRng, -}; -use sp_io::hashing::blake2_256; - -const SEED: u32 = 0; - -/// This function removes all validators and nominators from storage. -pub fn clear_validators_and_nominators() { - Validators::::remove_all(None); - CounterForValidators::::kill(); - Nominators::::remove_all(None); - CounterForNominators::::kill(); -} - -/// Grab a funded user. -pub fn create_funded_user( - string: &'static str, - n: u32, - balance_factor: u32, -) -> T::AccountId { - let user = account(string, n, SEED); - let balance = T::Currency::minimum_balance() * balance_factor.into(); - T::Currency::make_free_balance_be(&user, balance); - // ensure T::CurrencyToVote will work correctly. - T::Currency::issue(balance); - user -} - -/// Create a stash and controller pair. -pub fn create_stash_controller( - n: u32, - balance_factor: u32, - destination: RewardDestination, -) -> Result<(T::AccountId, T::AccountId), &'static str> { - let stash = create_funded_user::("stash", n, balance_factor); - let controller = create_funded_user::("controller", n, balance_factor); - let controller_lookup: ::Source = - T::Lookup::unlookup(controller.clone()); - let amount = T::Currency::minimum_balance() * (balance_factor / 10).max(1).into(); - Staking::::bond( - RawOrigin::Signed(stash.clone()).into(), - controller_lookup, - amount, - destination, - )?; - return Ok((stash, controller)) -} - -/// Create a stash and controller pair, where the controller is dead, and payouts go to controller. -/// This is used to test worst case payout scenarios. -pub fn create_stash_and_dead_controller( - n: u32, - balance_factor: u32, - destination: RewardDestination, -) -> Result<(T::AccountId, T::AccountId), &'static str> { - let stash = create_funded_user::("stash", n, balance_factor); - // controller has no funds - let controller = create_funded_user::("controller", n, 0); - let controller_lookup: ::Source = - T::Lookup::unlookup(controller.clone()); - let amount = T::Currency::minimum_balance() * (balance_factor / 10).max(1).into(); - Staking::::bond( - RawOrigin::Signed(stash.clone()).into(), - controller_lookup, - amount, - destination, - )?; - return Ok((stash, controller)) -} - -/// create `max` validators. -pub fn create_validators( - max: u32, - balance_factor: u32, -) -> Result::Source>, &'static str> { - let mut validators: Vec<::Source> = Vec::with_capacity(max as usize); - for i in 0..max { - let (stash, controller) = - create_stash_controller::(i, balance_factor, RewardDestination::Staked)?; - let validator_prefs = - ValidatorPrefs { commission: Perbill::from_percent(50), ..Default::default() }; - Staking::::validate(RawOrigin::Signed(controller).into(), validator_prefs)?; - let stash_lookup: ::Source = T::Lookup::unlookup(stash); - validators.push(stash_lookup); - } - Ok(validators) -} - -/// This function generates validators and nominators who are randomly nominating -/// `edge_per_nominator` random validators (until `to_nominate` if provided). -/// -/// NOTE: This function will remove any existing validators or nominators to ensure -/// we are working with a clean state. -/// -/// Parameters: -/// - `validators`: number of bonded validators -/// - `nominators`: number of bonded nominators. -/// - `edge_per_nominator`: number of edge (vote) per nominator. -/// - `randomize_stake`: whether to randomize the stakes. -/// - `to_nominate`: if `Some(n)`, only the first `n` bonded validator are voted upon. Else, all of -/// them are considered and `edge_per_nominator` random validators are voted for. -/// -/// Return the validators chosen to be nominated. -pub fn create_validators_with_nominators_for_era( - validators: u32, - nominators: u32, - edge_per_nominator: usize, - randomize_stake: bool, - to_nominate: Option, -) -> Result::Source>, &'static str> { - clear_validators_and_nominators::(); - - let mut validators_stash: Vec<::Source> = - Vec::with_capacity(validators as usize); - let mut rng = ChaChaRng::from_seed(SEED.using_encoded(blake2_256)); - - // Create validators - for i in 0..validators { - let balance_factor = if randomize_stake { rng.next_u32() % 255 + 10 } else { 100u32 }; - let (v_stash, v_controller) = - create_stash_controller::(i, balance_factor, RewardDestination::Staked)?; - let validator_prefs = - ValidatorPrefs { commission: Perbill::from_percent(50), ..Default::default() }; - Staking::::validate(RawOrigin::Signed(v_controller.clone()).into(), validator_prefs)?; - let stash_lookup: ::Source = - T::Lookup::unlookup(v_stash.clone()); - validators_stash.push(stash_lookup.clone()); - } - - let to_nominate = to_nominate.unwrap_or(validators_stash.len() as u32) as usize; - let validator_chosen = validators_stash[0..to_nominate].to_vec(); - - // Create nominators - for j in 0..nominators { - let balance_factor = if randomize_stake { rng.next_u32() % 255 + 10 } else { 100u32 }; - let (_n_stash, n_controller) = - create_stash_controller::(u32::MAX - j, balance_factor, RewardDestination::Staked)?; - - // Have them randomly validate - let mut available_validators = validator_chosen.clone(); - let mut selected_validators: Vec<::Source> = - Vec::with_capacity(edge_per_nominator); - - for _ in 0..validators.min(edge_per_nominator as u32) { - let selected = rng.next_u32() as usize % available_validators.len(); - let validator = available_validators.remove(selected); - selected_validators.push(validator); - } - Staking::::nominate( - RawOrigin::Signed(n_controller.clone()).into(), - selected_validators, - )?; - } - - ValidatorCount::::put(validators); - - Ok(validator_chosen) -} - -/// get the current era. -pub fn current_era() -> EraIndex { - >::current_era().unwrap_or(0) -} diff --git a/lib-serml/serp/serp-staking/src/tests.rs b/lib-serml/serp/serp-staking/src/tests.rs deleted file mode 100644 index fdb915ebc..000000000 --- a/lib-serml/serp/serp-staking/src/tests.rs +++ /dev/null @@ -1,4332 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Tests for the module. - -use super::{Event, *}; -use frame_election_provider_support::Support; -use frame_support::{ - assert_noop, assert_ok, - traits::{Currency, OnInitialize, ReservableCurrency}, - weights::{extract_actual_weight, GetDispatchInfo}, -}; -use mock::*; -use pallet_balances::Error as BalancesError; -use sp_runtime::{ - assert_eq_error_rate, - traits::{BadOrigin, Dispatchable}, -}; -use sp_staking::offence::OffenceDetails; -use substrate_test_utils::assert_eq_uvec; - -#[test] -fn force_unstake_works() { - ExtBuilder::default().build_and_execute(|| { - // Account 11 is stashed and locked, and account 10 is the controller - assert_eq!(Staking::bonded(&11), Some(10)); - // Adds 2 slashing spans - add_slash(&11); - // Cant transfer - assert_noop!( - Balances::transfer(Origin::signed(11), 1, 10), - BalancesError::::LiquidityRestrictions - ); - // Force unstake requires root. - assert_noop!(Staking::force_unstake(Origin::signed(11), 11, 2), BadOrigin); - // Force unstake needs correct number of slashing spans (for weight calculation) - assert_noop!( - Staking::force_unstake(Origin::root(), 11, 0), - Error::::IncorrectSlashingSpans - ); - // We now force them to unstake - assert_ok!(Staking::force_unstake(Origin::root(), 11, 2)); - // No longer bonded. - assert_eq!(Staking::bonded(&11), None); - // Transfer works. - assert_ok!(Balances::transfer(Origin::signed(11), 1, 10)); - }); -} - -#[test] -fn kill_stash_works() { - ExtBuilder::default().build_and_execute(|| { - // Account 11 is stashed and locked, and account 10 is the controller - assert_eq!(Staking::bonded(&11), Some(10)); - // Adds 2 slashing spans - add_slash(&11); - // Only can kill a stash account - assert_noop!(Staking::kill_stash(&12, 0), Error::::NotStash); - // Respects slashing span count - assert_noop!(Staking::kill_stash(&11, 0), Error::::IncorrectSlashingSpans); - // Correct inputs, everything works - assert_ok!(Staking::kill_stash(&11, 2)); - // No longer bonded. - assert_eq!(Staking::bonded(&11), None); - }); -} - -#[test] -fn basic_setup_works() { - // Verifies initial conditions of mock - ExtBuilder::default().build_and_execute(|| { - // Account 11 is stashed and locked, and account 10 is the controller - assert_eq!(Staking::bonded(&11), Some(10)); - // Account 21 is stashed and locked, and account 20 is the controller - assert_eq!(Staking::bonded(&21), Some(20)); - // Account 1 is not a stashed - assert_eq!(Staking::bonded(&1), None); - - // Account 10 controls the stash from account 11, which is 100 * balance_factor units - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![] - }) - ); - // Account 20 controls the stash from account 21, which is 200 * balance_factor units - assert_eq!( - Staking::ledger(&20), - Some(StakingLedger { - stash: 21, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![] - }) - ); - // Account 1 does not control any stash - assert_eq!(Staking::ledger(&1), None); - - // ValidatorPrefs are default - assert_eq_uvec!( - >::iter().collect::>(), - vec![ - (31, ValidatorPrefs::default()), - (21, ValidatorPrefs::default()), - (11, ValidatorPrefs::default()) - ] - ); - - assert_eq!( - Staking::ledger(100), - Some(StakingLedger { - stash: 101, - total: 500, - active: 500, - unlocking: vec![], - claimed_rewards: vec![] - }) - ); - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); - - assert_eq!( - Staking::eras_stakers(Staking::active_era().unwrap().index, 11), - Exposure { - total: 1125, - own: 1000, - others: vec![IndividualExposure { who: 101, value: 125 }] - }, - ); - assert_eq!( - Staking::eras_stakers(Staking::active_era().unwrap().index, 21), - Exposure { - total: 1375, - own: 1000, - others: vec![IndividualExposure { who: 101, value: 375 }] - }, - ); - - // initial total stake = 1125 + 1375 - assert_eq!(Staking::eras_total_stake(Staking::active_era().unwrap().index), 2500); - - // The number of validators required. - assert_eq!(Staking::validator_count(), 2); - - // Initial Era and session - assert_eq!(Staking::active_era().unwrap().index, 0); - - // Account 10 has `balance_factor` free balance - assert_eq!(Balances::free_balance(10), 1); - assert_eq!(Balances::free_balance(10), 1); - - // New era is not being forced - assert_eq!(Staking::force_era(), Forcing::NotForcing); - }); -} - -#[test] -fn change_controller_works() { - ExtBuilder::default().build_and_execute(|| { - // 10 and 11 are bonded as stash controller. - assert_eq!(Staking::bonded(&11), Some(10)); - - // 10 can control 11 who is initially a validator. - assert_ok!(Staking::chill(Origin::signed(10))); - - // change controller - assert_ok!(Staking::set_controller(Origin::signed(11), 5)); - assert_eq!(Staking::bonded(&11), Some(5)); - mock::start_active_era(1); - - // 10 is no longer in control. - assert_noop!( - Staking::validate(Origin::signed(10), ValidatorPrefs::default()), - Error::::NotController, - ); - assert_ok!(Staking::validate(Origin::signed(5), ValidatorPrefs::default())); - }) -} - -#[test] -fn rewards_should_work() { - ExtBuilder::default().nominate(true).session_per_era(3).build_and_execute(|| { - let init_balance_10 = Balances::total_balance(&10); - let init_balance_11 = Balances::total_balance(&11); - let init_balance_20 = Balances::total_balance(&20); - let init_balance_21 = Balances::total_balance(&21); - let init_balance_100 = Balances::total_balance(&100); - let init_balance_101 = Balances::total_balance(&101); - - // Set payees - Payee::::insert(11, RewardDestination::Controller); - Payee::::insert(21, RewardDestination::Controller); - Payee::::insert(101, RewardDestination::Controller); - - >::reward_by_ids(vec![(11, 50)]); - >::reward_by_ids(vec![(11, 50)]); - // This is the second validator of the current elected set. - >::reward_by_ids(vec![(21, 50)]); - - // Compute total payout now for whole duration of the session. - let total_payout_0 = current_total_payout_for_duration(reward_time_per_era()); - let maximum_payout = maximum_payout_for_duration(reward_time_per_era()); - - start_session(1); - - assert_eq!(Balances::total_balance(&10), init_balance_10); - assert_eq!(Balances::total_balance(&11), init_balance_11); - assert_eq!(Balances::total_balance(&20), init_balance_20); - assert_eq!(Balances::total_balance(&21), init_balance_21); - assert_eq!(Balances::total_balance(&100), init_balance_100); - assert_eq!(Balances::total_balance(&101), init_balance_101); - assert_eq_uvec!(Session::validators(), vec![11, 21]); - assert_eq!( - Staking::eras_reward_points(Staking::active_era().unwrap().index), - EraRewardPoints { - total: 50 * 3, - individual: vec![(11, 100), (21, 50)].into_iter().collect(), - } - ); - let part_for_10 = Perbill::from_rational::(1000, 1125); - let part_for_20 = Perbill::from_rational::(1000, 1375); - let part_for_100_from_10 = Perbill::from_rational::(125, 1125); - let part_for_100_from_20 = Perbill::from_rational::(375, 1375); - - start_session(2); - start_session(3); - - assert_eq!(Staking::active_era().unwrap().index, 1); - assert_eq!( - mock::REWARD_REMAINDER_UNBALANCED.with(|v| *v.borrow()), - maximum_payout - total_payout_0, - ); - assert_eq!( - *mock::staking_events().last().unwrap(), - Event::EraPayout(0, total_payout_0, maximum_payout - total_payout_0) - ); - mock::make_all_reward_payment(0); - - assert_eq_error_rate!( - Balances::total_balance(&10), - init_balance_10 + part_for_10 * total_payout_0 * 2 / 3, - 2, - ); - assert_eq_error_rate!(Balances::total_balance(&11), init_balance_11, 2); - assert_eq_error_rate!( - Balances::total_balance(&20), - init_balance_20 + part_for_20 * total_payout_0 * 1 / 3, - 2, - ); - assert_eq_error_rate!(Balances::total_balance(&21), init_balance_21, 2); - assert_eq_error_rate!( - Balances::total_balance(&100), - init_balance_100 + - part_for_100_from_10 * total_payout_0 * 2 / 3 + - part_for_100_from_20 * total_payout_0 * 1 / 3, - 2 - ); - assert_eq_error_rate!(Balances::total_balance(&101), init_balance_101, 2); - - assert_eq_uvec!(Session::validators(), vec![11, 21]); - >::reward_by_ids(vec![(11, 1)]); - - // Compute total payout now for whole duration as other parameter won't change - let total_payout_1 = current_total_payout_for_duration(reward_time_per_era()); - - mock::start_active_era(2); - assert_eq!( - mock::REWARD_REMAINDER_UNBALANCED.with(|v| *v.borrow()), - maximum_payout * 2 - total_payout_0 - total_payout_1, - ); - assert_eq!( - *mock::staking_events().last().unwrap(), - Event::EraPayout(1, total_payout_1, maximum_payout - total_payout_1) - ); - mock::make_all_reward_payment(1); - - assert_eq_error_rate!( - Balances::total_balance(&10), - init_balance_10 + part_for_10 * (total_payout_0 * 2 / 3 + total_payout_1), - 2, - ); - assert_eq_error_rate!(Balances::total_balance(&11), init_balance_11, 2); - assert_eq_error_rate!( - Balances::total_balance(&20), - init_balance_20 + part_for_20 * total_payout_0 * 1 / 3, - 2, - ); - assert_eq_error_rate!(Balances::total_balance(&21), init_balance_21, 2); - assert_eq_error_rate!( - Balances::total_balance(&100), - init_balance_100 + - part_for_100_from_10 * (total_payout_0 * 2 / 3 + total_payout_1) + - part_for_100_from_20 * total_payout_0 * 1 / 3, - 2 - ); - assert_eq_error_rate!(Balances::total_balance(&101), init_balance_101, 2); - }); -} - -#[test] -fn staking_should_work() { - ExtBuilder::default() - .nominate(false) - .fair(false) // to give 20 more staked value - .build_and_execute(|| { - // remember + compare this along with the test. - assert_eq_uvec!(validator_controllers(), vec![20, 10]); - - // put some money in account that we'll use. - for i in 1..5 { - let _ = Balances::make_free_balance_be(&i, 2000); - } - - // --- Block 2: - start_session(2); - // add a new candidate for being a validator. account 3 controlled by 4. - assert_ok!(Staking::bond(Origin::signed(3), 4, 1500, RewardDestination::Controller)); - assert_ok!(Staking::validate(Origin::signed(4), ValidatorPrefs::default())); - - // No effects will be seen so far. - assert_eq_uvec!(validator_controllers(), vec![20, 10]); - - // --- Block 3: - start_session(3); - - // No effects will be seen so far. Era has not been yet triggered. - assert_eq_uvec!(validator_controllers(), vec![20, 10]); - - // --- Block 4: the validators will now be queued. - start_session(4); - assert_eq!(Staking::active_era().unwrap().index, 1); - - // --- Block 5: the validators are still in queue. - start_session(5); - - // --- Block 6: the validators will now be changed. - start_session(6); - - assert_eq_uvec!(validator_controllers(), vec![20, 4]); - // --- Block 6: Unstake 4 as a validator, freeing up the balance stashed in 3 - // 4 will chill - Staking::chill(Origin::signed(4)).unwrap(); - - // --- Block 7: nothing. 4 is still there. - start_session(7); - assert_eq_uvec!(validator_controllers(), vec![20, 4]); - - // --- Block 8: - start_session(8); - - // --- Block 9: 4 will not be a validator. - start_session(9); - assert_eq_uvec!(validator_controllers(), vec![20, 10]); - - // Note: the stashed value of 4 is still lock - assert_eq!( - Staking::ledger(&4), - Some(StakingLedger { - stash: 3, - total: 1500, - active: 1500, - unlocking: vec![], - claimed_rewards: vec![0], - }) - ); - // e.g. it cannot reserve more than 500 that it has free from the total 2000 - assert_noop!( - Balances::reserve(&3, 501), - BalancesError::::LiquidityRestrictions - ); - assert_ok!(Balances::reserve(&3, 409)); - }); -} - -#[test] -fn blocking_and_kicking_works() { - ExtBuilder::default() - .minimum_validator_count(1) - .validator_count(4) - .nominate(true) - .num_validators(3) - .build_and_execute(|| { - // block validator 10/11 - assert_ok!(Staking::validate( - Origin::signed(10), - ValidatorPrefs { blocked: true, ..Default::default() } - )); - // attempt to nominate from 100/101... - assert_ok!(Staking::nominate(Origin::signed(100), vec![11])); - // should have worked since we're already nominated them - assert_eq!(Nominators::::get(&101).unwrap().targets, vec![11]); - // kick the nominator - assert_ok!(Staking::kick(Origin::signed(10), vec![101])); - // should have been kicked now - assert!(Nominators::::get(&101).unwrap().targets.is_empty()); - // attempt to nominate from 100/101... - assert_noop!( - Staking::nominate(Origin::signed(100), vec![11]), - Error::::BadTarget - ); - }); -} - -#[test] -fn less_than_needed_candidates_works() { - ExtBuilder::default() - .minimum_validator_count(1) - .validator_count(4) - .nominate(false) - .num_validators(3) - .build_and_execute(|| { - assert_eq!(Staking::validator_count(), 4); - assert_eq!(Staking::minimum_validator_count(), 1); - assert_eq_uvec!(validator_controllers(), vec![30, 20, 10]); - - mock::start_active_era(1); - - // Previous set is selected. NO election algorithm is even executed. - assert_eq_uvec!(validator_controllers(), vec![30, 20, 10]); - - // But the exposure is updated in a simple way. No external votes exists. - // This is purely self-vote. - assert!(ErasStakers::::iter_prefix_values(Staking::active_era().unwrap().index) - .all(|exposure| exposure.others.is_empty())); - }); -} - -#[test] -fn no_candidate_emergency_condition() { - ExtBuilder::default() - .minimum_validator_count(1) - .validator_count(15) - .num_validators(4) - .validator_pool(true) - .nominate(false) - .build_and_execute(|| { - // initial validators - assert_eq_uvec!(validator_controllers(), vec![10, 20, 30, 40]); - let prefs = ValidatorPrefs { commission: Perbill::one(), ..Default::default() }; - ::Validators::insert(11, prefs.clone()); - - // set the minimum validator count. - ::MinimumValidatorCount::put(10); - - // try to chill - let res = Staking::chill(Origin::signed(10)); - assert_ok!(res); - - let current_era = CurrentEra::::get(); - - // try trigger new era - mock::run_to_block(20); - assert_eq!(*staking_events().last().unwrap(), Event::StakingElectionFailed); - // No new era is created - assert_eq!(current_era, CurrentEra::::get()); - - // Go to far further session to see if validator have changed - mock::run_to_block(100); - - // Previous ones are elected. chill is not effective in active era (as era hasn't changed) - assert_eq_uvec!(validator_controllers(), vec![10, 20, 30, 40]); - // The chill is still pending. - assert!(!::Validators::contains_key(11)); - // No new era is created. - assert_eq!(current_era, CurrentEra::::get()); - }); -} - -#[test] -fn nominating_and_rewards_should_work() { - ExtBuilder::default() - .nominate(false) - .validator_pool(true) - .build_and_execute(|| { - // initial validators -- everyone is actually even. - assert_eq_uvec!(validator_controllers(), vec![40, 30]); - - // Set payee to controller - assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); - assert_ok!(Staking::set_payee(Origin::signed(20), RewardDestination::Controller)); - assert_ok!(Staking::set_payee(Origin::signed(30), RewardDestination::Controller)); - assert_ok!(Staking::set_payee(Origin::signed(40), RewardDestination::Controller)); - - // give the man some money - let initial_balance = 1000; - for i in [1, 2, 3, 4, 5, 10, 11, 20, 21].iter() { - let _ = Balances::make_free_balance_be(i, initial_balance); - } - - // bond two account pairs and state interest in nomination. - // 2 will nominate for 10, 20, 30 - assert_ok!(Staking::bond(Origin::signed(1), 2, 1000, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(2), vec![11, 21, 31])); - // 4 will nominate for 10, 20, 40 - assert_ok!(Staking::bond(Origin::signed(3), 4, 1000, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(4), vec![11, 21, 41])); - - // the total reward for era 0 - let total_payout_0 = current_total_payout_for_duration(reward_time_per_era()); - >::reward_by_ids(vec![(41, 1)]); - >::reward_by_ids(vec![(31, 1)]); - - mock::start_active_era(1); - - // 10 and 20 have more votes, they will be chosen. - assert_eq_uvec!(validator_controllers(), vec![20, 10]); - - // OLD validators must have already received some rewards. - mock::make_all_reward_payment(0); - assert_eq!(Balances::total_balance(&40), 1 + total_payout_0 / 2); - assert_eq!(Balances::total_balance(&30), 1 + total_payout_0 / 2); - - // ------ check the staked value of all parties. - - // 30 and 40 are not chosen anymore - assert_eq!( - ErasStakers::::iter_prefix_values(Staking::active_era().unwrap().index) - .count(), - 2 - ); - assert_eq!( - Staking::eras_stakers(Staking::active_era().unwrap().index, 11), - Exposure { - total: 1000 + 800, - own: 1000, - others: vec![ - IndividualExposure { who: 3, value: 400 }, - IndividualExposure { who: 1, value: 400 }, - ] - }, - ); - assert_eq!( - Staking::eras_stakers(Staking::active_era().unwrap().index, 21), - Exposure { - total: 1000 + 1200, - own: 1000, - others: vec![ - IndividualExposure { who: 3, value: 600 }, - IndividualExposure { who: 1, value: 600 }, - ] - }, - ); - - // the total reward for era 1 - let total_payout_1 = current_total_payout_for_duration(reward_time_per_era()); - >::reward_by_ids(vec![(21, 2)]); - >::reward_by_ids(vec![(11, 1)]); - - mock::start_active_era(2); - - // nothing else will happen, era ends and rewards are paid again, - // it is expected that nominators will also be paid. See below - - mock::make_all_reward_payment(1); - let payout_for_10 = total_payout_1 / 3; - let payout_for_20 = 2 * total_payout_1 / 3; - // Nominator 2: has [400/1800 ~ 2/9 from 10] + [600/2200 ~ 3/11 from 20]'s reward. ==> 2/9 + 3/11 - assert_eq_error_rate!( - Balances::total_balance(&2), - initial_balance + (2 * payout_for_10 / 9 + 3 * payout_for_20 / 11), - 2, - ); - // Nominator 4: has [400/1800 ~ 2/9 from 10] + [600/2200 ~ 3/11 from 20]'s reward. ==> 2/9 + 3/11 - assert_eq_error_rate!( - Balances::total_balance(&4), - initial_balance + (2 * payout_for_10 / 9 + 3 * payout_for_20 / 11), - 2, - ); - - // Validator 10: got 800 / 1800 external stake => 8/18 =? 4/9 => Validator's share = 5/9 - assert_eq_error_rate!( - Balances::total_balance(&10), - initial_balance + 5 * payout_for_10 / 9, - 2, - ); - // Validator 20: got 1200 / 2200 external stake => 12/22 =? 6/11 => Validator's share = 5/11 - assert_eq_error_rate!( - Balances::total_balance(&20), - initial_balance + 5 * payout_for_20 / 11, - 2, - ); - }); -} - -#[test] -fn nominators_also_get_slashed_pro_rata() { - ExtBuilder::default().build_and_execute(|| { - mock::start_active_era(1); - let slash_percent = Perbill::from_percent(5); - let initial_exposure = Staking::eras_stakers(active_era(), 11); - // 101 is a nominator for 11 - assert_eq!(initial_exposure.others.first().unwrap().who, 101); - - // staked values; - let nominator_stake = Staking::ledger(100).unwrap().active; - let nominator_balance = balances(&101).0; - let validator_stake = Staking::ledger(10).unwrap().active; - let validator_balance = balances(&11).0; - let exposed_stake = initial_exposure.total; - let exposed_validator = initial_exposure.own; - let exposed_nominator = initial_exposure.others.first().unwrap().value; - - // 11 goes offline - on_offence_now( - &[OffenceDetails { offender: (11, initial_exposure.clone()), reporters: vec![] }], - &[slash_percent], - ); - - // both stakes must have been decreased. - assert!(Staking::ledger(100).unwrap().active < nominator_stake); - assert!(Staking::ledger(10).unwrap().active < validator_stake); - - let slash_amount = slash_percent * exposed_stake; - let validator_share = - Perbill::from_rational(exposed_validator, exposed_stake) * slash_amount; - let nominator_share = - Perbill::from_rational(exposed_nominator, exposed_stake) * slash_amount; - - // both slash amounts need to be positive for the test to make sense. - assert!(validator_share > 0); - assert!(nominator_share > 0); - - // both stakes must have been decreased pro-rata. - assert_eq!(Staking::ledger(100).unwrap().active, nominator_stake - nominator_share); - assert_eq!(Staking::ledger(10).unwrap().active, validator_stake - validator_share); - assert_eq!( - balances(&101).0, // free balance - nominator_balance - nominator_share, - ); - assert_eq!( - balances(&11).0, // free balance - validator_balance - validator_share, - ); - // Because slashing happened. - assert!(is_disabled(10)); - }); -} - -#[test] -fn double_staking_should_fail() { - // should test (in the same order): - // * an account already bonded as stash cannot be be stashed again. - // * an account already bonded as stash cannot nominate. - // * an account already bonded as controller can nominate. - ExtBuilder::default().build_and_execute(|| { - let arbitrary_value = 5; - // 2 = controller, 1 stashed => ok - assert_ok!(Staking::bond( - Origin::signed(1), - 2, - arbitrary_value, - RewardDestination::default() - )); - // 4 = not used so far, 1 stashed => not allowed. - assert_noop!( - Staking::bond(Origin::signed(1), 4, arbitrary_value, RewardDestination::default()), - Error::::AlreadyBonded, - ); - // 1 = stashed => attempting to nominate should fail. - assert_noop!(Staking::nominate(Origin::signed(1), vec![1]), Error::::NotController); - // 2 = controller => nominating should work. - assert_ok!(Staking::nominate(Origin::signed(2), vec![1])); - }); -} - -#[test] -fn double_controlling_should_fail() { - // should test (in the same order): - // * an account already bonded as controller CANNOT be reused as the controller of another account. - ExtBuilder::default().build_and_execute(|| { - let arbitrary_value = 5; - // 2 = controller, 1 stashed => ok - assert_ok!(Staking::bond( - Origin::signed(1), - 2, - arbitrary_value, - RewardDestination::default(), - )); - // 2 = controller, 3 stashed (Note that 2 is reused.) => no-op - assert_noop!( - Staking::bond(Origin::signed(3), 2, arbitrary_value, RewardDestination::default()), - Error::::AlreadyPaired, - ); - }); -} - -#[test] -fn session_and_eras_work_simple() { - ExtBuilder::default().period(1).build_and_execute(|| { - assert_eq!(active_era(), 0); - assert_eq!(current_era(), 0); - assert_eq!(Session::current_index(), 1); - assert_eq!(System::block_number(), 1); - - // Session 1: this is basically a noop. This has already been started. - start_session(1); - assert_eq!(Session::current_index(), 1); - assert_eq!(active_era(), 0); - assert_eq!(System::block_number(), 1); - - // Session 2: No change. - start_session(2); - assert_eq!(Session::current_index(), 2); - assert_eq!(active_era(), 0); - assert_eq!(System::block_number(), 2); - - // Session 3: Era increment. - start_session(3); - assert_eq!(Session::current_index(), 3); - assert_eq!(active_era(), 1); - assert_eq!(System::block_number(), 3); - - // Session 4: No change. - start_session(4); - assert_eq!(Session::current_index(), 4); - assert_eq!(active_era(), 1); - assert_eq!(System::block_number(), 4); - - // Session 5: No change. - start_session(5); - assert_eq!(Session::current_index(), 5); - assert_eq!(active_era(), 1); - assert_eq!(System::block_number(), 5); - - // Session 6: Era increment. - start_session(6); - assert_eq!(Session::current_index(), 6); - assert_eq!(active_era(), 2); - assert_eq!(System::block_number(), 6); - }); -} - -#[test] -fn session_and_eras_work_complex() { - ExtBuilder::default().period(5).build_and_execute(|| { - assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 0); - assert_eq!(System::block_number(), 1); - - start_session(1); - assert_eq!(Session::current_index(), 1); - assert_eq!(active_era(), 0); - assert_eq!(System::block_number(), 5); - - start_session(2); - assert_eq!(Session::current_index(), 2); - assert_eq!(active_era(), 0); - assert_eq!(System::block_number(), 10); - - start_session(3); - assert_eq!(Session::current_index(), 3); - assert_eq!(active_era(), 1); - assert_eq!(System::block_number(), 15); - - start_session(4); - assert_eq!(Session::current_index(), 4); - assert_eq!(active_era(), 1); - assert_eq!(System::block_number(), 20); - - start_session(5); - assert_eq!(Session::current_index(), 5); - assert_eq!(active_era(), 1); - assert_eq!(System::block_number(), 25); - - start_session(6); - assert_eq!(Session::current_index(), 6); - assert_eq!(active_era(), 2); - assert_eq!(System::block_number(), 30); - }); -} - -#[test] -fn forcing_new_era_works() { - ExtBuilder::default().build_and_execute(|| { - // normal flow of session. - start_session(1); - assert_eq!(active_era(), 0); - - start_session(2); - assert_eq!(active_era(), 0); - - start_session(3); - assert_eq!(active_era(), 1); - - // no era change. - ForceEra::::put(Forcing::ForceNone); - - start_session(4); - assert_eq!(active_era(), 1); - - start_session(5); - assert_eq!(active_era(), 1); - - start_session(6); - assert_eq!(active_era(), 1); - - start_session(7); - assert_eq!(active_era(), 1); - - // back to normal. - // this immediately starts a new session. - ForceEra::::put(Forcing::NotForcing); - - start_session(8); - assert_eq!(active_era(), 1); - - start_session(9); - assert_eq!(active_era(), 2); - // forceful change - ForceEra::::put(Forcing::ForceAlways); - - start_session(10); - assert_eq!(active_era(), 2); - - start_session(11); - assert_eq!(active_era(), 3); - - start_session(12); - assert_eq!(active_era(), 4); - - // just one forceful change - ForceEra::::put(Forcing::ForceNew); - start_session(13); - assert_eq!(active_era(), 5); - assert_eq!(ForceEra::::get(), Forcing::NotForcing); - - start_session(14); - assert_eq!(active_era(), 6); - - start_session(15); - assert_eq!(active_era(), 6); - }); -} - -#[test] -fn cannot_transfer_staked_balance() { - // Tests that a stash account cannot transfer funds - ExtBuilder::default().nominate(false).build_and_execute(|| { - // Confirm account 11 is stashed - assert_eq!(Staking::bonded(&11), Some(10)); - // Confirm account 11 has some free balance - assert_eq!(Balances::free_balance(11), 1000); - // Confirm account 11 (via controller 10) is totally staked - assert_eq!(Staking::eras_stakers(active_era(), 11).total, 1000); - // Confirm account 11 cannot transfer as a result - assert_noop!( - Balances::transfer(Origin::signed(11), 20, 1), - BalancesError::::LiquidityRestrictions - ); - - // Give account 11 extra free balance - let _ = Balances::make_free_balance_be(&11, 10000); - // Confirm that account 11 can now transfer some balance - assert_ok!(Balances::transfer(Origin::signed(11), 20, 1)); - }); -} - -#[test] -fn cannot_transfer_staked_balance_2() { - // Tests that a stash account cannot transfer funds - // Same test as above but with 20, and more accurate. - // 21 has 2000 free balance but 1000 at stake - ExtBuilder::default().nominate(false).fair(true).build_and_execute(|| { - // Confirm account 21 is stashed - assert_eq!(Staking::bonded(&21), Some(20)); - // Confirm account 21 has some free balance - assert_eq!(Balances::free_balance(21), 2000); - // Confirm account 21 (via controller 20) is totally staked - assert_eq!(Staking::eras_stakers(Staking::active_era().unwrap().index, 21).total, 1000); - // Confirm account 21 can transfer at most 1000 - assert_noop!( - Balances::transfer(Origin::signed(21), 20, 1001), - BalancesError::::LiquidityRestrictions - ); - assert_ok!(Balances::transfer(Origin::signed(21), 20, 1000)); - }); -} - -#[test] -fn cannot_reserve_staked_balance() { - // Checks that a bonded account cannot reserve balance from free balance - ExtBuilder::default().build_and_execute(|| { - // Confirm account 11 is stashed - assert_eq!(Staking::bonded(&11), Some(10)); - // Confirm account 11 has some free balance - assert_eq!(Balances::free_balance(11), 1000); - // Confirm account 11 (via controller 10) is totally staked - assert_eq!(Staking::eras_stakers(Staking::active_era().unwrap().index, 11).own, 1000); - // Confirm account 11 cannot reserve as a result - assert_noop!(Balances::reserve(&11, 1), BalancesError::::LiquidityRestrictions); - - // Give account 11 extra free balance - let _ = Balances::make_free_balance_be(&11, 10000); - // Confirm account 11 can now reserve balance - assert_ok!(Balances::reserve(&11, 1)); - }); -} - -#[test] -fn reward_destination_works() { - // Rewards go to the correct destination as determined in Payee - ExtBuilder::default().nominate(false).build_and_execute(|| { - // Check that account 11 is a validator - assert!(Session::validators().contains(&11)); - // Check the balance of the validator account - assert_eq!(Balances::free_balance(10), 1); - // Check the balance of the stash account - assert_eq!(Balances::free_balance(11), 1000); - // Check how much is at stake - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![], - }) - ); - - // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(reward_time_per_era()); - >::reward_by_ids(vec![(11, 1)]); - - mock::start_active_era(1); - mock::make_all_reward_payment(0); - - // Check that RewardDestination is Staked (default) - assert_eq!(Staking::payee(&11), RewardDestination::Staked); - // Check that reward went to the stash account of validator - assert_eq!(Balances::free_balance(11), 1000 + total_payout_0); - // Check that amount at stake increased accordingly - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000 + total_payout_0, - active: 1000 + total_payout_0, - unlocking: vec![], - claimed_rewards: vec![0], - }) - ); - - // Change RewardDestination to Stash - >::insert(&11, RewardDestination::Stash); - - // Compute total payout now for whole duration as other parameter won't change - let total_payout_1 = current_total_payout_for_duration(reward_time_per_era()); - >::reward_by_ids(vec![(11, 1)]); - - mock::start_active_era(2); - mock::make_all_reward_payment(1); - - // Check that RewardDestination is Stash - assert_eq!(Staking::payee(&11), RewardDestination::Stash); - // Check that reward went to the stash account - assert_eq!(Balances::free_balance(11), 1000 + total_payout_0 + total_payout_1); - // Record this value - let recorded_stash_balance = 1000 + total_payout_0 + total_payout_1; - // Check that amount at stake is NOT increased - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000 + total_payout_0, - active: 1000 + total_payout_0, - unlocking: vec![], - claimed_rewards: vec![0, 1], - }) - ); - - // Change RewardDestination to Controller - >::insert(&11, RewardDestination::Controller); - - // Check controller balance - assert_eq!(Balances::free_balance(10), 1); - - // Compute total payout now for whole duration as other parameter won't change - let total_payout_2 = current_total_payout_for_duration(reward_time_per_era()); - >::reward_by_ids(vec![(11, 1)]); - - mock::start_active_era(3); - mock::make_all_reward_payment(2); - - // Check that RewardDestination is Controller - assert_eq!(Staking::payee(&11), RewardDestination::Controller); - // Check that reward went to the controller account - assert_eq!(Balances::free_balance(10), 1 + total_payout_2); - // Check that amount at stake is NOT increased - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000 + total_payout_0, - active: 1000 + total_payout_0, - unlocking: vec![], - claimed_rewards: vec![0, 1, 2], - }) - ); - // Check that amount in staked account is NOT increased. - assert_eq!(Balances::free_balance(11), recorded_stash_balance); - }); -} - -#[test] -fn validator_payment_prefs_work() { - // Test that validator preferences are correctly honored - // Note: unstake threshold is being directly tested in slashing tests. - // This test will focus on validator payment. - ExtBuilder::default().build_and_execute(|| { - let commission = Perbill::from_percent(40); - >::insert( - &11, - ValidatorPrefs { commission: commission.clone(), ..Default::default() }, - ); - - // Reward controller so staked ratio doesn't change. - >::insert(&11, RewardDestination::Controller); - >::insert(&101, RewardDestination::Controller); - - mock::start_active_era(1); - mock::make_all_reward_payment(0); - - let balance_era_1_10 = Balances::total_balance(&10); - let balance_era_1_100 = Balances::total_balance(&100); - - // Compute total payout now for whole duration as other parameter won't change - let total_payout_1 = current_total_payout_for_duration(reward_time_per_era()); - let exposure_1 = Staking::eras_stakers(Staking::active_era().unwrap().index, 11); - >::reward_by_ids(vec![(11, 1)]); - - mock::start_active_era(2); - mock::make_all_reward_payment(1); - - let taken_cut = commission * total_payout_1; - let shared_cut = total_payout_1 - taken_cut; - let reward_of_10 = shared_cut * exposure_1.own / exposure_1.total + taken_cut; - let reward_of_100 = shared_cut * exposure_1.others[0].value / exposure_1.total; - assert_eq_error_rate!(Balances::total_balance(&10), balance_era_1_10 + reward_of_10, 2); - assert_eq_error_rate!(Balances::total_balance(&100), balance_era_1_100 + reward_of_100, 2); - }); -} - -#[test] -fn bond_extra_works() { - // Tests that extra `free_balance` in the stash can be added to stake - // NOTE: this tests only verifies `StakingLedger` for correct updates - // See `bond_extra_and_withdraw_unbonded_works` for more details and updates on `Exposure`. - ExtBuilder::default().build_and_execute(|| { - // Check that account 10 is a validator - assert!(>::contains_key(11)); - // Check that account 10 is bonded to account 11 - assert_eq!(Staking::bonded(&11), Some(10)); - // Check how much is at stake - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![], - }) - ); - - // Give account 11 some large free balance greater than total - let _ = Balances::make_free_balance_be(&11, 1000000); - - // Call the bond_extra function from controller, add only 100 - assert_ok!(Staking::bond_extra(Origin::signed(11), 100)); - // There should be 100 more `total` and `active` in the ledger - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000 + 100, - active: 1000 + 100, - unlocking: vec![], - claimed_rewards: vec![], - }) - ); - - // Call the bond_extra function with a large number, should handle it - assert_ok!(Staking::bond_extra(Origin::signed(11), Balance::max_value())); - // The full amount of the funds should now be in the total and active - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000000, - active: 1000000, - unlocking: vec![], - claimed_rewards: vec![], - }) - ); - }); -} - -#[test] -fn bond_extra_and_withdraw_unbonded_works() { - // * Should test - // * Given an account being bonded [and chosen as a validator](not mandatory) - // * It can add extra funds to the bonded account. - // * it can unbond a portion of its funds from the stash account. - // * Once the unbonding period is done, it can actually take the funds out of the stash. - ExtBuilder::default().nominate(false).build_and_execute(|| { - // Set payee to controller. avoids confusion - assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); - - // Give account 11 some large free balance greater than total - let _ = Balances::make_free_balance_be(&11, 1000000); - - // Initial config should be correct - assert_eq!(Staking::active_era().unwrap().index, 0); - - // check the balance of a validator accounts. - assert_eq!(Balances::total_balance(&10), 1); - - // confirm that 10 is a normal validator and gets paid at the end of the era. - mock::start_active_era(1); - - // Initial state of 10 - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![], - }) - ); - assert_eq!( - Staking::eras_stakers(Staking::active_era().unwrap().index, 11), - Exposure { total: 1000, own: 1000, others: vec![] } - ); - - // deposit the extra 100 units - Staking::bond_extra(Origin::signed(11), 100).unwrap(); - - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000 + 100, - active: 1000 + 100, - unlocking: vec![], - claimed_rewards: vec![], - }) - ); - // Exposure is a snapshot! only updated after the next era update. - assert_ne!( - Staking::eras_stakers(Staking::active_era().unwrap().index, 11), - Exposure { total: 1000 + 100, own: 1000 + 100, others: vec![] } - ); - - // trigger next era. - mock::start_active_era(2); - assert_eq!(Staking::active_era().unwrap().index, 2); - - // ledger should be the same. - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000 + 100, - active: 1000 + 100, - unlocking: vec![], - claimed_rewards: vec![], - }) - ); - // Exposure is now updated. - assert_eq!( - Staking::eras_stakers(Staking::active_era().unwrap().index, 11), - Exposure { total: 1000 + 100, own: 1000 + 100, others: vec![] } - ); - - // Unbond almost all of the funds in stash. - Staking::unbond(Origin::signed(10), 1000).unwrap(); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000 + 100, - active: 100, - unlocking: vec![UnlockChunk { value: 1000, era: 2 + 3 }], - claimed_rewards: vec![] - }), - ); - - // Attempting to free the balances now will fail. 2 eras need to pass. - assert_ok!(Staking::withdraw_unbonded(Origin::signed(10), 0)); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000 + 100, - active: 100, - unlocking: vec![UnlockChunk { value: 1000, era: 2 + 3 }], - claimed_rewards: vec![] - }), - ); - - // trigger next era. - mock::start_active_era(3); - - // nothing yet - assert_ok!(Staking::withdraw_unbonded(Origin::signed(10), 0)); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000 + 100, - active: 100, - unlocking: vec![UnlockChunk { value: 1000, era: 2 + 3 }], - claimed_rewards: vec![] - }), - ); - - // trigger next era. - mock::start_active_era(5); - - assert_ok!(Staking::withdraw_unbonded(Origin::signed(10), 0)); - // Now the value is free and the staking ledger is updated. - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 100, - active: 100, - unlocking: vec![], - claimed_rewards: vec![] - }), - ); - }) -} - -#[test] -fn too_many_unbond_calls_should_not_work() { - ExtBuilder::default().build_and_execute(|| { - // locked at era 0 until 3 - for _ in 0..MAX_UNLOCKING_CHUNKS - 1 { - assert_ok!(Staking::unbond(Origin::signed(10), 1)); - } - - mock::start_active_era(1); - - // locked at era 1 until 4 - assert_ok!(Staking::unbond(Origin::signed(10), 1)); - // can't do more. - assert_noop!(Staking::unbond(Origin::signed(10), 1), Error::::NoMoreChunks); - - mock::start_active_era(3); - - assert_noop!(Staking::unbond(Origin::signed(10), 1), Error::::NoMoreChunks); - // free up. - assert_ok!(Staking::withdraw_unbonded(Origin::signed(10), 0)); - - // Can add again. - assert_ok!(Staking::unbond(Origin::signed(10), 1)); - assert_eq!(Staking::ledger(&10).unwrap().unlocking.len(), 2); - }) -} - -#[test] -fn rebond_works() { - // * Should test - // * Given an account being bonded [and chosen as a validator](not mandatory) - // * it can unbond a portion of its funds from the stash account. - // * it can re-bond a portion of the funds scheduled to unlock. - ExtBuilder::default().nominate(false).build_and_execute(|| { - // Set payee to controller. avoids confusion - assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); - - // Give account 11 some large free balance greater than total - let _ = Balances::make_free_balance_be(&11, 1000000); - - // confirm that 10 is a normal validator and gets paid at the end of the era. - mock::start_active_era(1); - - // Initial state of 10 - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![], - }) - ); - - mock::start_active_era(2); - assert_eq!(Staking::active_era().unwrap().index, 2); - - // Try to rebond some funds. We get an error since no fund is unbonded. - assert_noop!(Staking::rebond(Origin::signed(10), 500), Error::::NoUnlockChunk); - - // Unbond almost all of the funds in stash. - Staking::unbond(Origin::signed(10), 900).unwrap(); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 100, - unlocking: vec![UnlockChunk { value: 900, era: 2 + 3 }], - claimed_rewards: vec![], - }) - ); - - // Re-bond all the funds unbonded. - Staking::rebond(Origin::signed(10), 900).unwrap(); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![], - }) - ); - - // Unbond almost all of the funds in stash. - Staking::unbond(Origin::signed(10), 900).unwrap(); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 100, - unlocking: vec![UnlockChunk { value: 900, era: 5 }], - claimed_rewards: vec![], - }) - ); - - // Re-bond part of the funds unbonded. - Staking::rebond(Origin::signed(10), 500).unwrap(); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 600, - unlocking: vec![UnlockChunk { value: 400, era: 5 }], - claimed_rewards: vec![], - }) - ); - - // Re-bond the remainder of the funds unbonded. - Staking::rebond(Origin::signed(10), 500).unwrap(); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![], - }) - ); - - // Unbond parts of the funds in stash. - Staking::unbond(Origin::signed(10), 300).unwrap(); - Staking::unbond(Origin::signed(10), 300).unwrap(); - Staking::unbond(Origin::signed(10), 300).unwrap(); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 100, - unlocking: vec![ - UnlockChunk { value: 300, era: 5 }, - UnlockChunk { value: 300, era: 5 }, - UnlockChunk { value: 300, era: 5 }, - ], - claimed_rewards: vec![], - }) - ); - - // Re-bond part of the funds unbonded. - Staking::rebond(Origin::signed(10), 500).unwrap(); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 600, - unlocking: vec![ - UnlockChunk { value: 300, era: 5 }, - UnlockChunk { value: 100, era: 5 }, - ], - claimed_rewards: vec![], - }) - ); - }) -} - -#[test] -fn rebond_is_fifo() { - // Rebond should proceed by reversing the most recent bond operations. - ExtBuilder::default().nominate(false).build_and_execute(|| { - // Set payee to controller. avoids confusion - assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); - - // Give account 11 some large free balance greater than total - let _ = Balances::make_free_balance_be(&11, 1000000); - - // confirm that 10 is a normal validator and gets paid at the end of the era. - mock::start_active_era(1); - - // Initial state of 10 - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![], - }) - ); - - mock::start_active_era(2); - - // Unbond some of the funds in stash. - Staking::unbond(Origin::signed(10), 400).unwrap(); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 600, - unlocking: vec![UnlockChunk { value: 400, era: 2 + 3 },], - claimed_rewards: vec![], - }) - ); - - mock::start_active_era(3); - - // Unbond more of the funds in stash. - Staking::unbond(Origin::signed(10), 300).unwrap(); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 300, - unlocking: vec![ - UnlockChunk { value: 400, era: 2 + 3 }, - UnlockChunk { value: 300, era: 3 + 3 }, - ], - claimed_rewards: vec![], - }) - ); - - mock::start_active_era(4); - - // Unbond yet more of the funds in stash. - Staking::unbond(Origin::signed(10), 200).unwrap(); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 100, - unlocking: vec![ - UnlockChunk { value: 400, era: 2 + 3 }, - UnlockChunk { value: 300, era: 3 + 3 }, - UnlockChunk { value: 200, era: 4 + 3 }, - ], - claimed_rewards: vec![], - }) - ); - - // Re-bond half of the unbonding funds. - Staking::rebond(Origin::signed(10), 400).unwrap(); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 500, - unlocking: vec![ - UnlockChunk { value: 400, era: 2 + 3 }, - UnlockChunk { value: 100, era: 3 + 3 }, - ], - claimed_rewards: vec![], - }) - ); - }) -} - -#[test] -fn reward_to_stake_works() { - ExtBuilder::default().nominate(false).fair(false).build_and_execute(|| { - // Confirm validator count is 2 - assert_eq!(Staking::validator_count(), 2); - // Confirm account 10 and 20 are validators - assert!(>::contains_key(&11) && >::contains_key(&21)); - - assert_eq!(Staking::eras_stakers(Staking::active_era().unwrap().index, 11).total, 1000); - assert_eq!(Staking::eras_stakers(Staking::active_era().unwrap().index, 21).total, 2000); - - // Give the man some money. - let _ = Balances::make_free_balance_be(&10, 1000); - let _ = Balances::make_free_balance_be(&20, 1000); - - // Bypass logic and change current exposure - ErasStakers::::insert(0, 21, Exposure { total: 69, own: 69, others: vec![] }); - - // Now lets lower account 20 stake - assert_eq!(Staking::eras_stakers(Staking::active_era().unwrap().index, 21).total, 69); - >::insert( - &20, - StakingLedger { - stash: 21, - total: 69, - active: 69, - unlocking: vec![], - claimed_rewards: vec![], - }, - ); - - // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(reward_time_per_era()); - >::reward_by_ids(vec![(11, 1)]); - >::reward_by_ids(vec![(21, 1)]); - - // New era --> rewards are paid --> stakes are changed - mock::start_active_era(1); - mock::make_all_reward_payment(0); - - assert_eq!(Staking::eras_stakers(Staking::active_era().unwrap().index, 11).total, 1000); - assert_eq!(Staking::eras_stakers(Staking::active_era().unwrap().index, 21).total, 69); - - let _11_balance = Balances::free_balance(&11); - assert_eq!(_11_balance, 1000 + total_payout_0 / 2); - - // Trigger another new era as the info are frozen before the era start. - mock::start_active_era(2); - - // -- new infos - assert_eq!( - Staking::eras_stakers(Staking::active_era().unwrap().index, 11).total, - 1000 + total_payout_0 / 2 - ); - assert_eq!( - Staking::eras_stakers(Staking::active_era().unwrap().index, 21).total, - 69 + total_payout_0 / 2 - ); - }); -} - -#[test] -fn on_free_balance_zero_stash_removes_validator() { - // Tests that validator storage items are cleaned up when stash is empty - // Tests that storage items are untouched when controller is empty - ExtBuilder::default() - .existential_deposit(10) - .min_nominator_bond(10) - .min_validator_bond(10) - .build_and_execute(|| { - // Check the balance of the validator account - assert_eq!(Balances::free_balance(10), 256); - // Check the balance of the stash account - assert_eq!(Balances::free_balance(11), 256000); - // Check these two accounts are bonded - assert_eq!(Staking::bonded(&11), Some(10)); - - // Set some storage items which we expect to be cleaned up - // Set payee information - assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Stash)); - - // Check storage items that should be cleaned up - assert!(>::contains_key(&10)); - assert!(>::contains_key(&11)); - assert!(>::contains_key(&11)); - assert!(>::contains_key(&11)); - - // Reduce free_balance of controller to 0 - let _ = Balances::slash(&10, Balance::max_value()); - - // Check the balance of the stash account has not been touched - assert_eq!(Balances::free_balance(11), 256000); - // Check these two accounts are still bonded - assert_eq!(Staking::bonded(&11), Some(10)); - - // Check storage items have not changed - assert!(>::contains_key(&10)); - assert!(>::contains_key(&11)); - assert!(>::contains_key(&11)); - assert!(>::contains_key(&11)); - - // Reduce free_balance of stash to 0 - let _ = Balances::slash(&11, Balance::max_value()); - // Check total balance of stash - assert_eq!(Balances::total_balance(&11), 10); - - // Reap the stash - assert_ok!(Staking::reap_stash(Origin::none(), 11, 0)); - - // Check storage items do not exist - assert!(!>::contains_key(&10)); - assert!(!>::contains_key(&11)); - assert!(!>::contains_key(&11)); - assert!(!>::contains_key(&11)); - assert!(!>::contains_key(&11)); - }); -} - -#[test] -fn on_free_balance_zero_stash_removes_nominator() { - // Tests that nominator storage items are cleaned up when stash is empty - // Tests that storage items are untouched when controller is empty - ExtBuilder::default() - .existential_deposit(10) - .min_nominator_bond(10) - .min_validator_bond(10) - .build_and_execute(|| { - // Make 10 a nominator - assert_ok!(Staking::nominate(Origin::signed(10), vec![20])); - // Check that account 10 is a nominator - assert!(>::contains_key(11)); - // Check the balance of the nominator account - assert_eq!(Balances::free_balance(10), 256); - // Check the balance of the stash account - assert_eq!(Balances::free_balance(11), 256000); - - // Set payee information - assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Stash)); - - // Check storage items that should be cleaned up - assert!(>::contains_key(&10)); - assert!(>::contains_key(&11)); - assert!(>::contains_key(&11)); - assert!(>::contains_key(&11)); - - // Reduce free_balance of controller to 0 - let _ = Balances::slash(&10, Balance::max_value()); - // Check total balance of account 10 - assert_eq!(Balances::total_balance(&10), 0); - - // Check the balance of the stash account has not been touched - assert_eq!(Balances::free_balance(11), 256000); - // Check these two accounts are still bonded - assert_eq!(Staking::bonded(&11), Some(10)); - - // Check storage items have not changed - assert!(>::contains_key(&10)); - assert!(>::contains_key(&11)); - assert!(>::contains_key(&11)); - assert!(>::contains_key(&11)); - - // Reduce free_balance of stash to 0 - let _ = Balances::slash(&11, Balance::max_value()); - // Check total balance of stash - assert_eq!(Balances::total_balance(&11), 10); - - // Reap the stash - assert_ok!(Staking::reap_stash(Origin::none(), 11, 0)); - - // Check storage items do not exist - assert!(!>::contains_key(&10)); - assert!(!>::contains_key(&11)); - assert!(!>::contains_key(&11)); - assert!(!>::contains_key(&11)); - assert!(!>::contains_key(&11)); - }); -} - -#[test] -fn switching_roles() { - // Test that it should be possible to switch between roles (nominator, validator, idle) with minimal overhead. - ExtBuilder::default().nominate(false).build_and_execute(|| { - // Reset reward destination - for i in &[10, 20] { - assert_ok!(Staking::set_payee(Origin::signed(*i), RewardDestination::Controller)); - } - - assert_eq_uvec!(validator_controllers(), vec![20, 10]); - - // put some money in account that we'll use. - for i in 1..7 { - let _ = Balances::deposit_creating(&i, 5000); - } - - // add 2 nominators - assert_ok!(Staking::bond(Origin::signed(1), 2, 2000, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(2), vec![11, 5])); - - assert_ok!(Staking::bond(Origin::signed(3), 4, 500, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(4), vec![21, 1])); - - // add a new validator candidate - assert_ok!(Staking::bond(Origin::signed(5), 6, 1000, RewardDestination::Controller)); - assert_ok!(Staking::validate(Origin::signed(6), ValidatorPrefs::default())); - - mock::start_active_era(1); - - // with current nominators 10 and 5 have the most stake - assert_eq_uvec!(validator_controllers(), vec![6, 10]); - - // 2 decides to be a validator. Consequences: - assert_ok!(Staking::validate(Origin::signed(2), ValidatorPrefs::default())); - // new stakes: - // 10: 1000 self vote - // 20: 1000 self vote + 250 vote - // 6 : 1000 self vote - // 2 : 2000 self vote + 250 vote. - // Winners: 20 and 2 - - mock::start_active_era(2); - - assert_eq_uvec!(validator_controllers(), vec![2, 20]); - }); -} - -#[test] -fn wrong_vote_is_null() { - ExtBuilder::default() - .nominate(false) - .validator_pool(true) - .build_and_execute(|| { - assert_eq_uvec!(validator_controllers(), vec![40, 30]); - - // put some money in account that we'll use. - for i in 1..3 { - let _ = Balances::deposit_creating(&i, 5000); - } - - // add 1 nominators - assert_ok!(Staking::bond(Origin::signed(1), 2, 2000, RewardDestination::default())); - assert_ok!(Staking::nominate( - Origin::signed(2), - vec![ - 11, 21, // good votes - 1, 2, 15, 1000, 25 // crap votes. No effect. - ] - )); - - // new block - mock::start_active_era(1); - - assert_eq_uvec!(validator_controllers(), vec![20, 10]); - }); -} - -#[test] -fn bond_with_no_staked_value() { - // Behavior when someone bonds with no staked value. - // Particularly when she votes and the candidate is elected. - ExtBuilder::default() - .validator_count(3) - .existential_deposit(5) - .min_nominator_bond(5) - .min_validator_bond(5) - .nominate(false) - .minimum_validator_count(1) - .build_and_execute(|| { - // Can't bond with 1 - assert_noop!( - Staking::bond(Origin::signed(1), 2, 1, RewardDestination::Controller), - Error::::InsufficientBond, - ); - // bonded with absolute minimum value possible. - assert_ok!(Staking::bond(Origin::signed(1), 2, 5, RewardDestination::Controller)); - assert_eq!(Balances::locks(&1)[0].amount, 5); - - // unbonding even 1 will cause all to be unbonded. - assert_ok!(Staking::unbond(Origin::signed(2), 1)); - assert_eq!( - Staking::ledger(2), - Some(StakingLedger { - stash: 1, - active: 0, - total: 5, - unlocking: vec![UnlockChunk { value: 5, era: 3 }], - claimed_rewards: vec![], - }) - ); - - mock::start_active_era(1); - mock::start_active_era(2); - - // not yet removed. - assert_ok!(Staking::withdraw_unbonded(Origin::signed(2), 0)); - assert!(Staking::ledger(2).is_some()); - assert_eq!(Balances::locks(&1)[0].amount, 5); - - mock::start_active_era(3); - - // poof. Account 1 is removed from the staking system. - assert_ok!(Staking::withdraw_unbonded(Origin::signed(2), 0)); - assert!(Staking::ledger(2).is_none()); - assert_eq!(Balances::locks(&1).len(), 0); - }); -} - -#[test] -fn bond_with_little_staked_value_bounded() { - ExtBuilder::default() - .validator_count(3) - .nominate(false) - .minimum_validator_count(1) - .build_and_execute(|| { - // setup - assert_ok!(Staking::chill(Origin::signed(30))); - assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); - let init_balance_2 = Balances::free_balance(&2); - let init_balance_10 = Balances::free_balance(&10); - - // Stingy validator. - assert_ok!(Staking::bond(Origin::signed(1), 2, 1, RewardDestination::Controller)); - assert_ok!(Staking::validate(Origin::signed(2), ValidatorPrefs::default())); - - // 1 era worth of reward. BUT, we set the timestamp after on_initialize, so outdated by - // one block. - let total_payout_0 = current_total_payout_for_duration(reward_time_per_era()); - - reward_all_elected(); - mock::start_active_era(1); - mock::make_all_reward_payment(0); - - // 2 is elected. - assert_eq_uvec!(validator_controllers(), vec![20, 10, 2]); - assert_eq!(Staking::eras_stakers(active_era(), 2).total, 0); - - // Old ones are rewarded. - assert_eq_error_rate!( - Balances::free_balance(10), - init_balance_10 + total_payout_0 / 3, - 1 - ); - // no rewards paid to 2. This was initial election. - assert_eq!(Balances::free_balance(2), init_balance_2); - - // reward era 2 - let total_payout_1 = current_total_payout_for_duration(reward_time_per_era()); - reward_all_elected(); - mock::start_active_era(2); - mock::make_all_reward_payment(1); - - assert_eq_uvec!(validator_controllers(), vec![20, 10, 2]); - assert_eq!(Staking::eras_stakers(active_era(), 2).total, 0); - - // 2 is now rewarded. - assert_eq_error_rate!( - Balances::free_balance(2), - init_balance_2 + total_payout_1 / 3, - 1 - ); - assert_eq_error_rate!( - Balances::free_balance(&10), - init_balance_10 + total_payout_0 / 3 + total_payout_1 / 3, - 2, - ); - }); -} - -#[test] -fn bond_with_duplicate_vote_should_be_ignored_by_election_provider() { - ExtBuilder::default() - .validator_count(2) - .nominate(false) - .minimum_validator_count(1) - .build_and_execute(|| { - // disable the nominator - assert_ok!(Staking::chill(Origin::signed(100))); - // make stakes equal. - assert_ok!(Staking::bond_extra(Origin::signed(31), 999)); - // ensure all have equal stake. - assert_eq!( - >::iter() - .map(|(v, _)| (v, Staking::ledger(v - 1).unwrap().total)) - .collect::>(), - vec![(31, 1000), (21, 1000), (11, 1000)], - ); - // no nominators shall exist. - assert!(>::iter().map(|(n, _)| n).collect::>().is_empty()); - - // give the man some money. - let initial_balance = 1000; - for i in [1, 2, 3, 4].iter() { - let _ = Balances::make_free_balance_be(i, initial_balance); - } - - assert_ok!(Staking::bond(Origin::signed(1), 2, 1000, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(2), vec![11, 11, 11, 21, 31])); - - assert_ok!(Staking::bond(Origin::signed(3), 4, 1000, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(4), vec![21, 31])); - - // winners should be 21 and 31. Otherwise this election is taking duplicates into - // account. - let supports = ::ElectionProvider::elect().unwrap().0; - assert_eq!( - supports, - vec![ - (21, Support { total: 1800, voters: vec![(21, 1000), (3, 400), (1, 400)] }), - (31, Support { total: 2200, voters: vec![(31, 1000), (3, 600), (1, 600)] }) - ], - ); - }); -} - -#[test] -fn bond_with_duplicate_vote_should_be_ignored_by_election_provider_elected() { - // same as above but ensures that even when the duple is being elected, everything is sane. - ExtBuilder::default() - .validator_count(2) - .nominate(false) - .minimum_validator_count(1) - .build_and_execute(|| { - // disable the nominator - assert_ok!(Staking::chill(Origin::signed(100))); - // 31/30 will have less stake - assert_ok!(Staking::bond_extra(Origin::signed(31), 99)); - // ensure all have equal stake. - assert_eq!( - >::iter() - .map(|(v, _)| (v, Staking::ledger(v - 1).unwrap().total)) - .collect::>(), - vec![(31, 100), (21, 1000), (11, 1000)], - ); - // no nominators shall exist. - assert!(>::iter().map(|(n, _)| n).collect::>().is_empty()); - - // give the man some money. - let initial_balance = 1000; - for i in [1, 2, 3, 4].iter() { - let _ = Balances::make_free_balance_be(i, initial_balance); - } - - assert_ok!(Staking::bond(Origin::signed(1), 2, 1000, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(2), vec![11, 11, 11, 21, 31])); - - assert_ok!(Staking::bond(Origin::signed(3), 4, 1000, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(4), vec![21, 31])); - - // winners should be 21 and 11. - let supports = ::ElectionProvider::elect().unwrap().0; - assert_eq!( - supports, - vec![ - (11, Support { total: 1500, voters: vec![(11, 1000), (1, 500)] }), - (21, Support { total: 2500, voters: vec![(21, 1000), (3, 1000), (1, 500)] }) - ], - ); - }); -} - -#[test] -fn new_era_elects_correct_number_of_validators() { - ExtBuilder::default() - .nominate(true) - .validator_pool(true) - .fair(true) - .validator_count(1) - .build_and_execute(|| { - assert_eq!(Staking::validator_count(), 1); - assert_eq!(validator_controllers().len(), 1); - - Session::on_initialize(System::block_number()); - - assert_eq!(validator_controllers().len(), 1); - }) -} - -#[test] -fn phragmen_should_not_overflow() { - ExtBuilder::default().nominate(false).build_and_execute(|| { - // This is the maximum value that we can have as the outcome of CurrencyToVote. - type Votes = u64; - - let _ = Staking::chill(Origin::signed(10)); - let _ = Staking::chill(Origin::signed(20)); - - bond_validator(3, 2, Votes::max_value() as Balance); - bond_validator(5, 4, Votes::max_value() as Balance); - - bond_nominator(7, 6, Votes::max_value() as Balance, vec![3, 5]); - bond_nominator(9, 8, Votes::max_value() as Balance, vec![3, 5]); - - mock::start_active_era(1); - - assert_eq_uvec!(validator_controllers(), vec![4, 2]); - - // We can safely convert back to values within [u64, u128]. - assert!(Staking::eras_stakers(active_era(), 3).total > Votes::max_value() as Balance); - assert!(Staking::eras_stakers(active_era(), 5).total > Votes::max_value() as Balance); - }) -} - -#[test] -fn reward_validator_slashing_validator_does_not_overflow() { - ExtBuilder::default().build_and_execute(|| { - let stake = u64::MAX as Balance * 2; - let halved_stake = &stake / 2; - let reward_slash = u64::MAX as Balance * 2; - - // Assert multiplication overflows in balance arithmetic. - assert!(stake.checked_mul(reward_slash).is_none()); - - // Set staker - let _ = Balances::make_free_balance_be(&11, stake); - - let exposure = Exposure:: { total: stake, own: stake, others: vec![] }; - let reward = EraRewardPoints:: { - total: 1, - individual: vec![(11, 1)].into_iter().collect(), - }; - - // Check reward - ErasRewardPoints::::insert(0, reward); - ErasStakers::::insert(0, 11, &exposure); - ErasStakersClipped::::insert(0, 11, exposure); - ErasValidatorReward::::insert(0, stake); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 0)); - assert_eq!(Tokens::total_balance(DRAM, &11), halved_stake * 2); - assert_eq!(Tokens::total_balance(SETR, &11), halved_stake * 2); - - // Set staker - let _ = Balances::make_free_balance_be(&11, stake); - let _ = Balances::make_free_balance_be(&2, stake); - - // only slashes out of bonded stake are applied. without this line, - // it is 0. - Staking::bond(Origin::signed(2), 20000, stake - 1, RewardDestination::default()).unwrap(); - // Override exposure of 11 - ErasStakers::::insert( - 0, - 11, - Exposure { - total: stake, - own: 1, - others: vec![IndividualExposure { who: 2, value: stake - 1 }], - }, - ); - - // Check slashing - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(100)], - ); - - assert_eq!(Balances::total_balance(&11), stake - 1); - assert_eq!(Balances::total_balance(&2), 1); - }) -} - -#[test] -fn reward_from_authorship_event_handler_works() { - ExtBuilder::default().build_and_execute(|| { - use pallet_authorship::EventHandler; - - assert_eq!(>::author(), 11); - - >::note_author(11); - >::note_uncle(21, 1); - // Rewarding the same two times works. - >::note_uncle(11, 1); - - // Not mandatory but must be coherent with rewards - assert_eq_uvec!(Session::validators(), vec![11, 21]); - - // 21 is rewarded as an uncle producer - // 11 is rewarded as a block producer and uncle referencer and uncle producer - assert_eq!( - ErasRewardPoints::::get(Staking::active_era().unwrap().index), - EraRewardPoints { - individual: vec![(11, 20 + 2 * 2 + 1), (21, 1)].into_iter().collect(), - total: 26, - }, - ); - }) -} - -#[test] -fn add_reward_points_fns_works() { - ExtBuilder::default().build_and_execute(|| { - // Not mandatory but must be coherent with rewards - assert_eq_uvec!(Session::validators(), vec![21, 11]); - - >::reward_by_ids(vec![(21, 1), (11, 1), (11, 1)]); - - >::reward_by_ids(vec![(21, 1), (11, 1), (11, 1)]); - - assert_eq!( - ErasRewardPoints::::get(Staking::active_era().unwrap().index), - EraRewardPoints { individual: vec![(11, 4), (21, 2)].into_iter().collect(), total: 6 }, - ); - }) -} - -#[test] -fn unbonded_balance_is_not_slashable() { - ExtBuilder::default().build_and_execute(|| { - // total amount staked is slashable. - assert_eq!(Staking::slashable_balance_of(&11), 1000); - - assert_ok!(Staking::unbond(Origin::signed(10), 800)); - - // only the active portion. - assert_eq!(Staking::slashable_balance_of(&11), 200); - }) -} - -#[test] -fn era_is_always_same_length() { - // This ensures that the sessions is always of the same length if there is no forcing no - // session changes. - ExtBuilder::default().build_and_execute(|| { - let session_per_era = >::get(); - - mock::start_active_era(1); - assert_eq!(Staking::eras_start_session_index(current_era()).unwrap(), session_per_era); - - mock::start_active_era(2); - assert_eq!( - Staking::eras_start_session_index(current_era()).unwrap(), - session_per_era * 2u32 - ); - - let session = Session::current_index(); - ForceEra::::put(Forcing::ForceNew); - advance_session(); - advance_session(); - assert_eq!(current_era(), 3); - assert_eq!(Staking::eras_start_session_index(current_era()).unwrap(), session + 2); - - mock::start_active_era(4); - assert_eq!( - Staking::eras_start_session_index(current_era()).unwrap(), - session + 2u32 + session_per_era - ); - }); -} - -#[test] -fn offence_forces_new_era() { - ExtBuilder::default().build_and_execute(|| { - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(5)], - ); - - assert_eq!(Staking::force_era(), Forcing::ForceNew); - }); -} - -#[test] -fn offence_ensures_new_era_without_clobbering() { - ExtBuilder::default().build_and_execute(|| { - assert_ok!(Staking::force_new_era_always(Origin::root())); - assert_eq!(Staking::force_era(), Forcing::ForceAlways); - - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(5)], - ); - - assert_eq!(Staking::force_era(), Forcing::ForceAlways); - }); -} - -#[test] -fn offence_deselects_validator_even_when_slash_is_zero() { - ExtBuilder::default().build_and_execute(|| { - assert!(Session::validators().contains(&11)); - assert!(>::contains_key(11)); - - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(0)], - ); - - assert_eq!(Staking::force_era(), Forcing::ForceNew); - assert!(!>::contains_key(11)); - - mock::start_active_era(1); - - assert!(!Session::validators().contains(&11)); - assert!(!>::contains_key(11)); - }); -} - -#[test] -fn slashing_performed_according_exposure() { - // This test checks that slashing is performed according the exposure (or more precisely, - // historical exposure), not the current balance. - ExtBuilder::default().build_and_execute(|| { - assert_eq!(Staking::eras_stakers(Staking::active_era().unwrap().index, 11).own, 1000); - - // Handle an offence with a historical exposure. - on_offence_now( - &[OffenceDetails { - offender: (11, Exposure { total: 500, own: 500, others: vec![] }), - reporters: vec![], - }], - &[Perbill::from_percent(50)], - ); - - // The stash account should be slashed for 250 (50% of 500). - assert_eq!(Balances::free_balance(11), 1000 - 250); - }); -} - -#[test] -fn slash_in_old_span_does_not_deselect() { - ExtBuilder::default().build_and_execute(|| { - mock::start_active_era(1); - - assert!(>::contains_key(11)); - assert!(Session::validators().contains(&11)); - - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(0)], - ); - - assert_eq!(Staking::force_era(), Forcing::ForceNew); - assert!(!>::contains_key(11)); - - mock::start_active_era(2); - - Staking::validate(Origin::signed(10), Default::default()).unwrap(); - assert_eq!(Staking::force_era(), Forcing::NotForcing); - assert!(>::contains_key(11)); - assert!(!Session::validators().contains(&11)); - - mock::start_active_era(3); - - // this staker is in a new slashing span now, having re-registered after - // their prior slash. - - on_offence_in_era( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(0)], - 1, - ); - - // not forcing for zero-slash and previous span. - assert_eq!(Staking::force_era(), Forcing::NotForcing); - assert!(>::contains_key(11)); - assert!(Session::validators().contains(&11)); - - on_offence_in_era( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - // NOTE: A 100% slash here would clean up the account, causing de-registration. - &[Perbill::from_percent(95)], - 1, - ); - - // or non-zero. - assert_eq!(Staking::force_era(), Forcing::NotForcing); - assert!(>::contains_key(11)); - assert!(Session::validators().contains(&11)); - }); -} - -#[test] -fn reporters_receive_their_slice() { - // This test verifies that the reporters of the offence receive their slice from the slashed - // amount. - ExtBuilder::default().build_and_execute(|| { - // The reporters' reward is calculated from the total exposure. - let initial_balance = 1125; - - assert_eq!( - Staking::eras_stakers(Staking::active_era().unwrap().index, 11).total, - initial_balance - ); - - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![1, 2], - }], - &[Perbill::from_percent(50)], - ); - - // F1 * (reward_proportion * slash - 0) - // 50% * (10% * initial_balance / 2) - let reward = (initial_balance / 20) / 2; - let reward_each = reward / 2; // split into two pieces. - assert_eq!(Balances::free_balance(1), 10 + reward_each); - assert_eq!(Balances::free_balance(2), 20 + reward_each); - }); -} - -#[test] -fn subsequent_reports_in_same_span_pay_out_less() { - // This test verifies that the reporters of the offence receive their slice from the slashed - // amount, but less and less if they submit multiple reports in one span. - ExtBuilder::default().build_and_execute(|| { - // The reporters' reward is calculated from the total exposure. - let initial_balance = 1125; - - assert_eq!( - Staking::eras_stakers(Staking::active_era().unwrap().index, 11).total, - initial_balance - ); - - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![1], - }], - &[Perbill::from_percent(20)], - ); - - // F1 * (reward_proportion * slash - 0) - // 50% * (10% * initial_balance * 20%) - let reward = (initial_balance / 5) / 20; - assert_eq!(Balances::free_balance(1), 10 + reward); - - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![1], - }], - &[Perbill::from_percent(50)], - ); - - let prior_payout = reward; - - // F1 * (reward_proportion * slash - prior_payout) - // 50% * (10% * (initial_balance / 2) - prior_payout) - let reward = ((initial_balance / 20) - prior_payout) / 2; - assert_eq!(Balances::free_balance(1), 10 + prior_payout + reward); - }); -} - -#[test] -fn invulnerables_are_not_slashed() { - // For invulnerable validators no slashing is performed. - ExtBuilder::default().invulnerables(vec![11]).build_and_execute(|| { - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(21), 2000); - - let exposure = Staking::eras_stakers(Staking::active_era().unwrap().index, 21); - let initial_balance = Staking::slashable_balance_of(&21); - - let nominator_balances: Vec<_> = - exposure.others.iter().map(|o| Balances::free_balance(&o.who)).collect(); - - on_offence_now( - &[ - OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }, - OffenceDetails { - offender: (21, Staking::eras_stakers(Staking::active_era().unwrap().index, 21)), - reporters: vec![], - }, - ], - &[Perbill::from_percent(50), Perbill::from_percent(20)], - ); - - // The validator 11 hasn't been slashed, but 21 has been. - assert_eq!(Balances::free_balance(11), 1000); - // 2000 - (0.2 * initial_balance) - assert_eq!(Balances::free_balance(21), 2000 - (2 * initial_balance / 10)); - - // ensure that nominators were slashed as well. - for (initial_balance, other) in nominator_balances.into_iter().zip(exposure.others) { - assert_eq!( - Balances::free_balance(&other.who), - initial_balance - (2 * other.value / 10), - ); - } - }); -} - -#[test] -fn dont_slash_if_fraction_is_zero() { - // Don't slash if the fraction is zero. - ExtBuilder::default().build_and_execute(|| { - assert_eq!(Balances::free_balance(11), 1000); - - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(0)], - ); - - // The validator hasn't been slashed. The new era is not forced. - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Staking::force_era(), Forcing::ForceNew); - }); -} - -#[test] -fn only_slash_for_max_in_era() { - // multiple slashes within one era are only applied if it is more than any previous slash in the - // same era. - ExtBuilder::default().build_and_execute(|| { - assert_eq!(Balances::free_balance(11), 1000); - - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(50)], - ); - - // The validator has been slashed and has been force-chilled. - assert_eq!(Balances::free_balance(11), 500); - assert_eq!(Staking::force_era(), Forcing::ForceNew); - - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(25)], - ); - - // The validator has not been slashed additionally. - assert_eq!(Balances::free_balance(11), 500); - - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(60)], - ); - - // The validator got slashed 10% more. - assert_eq!(Balances::free_balance(11), 400); - }) -} - -#[test] -fn garbage_collection_after_slashing() { - // ensures that `SlashingSpans` and `SpanSlash` of an account is removed after reaping. - ExtBuilder::default() - .existential_deposit(2) - .min_nominator_bond(2) - .min_validator_bond(2) - .build_and_execute(|| { - assert_eq!(Balances::free_balance(11), 256_000); - - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(10)], - ); - - assert_eq!(Balances::free_balance(11), 256_000 - 25_600); - assert!(::SlashingSpans::get(&11).is_some()); - assert_eq!( - ::SpanSlash::get(&(11, 0)).amount_slashed(), - &25_600 - ); - - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(100)], - ); - - // validator and nominator slash in era are garbage-collected by era change, - // so we don't test those here. - - assert_eq!(Balances::free_balance(11), 2); - assert_eq!(Balances::total_balance(&11), 2); - - let slashing_spans = ::SlashingSpans::get(&11).unwrap(); - assert_eq!(slashing_spans.iter().count(), 2); - - // reap_stash respects num_slashing_spans so that weight is accurate - assert_noop!( - Staking::reap_stash(Origin::none(), 11, 0), - Error::::IncorrectSlashingSpans - ); - assert_ok!(Staking::reap_stash(Origin::none(), 11, 2)); - - assert!(::SlashingSpans::get(&11).is_none()); - assert_eq!(::SpanSlash::get(&(11, 0)).amount_slashed(), &0); - }) -} - -#[test] -fn garbage_collection_on_window_pruning() { - // ensures that `ValidatorSlashInEra` and `NominatorSlashInEra` are cleared after - // `BondingDuration`. - ExtBuilder::default().build_and_execute(|| { - mock::start_active_era(1); - - assert_eq!(Balances::free_balance(11), 1000); - let now = Staking::active_era().unwrap().index; - - let exposure = Staking::eras_stakers(now, 11); - assert_eq!(Balances::free_balance(101), 2000); - let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value; - - on_offence_now( - &[OffenceDetails { offender: (11, Staking::eras_stakers(now, 11)), reporters: vec![] }], - &[Perbill::from_percent(10)], - ); - - assert_eq!(Balances::free_balance(11), 900); - assert_eq!(Balances::free_balance(101), 2000 - (nominated_value / 10)); - - assert!(::ValidatorSlashInEra::get(&now, &11).is_some()); - assert!(::NominatorSlashInEra::get(&now, &101).is_some()); - - // + 1 because we have to exit the bonding window. - for era in (0..(BondingDuration::get() + 1)).map(|offset| offset + now + 1) { - assert!(::ValidatorSlashInEra::get(&now, &11).is_some()); - assert!(::NominatorSlashInEra::get(&now, &101).is_some()); - - mock::start_active_era(era); - } - - assert!(::ValidatorSlashInEra::get(&now, &11).is_none()); - assert!(::NominatorSlashInEra::get(&now, &101).is_none()); - }) -} - -#[test] -fn slashing_nominators_by_span_max() { - ExtBuilder::default().build_and_execute(|| { - mock::start_active_era(1); - mock::start_active_era(2); - mock::start_active_era(3); - - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(21), 2000); - assert_eq!(Balances::free_balance(101), 2000); - assert_eq!(Staking::slashable_balance_of(&21), 1000); - - let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, 11); - let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, 21); - let nominated_value_11 = exposure_11.others.iter().find(|o| o.who == 101).unwrap().value; - let nominated_value_21 = exposure_21.others.iter().find(|o| o.who == 101).unwrap().value; - - on_offence_in_era( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(10)], - 2, - ); - - assert_eq!(Balances::free_balance(11), 900); - - let slash_1_amount = Perbill::from_percent(10) * nominated_value_11; - assert_eq!(Balances::free_balance(101), 2000 - slash_1_amount); - - let expected_spans = vec![ - slashing::SlashingSpan { index: 1, start: 4, length: None }, - slashing::SlashingSpan { index: 0, start: 0, length: Some(4) }, - ]; - - let get_span = |account| ::SlashingSpans::get(&account).unwrap(); - - assert_eq!(get_span(11).iter().collect::>(), expected_spans); - - assert_eq!(get_span(101).iter().collect::>(), expected_spans); - - // second slash: higher era, higher value, same span. - on_offence_in_era( - &[OffenceDetails { - offender: (21, Staking::eras_stakers(Staking::active_era().unwrap().index, 21)), - reporters: vec![], - }], - &[Perbill::from_percent(30)], - 3, - ); - - // 11 was not further slashed, but 21 and 101 were. - assert_eq!(Balances::free_balance(11), 900); - assert_eq!(Balances::free_balance(21), 1700); - - let slash_2_amount = Perbill::from_percent(30) * nominated_value_21; - assert!(slash_2_amount > slash_1_amount); - - // only the maximum slash in a single span is taken. - assert_eq!(Balances::free_balance(101), 2000 - slash_2_amount); - - // third slash: in same era and on same validator as first, higher - // in-era value, but lower slash value than slash 2. - on_offence_in_era( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(20)], - 2, - ); - - // 11 was further slashed, but 21 and 101 were not. - assert_eq!(Balances::free_balance(11), 800); - assert_eq!(Balances::free_balance(21), 1700); - - let slash_3_amount = Perbill::from_percent(20) * nominated_value_21; - assert!(slash_3_amount < slash_2_amount); - assert!(slash_3_amount > slash_1_amount); - - // only the maximum slash in a single span is taken. - assert_eq!(Balances::free_balance(101), 2000 - slash_2_amount); - }); -} - -#[test] -fn slashes_are_summed_across_spans() { - ExtBuilder::default().build_and_execute(|| { - mock::start_active_era(1); - mock::start_active_era(2); - mock::start_active_era(3); - - assert_eq!(Balances::free_balance(21), 2000); - assert_eq!(Staking::slashable_balance_of(&21), 1000); - - let get_span = |account| ::SlashingSpans::get(&account).unwrap(); - - on_offence_now( - &[OffenceDetails { - offender: (21, Staking::eras_stakers(Staking::active_era().unwrap().index, 21)), - reporters: vec![], - }], - &[Perbill::from_percent(10)], - ); - - let expected_spans = vec![ - slashing::SlashingSpan { index: 1, start: 4, length: None }, - slashing::SlashingSpan { index: 0, start: 0, length: Some(4) }, - ]; - - assert_eq!(get_span(21).iter().collect::>(), expected_spans); - assert_eq!(Balances::free_balance(21), 1900); - - // 21 has been force-chilled. re-signal intent to validate. - Staking::validate(Origin::signed(20), Default::default()).unwrap(); - - mock::start_active_era(4); - - assert_eq!(Staking::slashable_balance_of(&21), 900); - - on_offence_now( - &[OffenceDetails { - offender: (21, Staking::eras_stakers(Staking::active_era().unwrap().index, 21)), - reporters: vec![], - }], - &[Perbill::from_percent(10)], - ); - - let expected_spans = vec![ - slashing::SlashingSpan { index: 2, start: 5, length: None }, - slashing::SlashingSpan { index: 1, start: 4, length: Some(1) }, - slashing::SlashingSpan { index: 0, start: 0, length: Some(4) }, - ]; - - assert_eq!(get_span(21).iter().collect::>(), expected_spans); - assert_eq!(Balances::free_balance(21), 1810); - }); -} - -#[test] -fn deferred_slashes_are_deferred() { - ExtBuilder::default().slash_defer_duration(2).build_and_execute(|| { - mock::start_active_era(1); - - assert_eq!(Balances::free_balance(11), 1000); - - let exposure = Staking::eras_stakers(Staking::active_era().unwrap().index, 11); - assert_eq!(Balances::free_balance(101), 2000); - let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value; - - on_offence_now( - &[OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![], - }], - &[Perbill::from_percent(10)], - ); - - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); - - mock::start_active_era(2); - - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); - - mock::start_active_era(3); - - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); - - // at the start of era 4, slashes from era 1 are processed, - // after being deferred for at least 2 full eras. - mock::start_active_era(4); - - assert_eq!(Balances::free_balance(11), 900); - assert_eq!(Balances::free_balance(101), 2000 - (nominated_value / 10)); - }) -} - -#[test] -fn remove_deferred() { - ExtBuilder::default().slash_defer_duration(2).build_and_execute(|| { - mock::start_active_era(1); - - assert_eq!(Balances::free_balance(11), 1000); - - let exposure = Staking::eras_stakers(Staking::active_era().unwrap().index, 11); - assert_eq!(Balances::free_balance(101), 2000); - let nominated_value = exposure.others.iter().find(|o| o.who == 101).unwrap().value; - - on_offence_now( - &[OffenceDetails { offender: (11, exposure.clone()), reporters: vec![] }], - &[Perbill::from_percent(10)], - ); - - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); - - mock::start_active_era(2); - - on_offence_in_era( - &[OffenceDetails { offender: (11, exposure.clone()), reporters: vec![] }], - &[Perbill::from_percent(15)], - 1, - ); - - // fails if empty - assert_noop!( - Staking::cancel_deferred_slash(Origin::root(), 1, vec![]), - Error::::EmptyTargets - ); - - assert_ok!(Staking::cancel_deferred_slash(Origin::root(), 1, vec![0])); - - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); - - mock::start_active_era(3); - - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); - - // at the start of era 4, slashes from era 1 are processed, - // after being deferred for at least 2 full eras. - mock::start_active_era(4); - - // the first slash for 10% was cancelled, so no effect. - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); - - mock::start_active_era(5); - - let slash_10 = Perbill::from_percent(10); - let slash_15 = Perbill::from_percent(15); - let initial_slash = slash_10 * nominated_value; - - let total_slash = slash_15 * nominated_value; - let actual_slash = total_slash - initial_slash; - - // 5% slash (15 - 10) processed now. - assert_eq!(Balances::free_balance(11), 950); - assert_eq!(Balances::free_balance(101), 2000 - actual_slash); - }) -} - -#[test] -fn remove_multi_deferred() { - ExtBuilder::default().slash_defer_duration(2).build_and_execute(|| { - mock::start_active_era(1); - - assert_eq!(Balances::free_balance(11), 1000); - - let exposure = Staking::eras_stakers(Staking::active_era().unwrap().index, 11); - assert_eq!(Balances::free_balance(101), 2000); - - on_offence_now( - &[OffenceDetails { offender: (11, exposure.clone()), reporters: vec![] }], - &[Perbill::from_percent(10)], - ); - - on_offence_now( - &[OffenceDetails { - offender: (21, Staking::eras_stakers(Staking::active_era().unwrap().index, 21)), - reporters: vec![], - }], - &[Perbill::from_percent(10)], - ); - - on_offence_now( - &[OffenceDetails { offender: (11, exposure.clone()), reporters: vec![] }], - &[Perbill::from_percent(25)], - ); - - on_offence_now( - &[OffenceDetails { offender: (42, exposure.clone()), reporters: vec![] }], - &[Perbill::from_percent(25)], - ); - - on_offence_now( - &[OffenceDetails { offender: (69, exposure.clone()), reporters: vec![] }], - &[Perbill::from_percent(25)], - ); - - assert_eq!(::UnappliedSlashes::get(&1).len(), 5); - - // fails if list is not sorted - assert_noop!( - Staking::cancel_deferred_slash(Origin::root(), 1, vec![2, 0, 4]), - Error::::NotSortedAndUnique - ); - // fails if list is not unique - assert_noop!( - Staking::cancel_deferred_slash(Origin::root(), 1, vec![0, 2, 2]), - Error::::NotSortedAndUnique - ); - // fails if bad index - assert_noop!( - Staking::cancel_deferred_slash(Origin::root(), 1, vec![1, 2, 3, 4, 5]), - Error::::InvalidSlashIndex - ); - - assert_ok!(Staking::cancel_deferred_slash(Origin::root(), 1, vec![0, 2, 4])); - - let slashes = ::UnappliedSlashes::get(&1); - assert_eq!(slashes.len(), 2); - assert_eq!(slashes[0].validator, 21); - assert_eq!(slashes[1].validator, 42); - }) -} - -#[test] -fn slash_kicks_validators_not_nominators_and_disables_nominator_for_kicked_validator() { - ExtBuilder::default().build_and_execute(|| { - mock::start_active_era(1); - assert_eq_uvec!(Session::validators(), vec![11, 21]); - - // pre-slash balance - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); - - // 11 and 21 both have the support of 100 - let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11); - let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21); - - assert_eq!(exposure_11.total, 1000 + 125); - assert_eq!(exposure_21.total, 1000 + 375); - - on_offence_now( - &[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }], - &[Perbill::from_percent(10)], - ); - - // post-slash balance - let nominator_slash_amount_11 = 125 / 10; - assert_eq!(Balances::free_balance(11), 900); - assert_eq!(Balances::free_balance(101), 2000 - nominator_slash_amount_11); - - // This is the best way to check that the validator was chilled; `get` will - // return default value. - for (stash, _) in ::Validators::iter() { - assert!(stash != 11); - } - - let nominations = ::Nominators::get(&101).unwrap(); - - // and make sure that the vote will be ignored even if the validator - // re-registers. - let last_slash = ::SlashingSpans::get(&11).unwrap().last_nonzero_slash(); - assert!(nominations.submitted_in < last_slash); - - // actually re-bond the slashed validator - assert_ok!(Staking::validate(Origin::signed(10), Default::default())); - - mock::start_active_era(2); - let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11); - let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21); - - // 10 is re-elected, but without the support of 100 - assert_eq!(exposure_11.total, 900); - - // 20 is re-elected, with the (almost) entire support of 100 - assert_eq!(exposure_21.total, 1000 + 500 - nominator_slash_amount_11); - }); -} - -#[test] -fn claim_reward_at_the_last_era_and_no_double_claim_and_invalid_claim() { - // should check that: - // * rewards get paid until history_depth for both validators and nominators - // * an invalid era to claim doesn't update last_reward - // * double claim of one era fails - ExtBuilder::default().nominate(true).build_and_execute(|| { - // Consumed weight for all payout_stakers dispatches that fail - let err_weight = weights::SubstrateWeight::::payout_stakers_alive_staked(0); - - let init_balance_5 = Tokens::total_balance(DRAM, &5); - let init_balance_50 = Tokens::total_balance(DRAM, &50); - let init_balance_5 = Tokens::total_balance(SETR, &5); - let init_balance_50 = Tokens::total_balance(SETR, &50); - - let part_for_10 = Perbill::from_rational::(1000, 1125); - let part_for_100 = Perbill::from_rational::(125, 1125); - - MockPriceSource::set_relative_price(Some(Price::one())); - assert_eq!( - SerpPrices::get_relative_price(DNAR, DRAM), - Some(Price::saturating_from_rational(1, 1)) // 1DNAR = 1DRAM - ); - - MockPriceSource::set_relative_price(Some(Price::one())); - assert_eq!( - SerpPrices::get_relative_price(DRAM, SETR), - Some(Price::saturating_from_rational(1, 1)) // 1DRAM = 1SETR - ); - - // Check state - Payee::::insert(11, RewardDestination::Controller); - Payee::::insert(101, RewardDestination::Controller); - - >::reward_by_ids(vec![(11, 1)]); - // Compute total payout now for whole duration as other parameter won't change - let total_payout_0 = current_total_payout_for_duration(reward_time_per_era()); - - mock::start_active_era(1); - - >::reward_by_ids(vec![(11, 1)]); - // Change total issuance in order to modify total payout - let _ = Balances::deposit_creating(&999, 1_000_000_000); - // Compute total payout now for whole duration as other parameter won't change - let total_payout_1 = current_total_payout_for_duration(reward_time_per_era()); - assert!(total_payout_1 != total_payout_0); - - let halved_total_payout_1 = total_payout_1 / 2; - - mock::start_active_era(2); - - >::reward_by_ids(vec![(11, 1)]); - // Change total issuance in order to modify total payout - let _ = Balances::deposit_creating(&999, 1_000_000_000); - // Compute total payout now for whole duration as other parameter won't change - let total_payout_2 = current_total_payout_for_duration(reward_time_per_era()); - assert!(total_payout_2 != total_payout_0); - assert!(total_payout_2 != total_payout_1); - - let halved_total_payout_2 = total_payout_2 / 2; - - mock::start_active_era(Staking::history_depth() + 1); - - let active_era = Staking::active_era().unwrap().index; - - // This is the latest planned era in staking, not the active era - let current_era = Staking::current_era().unwrap(); - - // Last kept is 1: - assert!(current_era - Staking::history_depth() == 1); - assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, 0), - // Fail: Era out of history - Error::::InvalidEraToReward.with_weight(err_weight) - ); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 1)); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 2)); - assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, 2), - // Fail: Double claim - Error::::AlreadyClaimed.with_weight(err_weight) - ); - assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, active_era), - // Fail: Era not finished yet - Error::::InvalidEraToReward.with_weight(err_weight) - ); - - // Era 0 can't be rewarded anymore and current era can't be rewarded yet - // only era 1 and 2 can be rewarded. - - assert_eq!( - Tokens::total_balance(DRAM, &5), - init_balance_5 + part_for_5 * (halved_total_payout_1 + halved_total_payout_2), - ); - assert_eq!( - Tokens::total_balance(DRAM, &50), - init_balance_50 + part_for_50 * (halved_total_payout_1 + halved_total_payout_2), - ); - assert_eq!( - Tokens::total_balance(SETR, &5), - init_balance_5 + part_for_5 * (halved_total_payout_1 + halved_total_payout_2), - ); - assert_eq!( - Tokens::total_balance(SETR, &50), - init_balance_50 + part_for_50 * (halved_total_payout_1 + halved_total_payout_2), - ); - }); -} - -#[test] -fn zero_slash_keeps_nominators() { - ExtBuilder::default().build_and_execute(|| { - mock::start_active_era(1); - - assert_eq!(Balances::free_balance(11), 1000); - - let exposure = Staking::eras_stakers(Staking::active_era().unwrap().index, 11); - assert_eq!(Balances::free_balance(101), 2000); - - on_offence_now( - &[OffenceDetails { offender: (11, exposure.clone()), reporters: vec![] }], - &[Perbill::from_percent(0)], - ); - - assert_eq!(Balances::free_balance(11), 1000); - assert_eq!(Balances::free_balance(101), 2000); - - // This is the best way to check that the validator was chilled; `get` will - // return default value. - for (stash, _) in ::Validators::iter() { - assert!(stash != 11); - } - - let nominations = ::Nominators::get(&101).unwrap(); - - // and make sure that the vote will not be ignored, because the slash was - // zero. - let last_slash = ::SlashingSpans::get(&11).unwrap().last_nonzero_slash(); - assert!(nominations.submitted_in >= last_slash); - }); -} - -#[test] -fn six_session_delay() { - ExtBuilder::default().initialize_first_session(false).build_and_execute(|| { - use pallet_session::SessionManager; - - let val_set = Session::validators(); - let init_session = Session::current_index(); - let init_active_era = Staking::active_era().unwrap().index; - - // pallet-session is delaying session by one, thus the next session to plan is +2. - assert_eq!(>::new_session(init_session + 2), None); - assert_eq!( - >::new_session(init_session + 3), - Some(val_set.clone()) - ); - assert_eq!(>::new_session(init_session + 4), None); - assert_eq!(>::new_session(init_session + 5), None); - assert_eq!( - >::new_session(init_session + 6), - Some(val_set.clone()) - ); - - >::end_session(init_session); - >::start_session(init_session + 1); - assert_eq!(active_era(), init_active_era); - - >::end_session(init_session + 1); - >::start_session(init_session + 2); - assert_eq!(active_era(), init_active_era); - - // Reward current era - Staking::reward_by_ids(vec![(11, 1)]); - - // New active era is triggered here. - >::end_session(init_session + 2); - >::start_session(init_session + 3); - assert_eq!(active_era(), init_active_era + 1); - - >::end_session(init_session + 3); - >::start_session(init_session + 4); - assert_eq!(active_era(), init_active_era + 1); - - >::end_session(init_session + 4); - >::start_session(init_session + 5); - assert_eq!(active_era(), init_active_era + 1); - - // Reward current era - Staking::reward_by_ids(vec![(21, 2)]); - - // New active era is triggered here. - >::end_session(init_session + 5); - >::start_session(init_session + 6); - assert_eq!(active_era(), init_active_era + 2); - - // That reward are correct - assert_eq!(Staking::eras_reward_points(init_active_era).total, 1); - assert_eq!(Staking::eras_reward_points(init_active_era + 1).total, 2); - }); -} - -#[test] -fn test_max_nominator_rewarded_per_validator_and_cant_steal_someone_else_reward() { - ExtBuilder::default().build_and_execute(|| { - for i in 0..=::MaxNominatorRewardedPerValidator::get() { - let stash = 10_000 + i as AccountId; - let controller = 20_000 + i as AccountId; - let balance = 10_000 + i as Balance; - Balances::make_free_balance_be(&stash, balance); - assert_ok!(Staking::bond( - Origin::signed(stash), - controller, - balance, - RewardDestination::Stash - )); - assert_ok!(Staking::nominate(Origin::signed(controller), vec![11])); - } - mock::start_active_era(1); - - >::reward_by_ids(vec![(11, 1)]); - // compute and ensure the reward amount is greater than zero. - let _ = current_total_payout_for_duration(reward_time_per_era()); - - mock::start_active_era(2); - mock::make_all_reward_payment(1); - - // TODO: Check if to Update to Tokens is needed! - // - // Assert only nominators from 1 to Max are rewarded - for i in 0..=::MaxNominatorRewardedPerValidator::get() { - let stash = 10_000 + i as AccountId; - let balance = 10_000 + i as Balance; - if stash == 10_000 { - assert!(Balances::free_balance(&stash) == balance); - } else { - assert!(Balances::free_balance(&stash) > balance); - } - } - }); -} - -#[test] -fn set_history_depth_works() { - ExtBuilder::default().build_and_execute(|| { - mock::start_active_era(10); - Staking::set_history_depth(Origin::root(), 20, 0).unwrap(); - assert!(::ErasTotalStake::contains_key(10 - 4)); - assert!(::ErasTotalStake::contains_key(10 - 5)); - Staking::set_history_depth(Origin::root(), 4, 0).unwrap(); - assert!(::ErasTotalStake::contains_key(10 - 4)); - assert!(!::ErasTotalStake::contains_key(10 - 5)); - Staking::set_history_depth(Origin::root(), 3, 0).unwrap(); - assert!(!::ErasTotalStake::contains_key(10 - 4)); - assert!(!::ErasTotalStake::contains_key(10 - 5)); - Staking::set_history_depth(Origin::root(), 8, 0).unwrap(); - assert!(!::ErasTotalStake::contains_key(10 - 4)); - assert!(!::ErasTotalStake::contains_key(10 - 5)); - }); -} - -#[test] -fn test_payout_stakers() { - // Here we will test validator can set `max_nominators_payout` and it works. - // We also test that `payout_extra_nominators` works. - ExtBuilder::default().has_stakers(false).build_and_execute(|| { - let balance = 1000; - - MockPriceSource::set_relative_price(Some(Price::one())); - assert_eq!( - PriceSource::get_relative_price(DNAR, DRAM), - Some(Price::saturating_from_rational(1, 2)) // 1DNAR = 2DRAM - ); - - MockPriceSource::set_relative_price(Some(Price::one())); - assert_eq!( - PriceSource::get_relative_price(DRAM, SETR), - Some(Price::saturating_from_rational(1, 2)) // 1DRAM = 2SETR - ); - - // Create a validator: - bond_validator(11, 10, balance); // Default(64) - - // Create nominators, targeting stash of validators - for i in 0..100 { - bond_nominator(1000 + i, 100 + i, balance + i as Balance, vec![11]); - } - - mock::start_active_era(1); - Staking::reward_by_ids(vec![(11, 1)]); - - // compute and ensure the reward amount is greater than zero. - let _ = current_total_payout_for_duration(reward_time_per_era()); - - mock::start_active_era(2); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 1)); - - // Top 64 nominators of validator 11 automatically paid out, including the validator - // Validator payout goes to controller. - assert!(Tokens::free_balance(DRAM, &10) > balance); - assert!(Tokens::free_balance(SETR, &10) > balance); - for i in 36..100 { - assert!(Tokens::free_balance(DRAM, &(100 + i)) > balance + i as Balance); - assert!(Tokens::free_balance(SETR, &(100 + i)) > balance + i as Balance); - } - // The bottom 36 do not - for i in 0..36 { - assert_eq!(Tokens::free_balance(DRAM, &(100 + i)), balance + i as Balance); - assert_eq!(Tokens::free_balance(SETR, &(100 + i)), balance + i as Balance); - } - - // We track rewards in `claimed_rewards` vec - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![1] - }) - ); - - for i in 3..16 { - Staking::reward_by_ids(vec![(11, 1)]); - - // compute and ensure the reward amount is greater than zero. - let _ = current_total_payout_for_duration(reward_time_per_era()); - - mock::start_active_era(i); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, i - 1)); - } - - // We track rewards in `claimed_rewards` vec - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: (1..=14).collect() - }) - ); - - for i in 16..100 { - Staking::reward_by_ids(vec![(11, 1)]); - // compute and ensure the reward amount is greater than zero. - let _ = current_total_payout_for_duration(reward_time_per_era()); - mock::start_active_era(i); - } - - // We clean it up as history passes - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 15)); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 98)); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![15, 98] - }) - ); - - // Out of order claims works. - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 69)); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 23)); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 42)); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![15, 23, 42, 69, 98] - }) - ); - }); -} - -#[test] -fn payout_stakers_handles_basic_errors() { - // Here we will test payouts handle all errors. - ExtBuilder::default().has_stakers(false).build_and_execute(|| { - // Consumed weight for all payout_stakers dispatches that fail - let err_weight = weights::SubstrateWeight::::payout_stakers_alive_staked(0); - - // Same setup as the test above - let balance = 1000; - bond_validator(11, 10, balance); // Default(64) - - // Create nominators, targeting stash - for i in 0..100 { - bond_nominator(1000 + i, 100 + i, balance + i as Balance, vec![11]); - } - - mock::start_active_era(1); - Staking::reward_by_ids(vec![(11, 1)]); - - // compute and ensure the reward amount is greater than zero. - let _ = current_total_payout_for_duration(reward_time_per_era()); - - mock::start_active_era(2); - - // Wrong Era, too big - assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, 2), - Error::::InvalidEraToReward.with_weight(err_weight) - ); - // Wrong Staker - assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 10, 1), - Error::::NotStash.with_weight(err_weight) - ); - - for i in 3..100 { - Staking::reward_by_ids(vec![(11, 1)]); - // compute and ensure the reward amount is greater than zero. - let _ = current_total_payout_for_duration(reward_time_per_era()); - mock::start_active_era(i); - } - // We are at era 99, with history depth of 84 - // We should be able to payout era 15 through 98 (84 total eras), but not 14 or 99. - assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, 14), - Error::::InvalidEraToReward.with_weight(err_weight) - ); - assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, 99), - Error::::InvalidEraToReward.with_weight(err_weight) - ); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 15)); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 98)); - - // Can't claim again - assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, 15), - Error::::AlreadyClaimed.with_weight(err_weight) - ); - assert_noop!( - Staking::payout_stakers(Origin::signed(1337), 11, 98), - Error::::AlreadyClaimed.with_weight(err_weight) - ); - }); -} - -#[test] -fn payout_stakers_handles_weight_refund() { - // Note: this test relies on the assumption that `payout_stakers_alive_staked` is solely used by - // `payout_stakers` to calculate the weight of each payout op. - ExtBuilder::default().has_stakers(false).build_and_execute(|| { - let max_nom_rewarded = ::MaxNominatorRewardedPerValidator::get(); - // Make sure the configured value is meaningful for our use. - assert!(max_nom_rewarded >= 4); - let half_max_nom_rewarded = max_nom_rewarded / 2; - // Sanity check our max and half max nominator quantities. - assert!(half_max_nom_rewarded > 0); - assert!(max_nom_rewarded > half_max_nom_rewarded); - - let max_nom_rewarded_weight = - ::WeightInfo::payout_stakers_alive_staked(max_nom_rewarded); - let half_max_nom_rewarded_weight = - ::WeightInfo::payout_stakers_alive_staked(half_max_nom_rewarded); - let zero_nom_payouts_weight = ::WeightInfo::payout_stakers_alive_staked(0); - assert!(zero_nom_payouts_weight > 0); - assert!(half_max_nom_rewarded_weight > zero_nom_payouts_weight); - assert!(max_nom_rewarded_weight > half_max_nom_rewarded_weight); - - let balance = 1000; - bond_validator(11, 10, balance); - - // Era 1 - start_active_era(1); - - // Reward just the validator. - Staking::reward_by_ids(vec![(11, 1)]); - - // Add some `half_max_nom_rewarded` nominators who will start backing the validator in the - // next era. - for i in 0..half_max_nom_rewarded { - bond_nominator((1000 + i).into(), (100 + i).into(), balance + i as Balance, vec![11]); - } - - // Era 2 - start_active_era(2); - - // Collect payouts when there are no nominators - let call = TestRuntimeCall::Staking(StakingCall::payout_stakers(11, 1)); - let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(20)); - assert_ok!(result); - assert_eq!(extract_actual_weight(&result, &info), zero_nom_payouts_weight); - - // The validator is not rewarded in this era; so there will be zero payouts to claim for this era. - - // Era 3 - start_active_era(3); - - // Collect payouts for an era where the validator did not receive any points. - let call = TestRuntimeCall::Staking(StakingCall::payout_stakers(11, 2)); - let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(20)); - assert_ok!(result); - assert_eq!(extract_actual_weight(&result, &info), zero_nom_payouts_weight); - - // Reward the validator and its nominators. - Staking::reward_by_ids(vec![(11, 1)]); - - // Era 4 - start_active_era(4); - - // Collect payouts when the validator has `half_max_nom_rewarded` nominators. - let call = TestRuntimeCall::Staking(StakingCall::payout_stakers(11, 3)); - let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(20)); - assert_ok!(result); - assert_eq!(extract_actual_weight(&result, &info), half_max_nom_rewarded_weight); - - // Add enough nominators so that we are at the limit. They will be active nominators - // in the next era. - for i in half_max_nom_rewarded..max_nom_rewarded { - bond_nominator((1000 + i).into(), (100 + i).into(), balance + i as Balance, vec![11]); - } - - // Era 5 - start_active_era(5); - // We now have `max_nom_rewarded` nominators actively nominating our validator. - - // Reward the validator so we can collect for everyone in the next era. - Staking::reward_by_ids(vec![(11, 1)]); - - // Era 6 - start_active_era(6); - - // Collect payouts when the validator had `half_max_nom_rewarded` nominators. - let call = TestRuntimeCall::Staking(StakingCall::payout_stakers(11, 5)); - let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(20)); - assert_ok!(result); - assert_eq!(extract_actual_weight(&result, &info), max_nom_rewarded_weight); - - // Try and collect payouts for an era that has already been collected. - let call = TestRuntimeCall::Staking(StakingCall::payout_stakers(11, 5)); - let info = call.get_dispatch_info(); - let result = call.dispatch(Origin::signed(20)); - assert!(result.is_err()); - // When there is an error the consumed weight == weight when there are 0 nominator payouts. - assert_eq!(extract_actual_weight(&result, &info), zero_nom_payouts_weight); - }); -} - -#[test] -fn bond_during_era_correctly_populates_claimed_rewards() { - ExtBuilder::default().has_stakers(false).build_and_execute(|| { - // Era = None - bond_validator(9, 8, 1000); - assert_eq!( - Staking::ledger(&8), - Some(StakingLedger { - stash: 9, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![], - }) - ); - mock::start_active_era(5); - bond_validator(11, 10, 1000); - assert_eq!( - Staking::ledger(&10), - Some(StakingLedger { - stash: 11, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: (0..5).collect(), - }) - ); - mock::start_active_era(99); - bond_validator(13, 12, 1000); - assert_eq!( - Staking::ledger(&12), - Some(StakingLedger { - stash: 13, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: (15..99).collect(), - }) - ); - }); -} - -#[test] -fn offences_weight_calculated_correctly() { - ExtBuilder::default().nominate(true).build_and_execute(|| { - // On offence with zero offenders: 4 Reads, 1 Write - let zero_offence_weight = ::DbWeight::get().reads_writes(4, 1); - assert_eq!(Staking::on_offence(&[], &[Perbill::from_percent(50)], 0), zero_offence_weight); - - // On Offence with N offenders, Unapplied: 4 Reads, 1 Write + 4 Reads, 5 Writes - let n_offence_unapplied_weight = ::DbWeight::get().reads_writes(4, 1) - + ::DbWeight::get().reads_writes(4, 5); - - let offenders: Vec::AccountId, pallet_session::historical::IdentificationTuple>> - = (1..10).map(|i| - OffenceDetails { - offender: (i, Staking::eras_stakers(Staking::active_era().unwrap().index, i)), - reporters: vec![], - } - ).collect(); - assert_eq!(Staking::on_offence(&offenders, &[Perbill::from_percent(50)], 0), n_offence_unapplied_weight); - - // On Offence with one offenders, Applied - let one_offender = [ - OffenceDetails { - offender: (11, Staking::eras_stakers(Staking::active_era().unwrap().index, 11)), - reporters: vec![1], - }, - ]; - - let n = 1; // Number of offenders - let rw = 3 + 3 * n; // rw reads and writes - let one_offence_unapplied_weight = ::DbWeight::get().reads_writes(4, 1) - + ::DbWeight::get().reads_writes(rw, rw) - // One `slash_cost` - + ::DbWeight::get().reads_writes(6, 5) - // `slash_cost` * nominators (1) - + ::DbWeight::get().reads_writes(6, 5) - // `reward_cost` * reporters (1) - + ::DbWeight::get().reads_writes(2, 2); - - assert_eq!(Staking::on_offence(&one_offender, &[Perbill::from_percent(50)], 0), one_offence_unapplied_weight); - }); -} - -#[test] -fn payout_creates_controller() { - ExtBuilder::default().has_stakers(false).build_and_execute(|| { - let balance = 1000; - // Create a validator: - bond_validator(11, 10, balance); - - // Create a stash/controller pair - bond_nominator(1234, 1337, 100, vec![11]); - - // kill controller - assert_ok!(Balances::transfer(Origin::signed(1337), 1234, 100)); - assert_eq!(Balances::free_balance(1337), 0); - - mock::start_active_era(1); - Staking::reward_by_ids(vec![(11, 1)]); - // compute and ensure the reward amount is greater than zero. - let _ = current_total_payout_for_duration(reward_time_per_era()); - mock::start_active_era(2); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 1)); - - // Controller is created - assert!(Balances::free_balance(1337) > 0); - }) -} - -#[test] -fn payout_to_any_account_works() { - ExtBuilder::default().has_stakers(false).build_and_execute(|| { - let balance = 1000; - // Create a validator: - bond_validator(11, 10, balance); // Default(64) - - // Create a stash/controller pair - bond_nominator(1234, 1337, 100, vec![11]); - - // Update payout location - assert_ok!(Staking::set_payee(Origin::signed(1337), RewardDestination::Account(42))); - - // Reward Destination account doesn't exist - assert_eq!(Balances::free_balance(42), 0); - - mock::start_active_era(1); - Staking::reward_by_ids(vec![(11, 1)]); - // compute and ensure the reward amount is greater than zero. - let _ = current_total_payout_for_duration(reward_time_per_era()); - mock::start_active_era(2); - assert_ok!(Staking::payout_stakers(Origin::signed(1337), 11, 1)); - - // Payment is successful - assert!(Balances::free_balance(42) > 0); - }) -} - -#[test] -fn session_buffering_with_offset() { - // similar to live-chains, have some offset for the first session - ExtBuilder::default() - .offset(2) - .period(5) - .session_per_era(5) - .build_and_execute(|| { - assert_eq!(current_era(), 0); - assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 0); - - start_session(1); - assert_eq!(current_era(), 0); - assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 1); - assert_eq!(System::block_number(), 2); - - start_session(2); - assert_eq!(current_era(), 0); - assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 2); - assert_eq!(System::block_number(), 7); - - start_session(3); - assert_eq!(current_era(), 0); - assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 3); - assert_eq!(System::block_number(), 12); - - // active era is lagging behind by one session, because of how session module works. - start_session(4); - assert_eq!(current_era(), 1); - assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 4); - assert_eq!(System::block_number(), 17); - - start_session(5); - assert_eq!(current_era(), 1); - assert_eq!(active_era(), 1); - assert_eq!(Session::current_index(), 5); - assert_eq!(System::block_number(), 22); - - // go all the way to active 2. - start_active_era(2); - assert_eq!(current_era(), 2); - assert_eq!(active_era(), 2); - assert_eq!(Session::current_index(), 10); - }); -} - -#[test] -fn session_buffering_no_offset() { - // no offset, first session starts immediately - ExtBuilder::default() - .offset(0) - .period(5) - .session_per_era(5) - .build_and_execute(|| { - assert_eq!(current_era(), 0); - assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 0); - - start_session(1); - assert_eq!(current_era(), 0); - assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 1); - assert_eq!(System::block_number(), 5); - - start_session(2); - assert_eq!(current_era(), 0); - assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 2); - assert_eq!(System::block_number(), 10); - - start_session(3); - assert_eq!(current_era(), 0); - assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 3); - assert_eq!(System::block_number(), 15); - - // active era is lagging behind by one session, because of how session module works. - start_session(4); - assert_eq!(current_era(), 1); - assert_eq!(active_era(), 0); - assert_eq!(Session::current_index(), 4); - assert_eq!(System::block_number(), 20); - - start_session(5); - assert_eq!(current_era(), 1); - assert_eq!(active_era(), 1); - assert_eq!(Session::current_index(), 5); - assert_eq!(System::block_number(), 25); - - // go all the way to active 2. - start_active_era(2); - assert_eq!(current_era(), 2); - assert_eq!(active_era(), 2); - assert_eq!(Session::current_index(), 10); - }); -} - -#[test] -fn cannot_rebond_to_lower_than_ed() { - ExtBuilder::default() - .existential_deposit(10) - .min_nominator_bond(10) - .min_validator_bond(10) - .build_and_execute(|| { - // stash must have more balance than bonded for this to work. - assert_eq!(Balances::free_balance(&21), 512_000); - - // initial stuff. - assert_eq!( - Staking::ledger(&20).unwrap(), - StakingLedger { - stash: 21, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![] - } - ); - - // unbond all of it. must be chilled first. - assert_ok!(Staking::chill(Origin::signed(20))); - assert_ok!(Staking::unbond(Origin::signed(20), 1000)); - assert_eq!( - Staking::ledger(&20).unwrap(), - StakingLedger { - stash: 21, - total: 1000, - active: 0, - unlocking: vec![UnlockChunk { value: 1000, era: 3 }], - claimed_rewards: vec![] - } - ); - - // now bond a wee bit more - assert_noop!(Staking::rebond(Origin::signed(20), 5), Error::::InsufficientBond); - }) -} - -#[test] -fn cannot_bond_extra_to_lower_than_ed() { - ExtBuilder::default() - .existential_deposit(10) - .min_nominator_bond(10) - .min_validator_bond(10) - .build_and_execute(|| { - // stash must have more balance than bonded for this to work. - assert_eq!(Balances::free_balance(&21), 512_000); - - // initial stuff. - assert_eq!( - Staking::ledger(&20).unwrap(), - StakingLedger { - stash: 21, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![] - } - ); - - // unbond all of it. must be chilled first. - assert_ok!(Staking::chill(Origin::signed(20))); - assert_ok!(Staking::unbond(Origin::signed(20), 1000)); - assert_eq!( - Staking::ledger(&20).unwrap(), - StakingLedger { - stash: 21, - total: 1000, - active: 0, - unlocking: vec![UnlockChunk { value: 1000, era: 3 }], - claimed_rewards: vec![] - } - ); - - // now bond a wee bit more - assert_noop!( - Staking::bond_extra(Origin::signed(21), 5), - Error::::InsufficientBond, - ); - }) -} - -#[test] -fn do_not_die_when_active_is_ed() { - let ed = 10; - ExtBuilder::default() - .existential_deposit(ed) - .min_nominator_bond(ed) - .min_validator_bond(ed) - .build_and_execute(|| { - // initial stuff. - assert_eq!( - Staking::ledger(&20).unwrap(), - StakingLedger { - stash: 21, - total: 1000, - active: 1000, - unlocking: vec![], - claimed_rewards: vec![] - } - ); - - // unbond all of it except ed. - assert_ok!(Staking::unbond(Origin::signed(20), 1000 - ed)); - start_active_era(3); - assert_ok!(Staking::withdraw_unbonded(Origin::signed(20), 100)); - - // initial stuff. - assert_eq!( - Staking::ledger(&20).unwrap(), - StakingLedger { - stash: 21, - total: ed, - active: ed, - unlocking: vec![], - claimed_rewards: vec![] - } - ); - }) -} - -#[test] -fn on_finalize_weight_is_nonzero() { - ExtBuilder::default().build_and_execute(|| { - let on_finalize_weight = ::DbWeight::get().reads(1); - assert!(>::on_initialize(1) >= on_finalize_weight); - }) -} - -mod election_data_provider { - use super::*; - use frame_election_provider_support::ElectionDataProvider; - - #[test] - fn targets_2sec_block() { - let mut validators = 1000; - while ::WeightInfo::get_npos_targets(validators) < - 2 * frame_support::weights::constants::WEIGHT_PER_SECOND - { - validators += 1; - } - - println!("Can create a snapshot of {} validators in 2sec block", validators); - } - - #[test] - fn voters_2sec_block() { - // we assume a network only wants up to 1000 validators in most cases, thus having 2000 - // candidates is as high as it gets. - let validators = 2000; - // we assume the worse case: each validator also has a slashing span. - let slashing_spans = validators; - let mut nominators = 1000; - - while ::WeightInfo::get_npos_voters(validators, nominators, slashing_spans) < - 2 * frame_support::weights::constants::WEIGHT_PER_SECOND - { - nominators += 1; - } - - println!( - "Can create a snapshot of {} nominators [{} validators, each 1 slashing] in 2sec block", - nominators, validators - ); - } - - #[test] - fn voters_include_self_vote() { - ExtBuilder::default().nominate(false).build_and_execute(|| { - assert!(>::iter().map(|(x, _)| x).all(|v| Staking::voters(None) - .unwrap() - .0 - .into_iter() - .find(|(w, _, t)| { v == *w && t[0] == *w }) - .is_some())) - }) - } - - #[test] - fn voters_exclude_slashed() { - ExtBuilder::default().build_and_execute(|| { - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); - assert_eq!( - >::voters(None) - .unwrap() - .0 - .iter() - .find(|x| x.0 == 101) - .unwrap() - .2, - vec![11, 21] - ); - - start_active_era(1); - add_slash(&11); - - // 11 is gone. - start_active_era(2); - assert_eq!( - >::voters(None) - .unwrap() - .0 - .iter() - .find(|x| x.0 == 101) - .unwrap() - .2, - vec![21] - ); - - // resubmit and it is back - assert_ok!(Staking::nominate(Origin::signed(100), vec![11, 21])); - assert_eq!( - >::voters(None) - .unwrap() - .0 - .iter() - .find(|x| x.0 == 101) - .unwrap() - .2, - vec![11, 21] - ); - }) - } - - #[test] - fn respects_len_limits() { - ExtBuilder::default().build_and_execute(|| { - assert_eq!(Staking::voters(Some(1)).unwrap_err(), "Voter snapshot too big"); - assert_eq!(Staking::targets(Some(1)).unwrap_err(), "Target snapshot too big"); - }); - } - - #[test] - fn estimate_next_election_works() { - ExtBuilder::default().session_per_era(5).period(5).build_and_execute(|| { - // first session is always length 0. - for b in 1..20 { - run_to_block(b); - assert_eq!(Staking::next_election_prediction(System::block_number()), 20); - } - - // election - run_to_block(20); - assert_eq!(Staking::next_election_prediction(System::block_number()), 45); - assert_eq!(staking_events().len(), 1); - assert_eq!(*staking_events().last().unwrap(), Event::StakingElection); - - for b in 21..45 { - run_to_block(b); - assert_eq!(Staking::next_election_prediction(System::block_number()), 45); - } - - // election - run_to_block(45); - assert_eq!(Staking::next_election_prediction(System::block_number()), 70); - assert_eq!(staking_events().len(), 3); - assert_eq!(*staking_events().last().unwrap(), Event::StakingElection); - - Staking::force_no_eras(Origin::root()).unwrap(); - assert_eq!(Staking::next_election_prediction(System::block_number()), u64::MAX); - - Staking::force_new_era_always(Origin::root()).unwrap(); - assert_eq!(Staking::next_election_prediction(System::block_number()), 45 + 5); - - Staking::force_new_era(Origin::root()).unwrap(); - assert_eq!(Staking::next_election_prediction(System::block_number()), 45 + 5); - - // Do a fail election - MinimumValidatorCount::::put(1000); - run_to_block(50); - // Election: failed, next session is a new election - assert_eq!(Staking::next_election_prediction(System::block_number()), 50 + 5); - // The new era is still forced until a new era is planned. - assert_eq!(ForceEra::::get(), Forcing::ForceNew); - - MinimumValidatorCount::::put(2); - run_to_block(55); - assert_eq!(Staking::next_election_prediction(System::block_number()), 55 + 25); - assert_eq!(staking_events().len(), 6); - assert_eq!(*staking_events().last().unwrap(), Event::StakingElection); - // The new era has been planned, forcing is changed from `ForceNew` to `NotForcing`. - assert_eq!(ForceEra::::get(), Forcing::NotForcing); - }) - } - - #[test] - #[should_panic] - fn count_check_works() { - ExtBuilder::default().build_and_execute(|| { - // We should never insert into the validators or nominators map directly as this will - // not keep track of the count. This test should panic as we verify the count is accurate - // after every test using the `post_checks` in `mock`. - Validators::::insert(987654321, ValidatorPrefs::default()); - Nominators::::insert( - 987654321, - Nominations { - targets: vec![], - submitted_in: Default::default(), - suppressed: false, - }, - ); - }) - } - - #[test] - fn min_bond_checks_work() { - ExtBuilder::default() - .existential_deposit(100) - .min_nominator_bond(1_000) - .min_validator_bond(1_500) - .build_and_execute(|| { - // 500 is not enough for any role - assert_ok!(Staking::bond(Origin::signed(3), 4, 500, RewardDestination::Controller)); - assert_noop!( - Staking::nominate(Origin::signed(4), vec![1]), - Error::::InsufficientBond - ); - assert_noop!( - Staking::validate(Origin::signed(4), ValidatorPrefs::default()), - Error::::InsufficientBond, - ); - - // 1000 is enough for nominator - assert_ok!(Staking::bond_extra(Origin::signed(3), 500)); - assert_ok!(Staking::nominate(Origin::signed(4), vec![1])); - assert_noop!( - Staking::validate(Origin::signed(4), ValidatorPrefs::default()), - Error::::InsufficientBond, - ); - - // 1500 is enough for validator - assert_ok!(Staking::bond_extra(Origin::signed(3), 500)); - assert_ok!(Staking::nominate(Origin::signed(4), vec![1])); - assert_ok!(Staking::validate(Origin::signed(4), ValidatorPrefs::default())); - - // Can't unbond anything as validator - assert_noop!( - Staking::unbond(Origin::signed(4), 500), - Error::::InsufficientBond - ); - - // Once they are a nominator, they can unbond 500 - assert_ok!(Staking::nominate(Origin::signed(4), vec![1])); - assert_ok!(Staking::unbond(Origin::signed(4), 500)); - assert_noop!( - Staking::unbond(Origin::signed(4), 500), - Error::::InsufficientBond - ); - - // Once they are chilled they can unbond everything - assert_ok!(Staking::chill(Origin::signed(4))); - assert_ok!(Staking::unbond(Origin::signed(4), 1000)); - }) - } - - #[test] - fn chill_other_works() { - ExtBuilder::default() - .existential_deposit(100) - .min_nominator_bond(1_000) - .min_validator_bond(1_500) - .build_and_execute(|| { - for i in 0..15 { - let a = 4 * i; - let b = 4 * i + 1; - let c = 4 * i + 2; - let d = 4 * i + 3; - Balances::make_free_balance_be(&a, 100_000); - Balances::make_free_balance_be(&b, 100_000); - Balances::make_free_balance_be(&c, 100_000); - Balances::make_free_balance_be(&d, 100_000); - - // Nominator - assert_ok!(Staking::bond( - Origin::signed(a), - b, - 1000, - RewardDestination::Controller - )); - assert_ok!(Staking::nominate(Origin::signed(b), vec![1])); - - // Validator - assert_ok!(Staking::bond( - Origin::signed(c), - d, - 1500, - RewardDestination::Controller - )); - assert_ok!(Staking::validate(Origin::signed(d), ValidatorPrefs::default())); - } - - // To chill other users, we need to: - // * Set a minimum bond amount - // * Set a limit - // * Set a threshold - // - // If any of these are missing, we do not have enough information to allow the - // `chill_other` to succeed from one user to another. - - // Can't chill these users - assert_noop!( - Staking::chill_other(Origin::signed(1337), 1), - Error::::CannotChillOther - ); - assert_noop!( - Staking::chill_other(Origin::signed(1337), 3), - Error::::CannotChillOther - ); - - // Change the minimum bond... but no limits. - assert_ok!(Staking::set_staking_limits( - Origin::root(), - 1_500, - 2_000, - None, - None, - None - )); - - // Still can't chill these users - assert_noop!( - Staking::chill_other(Origin::signed(1337), 1), - Error::::CannotChillOther - ); - assert_noop!( - Staking::chill_other(Origin::signed(1337), 3), - Error::::CannotChillOther - ); - - // Add limits, but no threshold - assert_ok!(Staking::set_staking_limits( - Origin::root(), - 1_500, - 2_000, - Some(10), - Some(10), - None - )); - - // Still can't chill these users - assert_noop!( - Staking::chill_other(Origin::signed(1337), 1), - Error::::CannotChillOther - ); - assert_noop!( - Staking::chill_other(Origin::signed(1337), 3), - Error::::CannotChillOther - ); - - // Add threshold, but no limits - assert_ok!(Staking::set_staking_limits( - Origin::root(), - 1_500, - 2_000, - None, - None, - Some(Percent::from_percent(0)) - )); - - // Still can't chill these users - assert_noop!( - Staking::chill_other(Origin::signed(1337), 1), - Error::::CannotChillOther - ); - assert_noop!( - Staking::chill_other(Origin::signed(1337), 3), - Error::::CannotChillOther - ); - - // Add threshold and limits - assert_ok!(Staking::set_staking_limits( - Origin::root(), - 1_500, - 2_000, - Some(10), - Some(10), - Some(Percent::from_percent(75)) - )); - - // 16 people total because tests start with 1 active one - assert_eq!(CounterForNominators::::get(), 16); - assert_eq!(CounterForValidators::::get(), 16); - - // Users can now be chilled down to 7 people, so we try to remove 9 of them (starting with 16) - for i in 6..15 { - let b = 4 * i + 1; - let d = 4 * i + 3; - assert_ok!(Staking::chill_other(Origin::signed(1337), b)); - assert_ok!(Staking::chill_other(Origin::signed(1337), d)); - } - - // Cant go lower. - assert_noop!( - Staking::chill_other(Origin::signed(1337), 1), - Error::::CannotChillOther - ); - assert_noop!( - Staking::chill_other(Origin::signed(1337), 3), - Error::::CannotChillOther - ); - }) - } - - #[test] - fn capped_stakers_works() { - ExtBuilder::default().build_and_execute(|| { - let validator_count = CounterForValidators::::get(); - assert_eq!(validator_count, 3); - let nominator_count = CounterForNominators::::get(); - assert_eq!(nominator_count, 1); - - // Change the maximums - let max = 10; - assert_ok!(Staking::set_staking_limits( - Origin::root(), - 10, - 10, - Some(max), - Some(max), - Some(Percent::from_percent(0)) - )); - - // can create `max - validator_count` validators - let mut some_existing_validator = AccountId::default(); - for i in 0..max - validator_count { - let (_, controller) = testing_utils::create_stash_controller::( - i + 10_000_000, - 100, - RewardDestination::Controller, - ) - .unwrap(); - assert_ok!(Staking::validate( - Origin::signed(controller), - ValidatorPrefs::default() - )); - some_existing_validator = controller; - } - - // but no more - let (_, last_validator) = testing_utils::create_stash_controller::( - 1337, - 100, - RewardDestination::Controller, - ) - .unwrap(); - - assert_noop!( - Staking::validate(Origin::signed(last_validator), ValidatorPrefs::default()), - Error::::TooManyValidators, - ); - - // same with nominators - let mut some_existing_nominator = AccountId::default(); - for i in 0..max - nominator_count { - let (_, controller) = testing_utils::create_stash_controller::( - i + 20_000_000, - 100, - RewardDestination::Controller, - ) - .unwrap(); - assert_ok!(Staking::nominate(Origin::signed(controller), vec![1])); - some_existing_nominator = controller; - } - - // one more is too many - let (_, last_nominator) = testing_utils::create_stash_controller::( - 30_000_000, - 100, - RewardDestination::Controller, - ) - .unwrap(); - assert_noop!( - Staking::nominate(Origin::signed(last_nominator), vec![1]), - Error::::TooManyNominators - ); - - // Re-nominate works fine - assert_ok!(Staking::nominate(Origin::signed(some_existing_nominator), vec![1])); - // Re-validate works fine - assert_ok!(Staking::validate( - Origin::signed(some_existing_validator), - ValidatorPrefs::default() - )); - - // No problem when we set to `None` again - assert_ok!(Staking::set_staking_limits(Origin::root(), 10, 10, None, None, None)); - assert_ok!(Staking::nominate(Origin::signed(last_nominator), vec![1])); - assert_ok!(Staking::validate( - Origin::signed(last_validator), - ValidatorPrefs::default() - )); - }) - } -} diff --git a/lib-serml/serp/serp-staking/src/weights.rs b/lib-serml/serp/serp-staking/src/weights.rs deleted file mode 100644 index 5ca1f2245..000000000 --- a/lib-serml/serp/serp-staking/src/weights.rs +++ /dev/null @@ -1,453 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2021 Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Autogenerated weights for serp_staking -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 -//! DATE: 2021-06-19, STEPS: `[50, ]`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128 - -// Executed Command: -// target/release/substrate -// benchmark -// --chain=dev -// --steps=50 -// --repeat=20 -// --pallet=serp_staking -// --extrinsic=* -// --execution=wasm -// --wasm-execution=compiled -// --heap-pages=4096 -// --output=./frame/staking/src/weights.rs -// --template=./.maintain/frame-weight-template.hbs - - -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] - -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; -use sp_std::marker::PhantomData; - -/// Weight functions needed for serp_staking. -pub trait WeightInfo { - fn bond() -> Weight; - fn bond_extra() -> Weight; - fn unbond() -> Weight; - fn withdraw_unbonded_update(s: u32, ) -> Weight; - fn withdraw_unbonded_kill(s: u32, ) -> Weight; - fn validate() -> Weight; - fn kick(k: u32, ) -> Weight; - fn nominate(n: u32, ) -> Weight; - fn chill() -> Weight; - fn set_payee() -> Weight; - fn set_controller() -> Weight; - fn set_validator_count() -> Weight; - fn force_no_eras() -> Weight; - fn force_new_era() -> Weight; - fn force_new_era_always() -> Weight; - fn set_invulnerables(v: u32, ) -> Weight; - fn force_unstake(s: u32, ) -> Weight; - fn cancel_deferred_slash(s: u32, ) -> Weight; - fn payout_stakers_dead_controller(n: u32, ) -> Weight; - fn payout_stakers_alive_staked(n: u32, ) -> Weight; - fn rebond(l: u32, ) -> Weight; - fn set_history_depth(e: u32, ) -> Weight; - fn reap_stash(s: u32, ) -> Weight; - fn new_era(v: u32, n: u32, ) -> Weight; - fn get_npos_voters(v: u32, n: u32, s: u32, ) -> Weight; - fn get_npos_targets(v: u32, ) -> Weight; - fn set_staking_limits() -> Weight; - fn chill_other() -> Weight; -} - -/// Weights for serp_staking using the Substrate node and recommended hardware. -pub struct SubstrateWeight(PhantomData); -impl WeightInfo for SubstrateWeight { - fn bond() -> Weight { - (72_617_000 as Weight) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - fn bond_extra() -> Weight { - (55_590_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - fn unbond() -> Weight { - (59_730_000 as Weight) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - fn withdraw_unbonded_update(s: u32, ) -> Weight { - (52_279_000 as Weight) - // Standard Error: 0 - .saturating_add((68_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - fn withdraw_unbonded_kill(s: u32, ) -> Weight { - (86_629_000 as Weight) - // Standard Error: 1_000 - .saturating_add((2_379_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(8 as Weight)) - .saturating_add(T::DbWeight::get().writes(6 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - fn validate() -> Weight { - (32_393_000 as Weight) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - fn kick(k: u32, ) -> Weight { - (36_986_000 as Weight) - // Standard Error: 13_000 - .saturating_add((16_574_000 as Weight).saturating_mul(k as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(k as Weight))) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(k as Weight))) - } - fn nominate(n: u32, ) -> Weight { - (43_228_000 as Weight) - // Standard Error: 21_000 - .saturating_add((5_119_000 as Weight).saturating_mul(n as Weight)) - .saturating_add(T::DbWeight::get().reads(7 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(n as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } - fn chill() -> Weight { - (17_800_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - } - fn set_payee() -> Weight { - (12_612_000 as Weight) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn set_controller() -> Weight { - (27_503_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - fn set_validator_count() -> Weight { - (2_119_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn force_no_eras() -> Weight { - (2_320_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn force_new_era() -> Weight { - (2_269_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn force_new_era_always() -> Weight { - (2_334_000 as Weight) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn set_invulnerables(v: u32, ) -> Weight { - (2_354_000 as Weight) - // Standard Error: 0 - .saturating_add((5_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn force_unstake(s: u32, ) -> Weight { - (61_556_000 as Weight) - // Standard Error: 1_000 - .saturating_add((2_377_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(6 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - fn cancel_deferred_slash(s: u32, ) -> Weight { - (3_367_105_000 as Weight) - // Standard Error: 222_000 - .saturating_add((19_817_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) - } - fn payout_stakers_dead_controller(n: u32, ) -> Weight { - (47_229_000 as Weight) - // Standard Error: 53_000 - .saturating_add((48_365_000 as Weight).saturating_mul(n as Weight)) - .saturating_add(T::DbWeight::get().reads(10 as Weight)) - .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(n as Weight))) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(n as Weight))) - } - fn payout_stakers_alive_staked(n: u32, ) -> Weight { - (156_788_000 as Weight) - // Standard Error: 20_000 - .saturating_add((61_280_000 as Weight).saturating_mul(n as Weight)) - .saturating_add(T::DbWeight::get().reads(11 as Weight)) - .saturating_add(T::DbWeight::get().reads((5 as Weight).saturating_mul(n as Weight))) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(n as Weight))) - } - fn rebond(l: u32, ) -> Weight { - (47_815_000 as Weight) - // Standard Error: 1_000 - .saturating_add((65_000 as Weight).saturating_mul(l as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) - } - fn set_history_depth(e: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 74_000 - .saturating_add((34_945_000 as Weight).saturating_mul(e as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - .saturating_add(T::DbWeight::get().writes((7 as Weight).saturating_mul(e as Weight))) - } - fn reap_stash(s: u32, ) -> Weight { - (73_483_000 as Weight) - // Standard Error: 0 - .saturating_add((2_384_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(7 as Weight)) - .saturating_add(T::DbWeight::get().writes(8 as Weight)) - .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - fn new_era(v: u32, n: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 846_000 - .saturating_add((305_234_000 as Weight).saturating_mul(v as Weight)) - // Standard Error: 42_000 - .saturating_add((48_280_000 as Weight).saturating_mul(n as Weight)) - .saturating_add(T::DbWeight::get().reads(10 as Weight)) - .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(v as Weight))) - .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(n as Weight))) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(v as Weight))) - } - fn get_npos_voters(v: u32, n: u32, s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 99_000 - .saturating_add((25_735_000 as Weight).saturating_mul(v as Weight)) - // Standard Error: 99_000 - .saturating_add((28_122_000 as Weight).saturating_mul(n as Weight)) - // Standard Error: 3_388_000 - .saturating_add((21_500_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(v as Weight))) - .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(n as Weight))) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - } - fn get_npos_targets(v: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 30_000 - .saturating_add((11_065_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(T::DbWeight::get().reads(1 as Weight)) - .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(v as Weight))) - } - fn set_staking_limits() -> Weight { - (5_028_000 as Weight) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) - } - fn chill_other() -> Weight { - (35_758_000 as Weight) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) - } -} - -// For backwards compatibility and tests -impl WeightInfo for () { - fn bond() -> Weight { - (72_617_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - fn bond_extra() -> Weight { - (55_590_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - fn unbond() -> Weight { - (59_730_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - fn withdraw_unbonded_update(s: u32, ) -> Weight { - (52_279_000 as Weight) - // Standard Error: 0 - .saturating_add((68_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - fn withdraw_unbonded_kill(s: u32, ) -> Weight { - (86_629_000 as Weight) - // Standard Error: 1_000 - .saturating_add((2_379_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(8 as Weight)) - .saturating_add(RocksDbWeight::get().writes(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - fn validate() -> Weight { - (32_393_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - fn kick(k: u32, ) -> Weight { - (36_986_000 as Weight) - // Standard Error: 13_000 - .saturating_add((16_574_000 as Weight).saturating_mul(k as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(k as Weight))) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(k as Weight))) - } - fn nominate(n: u32, ) -> Weight { - (43_228_000 as Weight) - // Standard Error: 21_000 - .saturating_add((5_119_000 as Weight).saturating_mul(n as Weight)) - .saturating_add(RocksDbWeight::get().reads(7 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(n as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } - fn chill() -> Weight { - (17_800_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - } - fn set_payee() -> Weight { - (12_612_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn set_controller() -> Weight { - (27_503_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - fn set_validator_count() -> Weight { - (2_119_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn force_no_eras() -> Weight { - (2_320_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn force_new_era() -> Weight { - (2_269_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn force_new_era_always() -> Weight { - (2_334_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn set_invulnerables(v: u32, ) -> Weight { - (2_354_000 as Weight) - // Standard Error: 0 - .saturating_add((5_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn force_unstake(s: u32, ) -> Weight { - (61_556_000 as Weight) - // Standard Error: 1_000 - .saturating_add((2_377_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - fn cancel_deferred_slash(s: u32, ) -> Weight { - (3_367_105_000 as Weight) - // Standard Error: 222_000 - .saturating_add((19_817_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) - } - fn payout_stakers_dead_controller(n: u32, ) -> Weight { - (47_229_000 as Weight) - // Standard Error: 53_000 - .saturating_add((48_365_000 as Weight).saturating_mul(n as Weight)) - .saturating_add(RocksDbWeight::get().reads(10 as Weight)) - .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(n as Weight))) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(n as Weight))) - } - fn payout_stakers_alive_staked(n: u32, ) -> Weight { - (156_788_000 as Weight) - // Standard Error: 20_000 - .saturating_add((61_280_000 as Weight).saturating_mul(n as Weight)) - .saturating_add(RocksDbWeight::get().reads(11 as Weight)) - .saturating_add(RocksDbWeight::get().reads((5 as Weight).saturating_mul(n as Weight))) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(n as Weight))) - } - fn rebond(l: u32, ) -> Weight { - (47_815_000 as Weight) - // Standard Error: 1_000 - .saturating_add((65_000 as Weight).saturating_mul(l as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) - } - fn set_history_depth(e: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 74_000 - .saturating_add((34_945_000 as Weight).saturating_mul(e as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes((7 as Weight).saturating_mul(e as Weight))) - } - fn reap_stash(s: u32, ) -> Weight { - (73_483_000 as Weight) - // Standard Error: 0 - .saturating_add((2_384_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(7 as Weight)) - .saturating_add(RocksDbWeight::get().writes(8 as Weight)) - .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight))) - } - fn new_era(v: u32, n: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 846_000 - .saturating_add((305_234_000 as Weight).saturating_mul(v as Weight)) - // Standard Error: 42_000 - .saturating_add((48_280_000 as Weight).saturating_mul(n as Weight)) - .saturating_add(RocksDbWeight::get().reads(10 as Weight)) - .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(v as Weight))) - .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(n as Weight))) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(v as Weight))) - } - fn get_npos_voters(v: u32, n: u32, s: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 99_000 - .saturating_add((25_735_000 as Weight).saturating_mul(v as Weight)) - // Standard Error: 99_000 - .saturating_add((28_122_000 as Weight).saturating_mul(n as Weight)) - // Standard Error: 3_388_000 - .saturating_add((21_500_000 as Weight).saturating_mul(s as Weight)) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(v as Weight))) - .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(n as Weight))) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight))) - } - fn get_npos_targets(v: u32, ) -> Weight { - (0 as Weight) - // Standard Error: 30_000 - .saturating_add((11_065_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(RocksDbWeight::get().reads(1 as Weight)) - .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(v as Weight))) - } - fn set_staking_limits() -> Weight { - (5_028_000 as Weight) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) - } - fn chill_other() -> Weight { - (35_758_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) - } -} From b49fe340967eac6935542a44b9a7c80bf24ab0d0 Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Tue, 31 Aug 2021 19:22:00 +0800 Subject: [PATCH 02/22] UPDATE TP --- lib-serml/transaction-payment/Cargo.toml | 8 +- lib-serml/transaction-payment/src/lib.rs | 165 ++++++++++-------- lib-serml/transaction-payment/src/mock.rs | 167 +++++++++++++++++-- lib-serml/transaction-payment/src/tests.rs | 145 ++++++++++++---- lib-serml/transaction-payment/src/weights.rs | 6 +- 5 files changed, 363 insertions(+), 128 deletions(-) diff --git a/lib-serml/transaction-payment/Cargo.toml b/lib-serml/transaction-payment/Cargo.toml index 24ea7f3e4..fa853df18 100644 --- a/lib-serml/transaction-payment/Cargo.toml +++ b/lib-serml/transaction-payment/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "setheum-transaction-payment" -version = "0.9.0" +version = "0.8.0" authors = ["Setheum Labs"] edition = "2018" @@ -28,9 +28,9 @@ support = { package = "setheum-support", path = "../support", default-features = [dev-dependencies] sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -orml-tokens = { path = "../../lib-openrml/tokens", default-features = false } -setheum-currencies = { path = "../../lib-serml/tokens/currencies", default-features = false } -setheum-dex = { path = "../dex/dex", default-features = false } +orml-tokens = { path = "../../lib-openrml/tokens" } +setheum-currencies = { path = "../../lib-serml/tokens/currencies" } +setheum-dex = { path = "../dex/dex" } smallvec = "1.4.1" [features] diff --git a/lib-serml/transaction-payment/src/lib.rs b/lib-serml/transaction-payment/src/lib.rs index 3869473c1..22a862267 100644 --- a/lib-serml/transaction-payment/src/lib.rs +++ b/lib-serml/transaction-payment/src/lib.rs @@ -33,6 +33,7 @@ use frame_support::{ Currency, ExistenceRequirement, Imbalance, NamedReservableCurrency, OnUnbalanced, SameOrOther, WithdrawReasons, }, weights::{DispatchInfo, GetDispatchInfo, Pays, PostDispatchInfo, WeightToFeeCoefficient, WeightToFeePolynomial}, + BoundedVec, }; use frame_system::pallet_prelude::*; use orml_traits::MultiCurrency; @@ -41,16 +42,16 @@ use pallet_transaction_payment_rpc_runtime_api::{FeeDetails, InclusionFee}; use primitives::{Balance, CurrencyId, ReserveIdentifier}; use sp_runtime::{ traits::{ - CheckedSub, Convert, DispatchInfoOf, PostDispatchInfoOf, SaturatedConversion, Saturating, SignedExtension, - UniqueSaturatedInto, Zero, + Bounded, CheckedSub, Convert, DispatchInfoOf, One, PostDispatchInfoOf, SaturatedConversion, Saturating, + SignedExtension, UniqueSaturatedInto, Zero, }, transaction_validity::{ InvalidTransaction, TransactionPriority, TransactionValidity, TransactionValidityError, ValidTransaction, }, FixedPointNumber, FixedPointOperand, FixedU128, Perquintill, }; -use sp_std::{prelude::*, vec}; -use support::{DEXManager, Ratio, TransactionPayment}; +use sp_std::{convert::TryInto, prelude::*, vec}; +use support::{DEXManager, PriceProvider, Ratio, TransactionPayment}; mod mock; mod tests; @@ -219,18 +220,14 @@ pub mod module { #[pallet::config] pub trait Config: frame_system::Config { - /// All non-native currency ids in Setheum. - #[pallet::constant] - type AllNonNativeCurrencyIds: Get>; - /// Native currency id, the actual received currency type as fee for - /// treasury. Should be DNAR + /// treasury. Should be ACA #[pallet::constant] type NativeCurrencyId: Get; - /// Setter currency id, should be SETR + /// Default fee swap path list #[pallet::constant] - type SetterCurrencyId: Get; + type DefaultFeeSwapPathList: Get>>; /// The currency type in which fees will be paid. type Currency: Currency @@ -261,9 +258,16 @@ pub mod module { /// DEX to exchange currencies. type DEX: DEXManager; - /// The max slippage allowed when swap fee with DEX + /// When swap with DEX, the acceptable max slippage for the price from oracle. #[pallet::constant] - type MaxSlippageSwapWithDEX: Get; + type MaxSwapSlippageCompareToOracle: Get; + + /// The limit for length of trading path + #[pallet::constant] + type TradingPathLimit: Get; + + /// The price source to provider external market price. + type PriceSource: PriceProvider; /// Weight information for the extrinsics in this module. type WeightInfo: WeightInfo; @@ -284,6 +288,12 @@ pub mod module { Multiplier::saturating_from_integer(1) } + #[pallet::error] + pub enum Error { + /// The swap path is invalid + InvalidSwapPath, + } + /// The next fee multiplier. /// /// NextFeeMultiplier: Multiplier @@ -291,12 +301,11 @@ pub mod module { #[pallet::getter(fn next_fee_multiplier)] pub type NextFeeMultiplier = StorageValue<_, Multiplier, ValueQuery, DefaultFeeMultiplier>; - /// The default fee currency for accounts. - /// - /// DefaultFeeCurrencyId: AccountId => Option + /// The alternative fee swap path of accounts. #[pallet::storage] - #[pallet::getter(fn default_fee_currency_id)] - pub type DefaultFeeCurrencyId = StorageMap<_, Twox64Concat, T::AccountId, CurrencyId, OptionQuery>; + #[pallet::getter(fn alternative_fee_swap_path)] + pub type AlternativeFeeSwapPath = + StorageMap<_, Twox64Concat, T::AccountId, BoundedVec, OptionQuery>; #[pallet::pallet] pub struct Pallet(_); @@ -359,15 +368,26 @@ pub mod module { #[pallet::call] impl Pallet { - #[pallet::weight(::WeightInfo::set_default_fee_token())] - /// Set default fee token - pub fn set_default_fee_token(origin: OriginFor, fee_token: Option) -> DispatchResult { + /// Set fee swap path + #[pallet::weight(::WeightInfo::set_alternative_fee_swap_path())] + pub fn set_alternative_fee_swap_path( + origin: OriginFor, + fee_swap_path: Option>, + ) -> DispatchResult { let who = ensure_signed(origin)?; - if let Some(currency_id) = fee_token { - DefaultFeeCurrencyId::::insert(&who, currency_id); + if let Some(path) = fee_swap_path { + let path: BoundedVec = + path.try_into().map_err(|_| Error::::InvalidSwapPath)?; + ensure!( + path.len() > 1 + && path[0] != T::NativeCurrencyId::get() + && path[path.len() - 1] == T::NativeCurrencyId::get(), + Error::::InvalidSwapPath + ); + AlternativeFeeSwapPath::::insert(&who, &path); } else { - DefaultFeeCurrencyId::::remove(&who); + AlternativeFeeSwapPath::::remove(&who); } Ok(()) } @@ -552,59 +572,62 @@ where } pub fn ensure_can_charge_fee(who: &T::AccountId, fee: PalletBalanceOf, reason: WithdrawReasons) { - let native_currency_id = T::NativeCurrencyId::get(); - let setter_currency_id = T::SetterCurrencyId::get(); - let other_currency_ids = T::AllNonNativeCurrencyIds::get(); - let mut charge_fee_order: Vec = - if let Some(default_fee_currency_id) = DefaultFeeCurrencyId::::get(who) { - vec![vec![default_fee_currency_id, native_currency_id], other_currency_ids].concat() - } else { - vec![vec![native_currency_id], other_currency_ids].concat() - }; - charge_fee_order.dedup(); - - let price_impact_limit = Some(T::MaxSlippageSwapWithDEX::get()); let native_existential_deposit = ::Currency::minimum_balance(); let total_native = ::Currency::total_balance(who); - // add the gap amount to keep account alive and have enough fee - let fee_and_alive_gap = if total_native < native_existential_deposit { - fee.saturating_add(native_existential_deposit.saturating_sub(total_native)) - } else { - fee - }; - // iterator charge fee order to get enough fee - for currency_id in charge_fee_order { - if currency_id == native_currency_id { - // check native balance if is enough - let native_is_enough = ::Currency::free_balance(who) - .checked_sub(&fee_and_alive_gap) - .map_or(false, |new_free_balance| { - ::Currency::ensure_can_withdraw(who, fee, reason, new_free_balance).is_ok() - }); - if native_is_enough { - // native balance is enough, break iteration - break; - } - } else { - // try to use non-native currency to swap native currency by exchange with DEX - let trading_path = if currency_id == setter_currency_id { - vec![setter_currency_id, native_currency_id] + // check native balance if is enough + let native_is_enough = fee.saturating_add(native_existential_deposit) <= total_native + && ::Currency::free_balance(who) + .checked_sub(&fee) + .map_or(false, |new_free_balance| { + ::Currency::ensure_can_withdraw(who, fee, reason, new_free_balance).is_ok() + }); + + // native is not enough, try swap native to pay fee and gap + if !native_is_enough { + // add extra gap to keep alive after swap + let amount = fee.saturating_add(native_existential_deposit.saturating_sub(total_native)); + let native_currency_id = T::NativeCurrencyId::get(); + let default_fee_swap_path_list = T::DefaultFeeSwapPathList::get(); + let fee_swap_path_list: Vec> = + if let Some(trading_path) = AlternativeFeeSwapPath::::get(who) { + vec![vec![trading_path.into_inner()], default_fee_swap_path_list].concat() } else { - vec![currency_id, setter_currency_id, native_currency_id] + default_fee_swap_path_list }; - if T::DEX::swap_with_exact_target( - who, - &trading_path, - fee_and_alive_gap.unique_saturated_into(), - ::MultiCurrency::free_balance(currency_id, who), - price_impact_limit, - ) - .is_ok() - { - // successfully swap, break iteration - break; + for trading_path in fee_swap_path_list { + match trading_path.last() { + Some(target_currency_id) if *target_currency_id == native_currency_id => { + let supply_currency_id = *trading_path.first().expect("these's first guaranteed by match"); + // calculate the supply limit according to oracle price and the slippage limit, + // if oracle price is not avalible, do not limit + let max_supply_limit = if let Some(target_price) = + T::PriceSource::get_relative_price(*target_currency_id, supply_currency_id) + { + Ratio::one() + .saturating_sub(T::MaxSwapSlippageCompareToOracle::get()) + .reciprocal() + .unwrap_or_else(Ratio::max_value) + .saturating_mul_int(target_price.saturating_mul_int(amount)) + } else { + PalletBalanceOf::::max_value() + }; + + if T::DEX::swap_with_exact_target( + who, + &trading_path, + amount.unique_saturated_into(), + ::MultiCurrency::free_balance(supply_currency_id, who) + .min(max_supply_limit.unique_saturated_into()), + ) + .is_ok() + { + // successfully swap, break iteration + break; + } + } + _ => {} } } } diff --git a/lib-serml/transaction-payment/src/mock.rs b/lib-serml/transaction-payment/src/mock.rs index 061ee28e9..063492ea4 100644 --- a/lib-serml/transaction-payment/src/mock.rs +++ b/lib-serml/transaction-payment/src/mock.rs @@ -29,13 +29,9 @@ use orml_traits::parameter_type_with_key; use primitives::{Amount, ReserveIdentifier, TokenSymbol, TradingPair}; use smallvec::smallvec; use sp_core::{crypto::AccountId32, H256}; -use sp_runtime::{ - testing::Header, - traits::{IdentityLookup, One}, - Perbill, -}; +use sp_runtime::{testing::Header, traits::IdentityLookup, Perbill}; use sp_std::cell::RefCell; -use support::{mocks::MockAddressMapping, Ratio}; +use support::{mocks::MockAddressMapping, Price, PriceProvider, SerpTreasury}; pub type AccountId = AccountId32; pub type BlockNumber = u64; @@ -45,7 +41,7 @@ pub const BOB: AccountId = AccountId::new([2u8; 32]); pub const CHARLIE: AccountId = AccountId::new([3u8; 32]); pub const DNAR: CurrencyId = CurrencyId::Token(TokenSymbol::DNAR); pub const SETR: CurrencyId = CurrencyId::Token(TokenSymbol::SETR); -pub const DOT: CurrencyId = CurrencyId::Token(TokenSymbol::DOT); +pub const DRAM: CurrencyId = CurrencyId::Token(TokenSymbol::DRAM); parameter_types! { pub const BlockHashCount: u64 = 250; @@ -134,8 +130,123 @@ parameter_types! { pub const GetNativeCurrencyId: CurrencyId = DNAR; } +pub struct MockSerpTreasury; +impl SerpTreasury for MockSerpTreasury { + type Balance = Balance; + type CurrencyId = CurrencyId; + + /// SerpUp ratio for BuyBack Swaps to burn Dinar + fn get_buyback_serpup( + _amount: Balance, + _currency_id: CurrencyId, + ) -> DispatchResult { + unimplemented!() + } + + /// SerpUp ratio for Setheum Foundation's Charity Fund + fn get_charity_fund_serpup( + _amount: Balance, + _currency_id: CurrencyId + ) -> DispatchResult { + unimplemented!() + } + + /// SerpUp ratio for SettPay Cashdrops + fn get_cashdrop_serpup( + _amount: Balance, + _currency_id: CurrencyId + ) -> DispatchResult { + unimplemented!() + } + + /// Reward SETR cashdrop to vault + fn setter_cashdrop_to_vault() -> DispatchResult { + unimplemented!() + } + + /// Reward SETUSD cashdrop to vault + fn usdj_cashdrop_to_vault() -> DispatchResult { + unimplemented!() + } + + /// issue serpup surplus(stable currencies) to their destinations according to the serpup_ratio. + fn on_serpup( + _currency_id: CurrencyId, + _amount: Balance, + ) -> DispatchResult { + unimplemented!() + } + + /// buy back and burn surplus(stable currencies) with swap by DEX. + fn on_serpdown( + _currency_id: CurrencyId, + _amount: Balance, + ) -> DispatchResult { + unimplemented!() + } + + /// get the minimum supply of a setcurrency - by key + fn get_minimum_supply( + _currency_id: CurrencyId + ) -> Balance { + unimplemented!() + } + + /// issue standard to `who` + fn issue_standard( + _currency_id: CurrencyId, + _who: &AccountId, + _standard: Balance + ) -> DispatchResult { + unimplemented!() + } + + /// burn standard(stable currency) of `who` + fn burn_standard( + _currency_id: CurrencyId, + _who: &AccountId, + _standard: Balance + ) -> DispatchResult { + unimplemented!() + } + + /// issue setter of amount setter to `who` + fn issue_setter( + _who: &AccountId, + _setter: Balance + ) -> DispatchResult { + unimplemented!() + } + + /// burn setter of `who` + fn burn_setter( + _who: &AccountId, + _setter: Balance + ) -> DispatchResult { + unimplemented!() + } + + /// deposit reserve asset (Setter (SETR)) to serp treasury by `who` + fn deposit_setter( + _from: &AccountId, + _amount: Balance + ) -> DispatchResult { + unimplemented!() + } + + /// claim cashdrop of `currency_id` relative to `transfer_amount` for `who` + fn claim_cashdrop( + _currency_id: CurrencyId, + _who: &AccountId, + _transfer_amount: Balance + ) -> DispatchResult { + unimplemented!() + } +} + impl setheum_currencies::Config for Runtime { type Event = Event; + type SerpTreasury = MockSerpTreasury; type MultiCurrency = Tokens; type NativeCurrency = AdaptedBasicCurrency; type GetNativeCurrencyId = GetNativeCurrencyId; @@ -154,7 +265,7 @@ parameter_types! { pub const TradingPathLimit: u32 = 3; pub EnabledTradingPairs: Vec = vec![ TradingPair::from_currency_ids(SETR, DNAR).unwrap(), - TradingPair::from_currency_ids(SETR, DOT).unwrap(), + TradingPair::from_currency_ids(SETR, DRAM).unwrap(), ]; } @@ -170,10 +281,9 @@ impl setheum_dex::Config for Runtime { } parameter_types! { - pub AllNonNativeCurrencyIds: Vec = vec![SETR, DOT]; - pub MaxSlippageSwapWithDEX: Ratio = Ratio::one(); - pub const SetterCurrencyId: CurrencyId = SETR; + pub MaxSwapSlippageCompareToOracle: Ratio = Ratio::saturating_from_rational(1, 2); pub static TransactionByteFee: u128 = 1; + pub DefaultFeeSwapPathList: Vec> = vec![vec![SETR, DNAR], vec![DRAM, SETR, DNAR]]; } thread_local! { @@ -193,18 +303,43 @@ impl OnUnbalanced> for DealWithFees } } +thread_local! { + static RELATIVE_PRICE: RefCell> = RefCell::new(Some(Price::one())); +} + +pub struct MockPriceSource; +impl MockPriceSource { + pub fn set_relative_price(price: Option) { + RELATIVE_PRICE.with(|v| *v.borrow_mut() = price); + } +} +impl PriceProvider for MockPriceSource { + fn get_relative_price(_base: CurrencyId, _quote: CurrencyId) -> Option { + RELATIVE_PRICE.with(|v| *v.borrow_mut()) + } + + fn get_price(_currency_id: CurrencyId) -> Option { + unimplemented!() + } + + fn lock_price(_currency_id: CurrencyId) {} + + fn unlock_price(_currency_id: CurrencyId) {} +} + impl Config for Runtime { - type AllNonNativeCurrencyIds = AllNonNativeCurrencyIds; type NativeCurrencyId = GetNativeCurrencyId; - type SetterCurrencyId = SetterCurrencyId; + type DefaultFeeSwapPathList = DefaultFeeSwapPathList; type Currency = PalletBalances; type MultiCurrency = Currencies; type OnTransactionPayment = DealWithFees; type TransactionByteFee = TransactionByteFee; type WeightToFee = WeightToFee; type FeeMultiplierUpdate = (); - type DEX = DEXModule; - type MaxSlippageSwapWithDEX = MaxSlippageSwapWithDEX; + type DEX = SetheumDEX; + type MaxSwapSlippageCompareToOracle = MaxSwapSlippageCompareToOracle; + type TradingPathLimit = TradingPathLimit; + type PriceSource = MockPriceSource; type WeightInfo = (); } @@ -255,7 +390,7 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { Self { - balances: vec![(ALICE, SETR, 10000), (ALICE, DOT, 1000)], + balances: vec![(ALICE, SETR, 10000), (ALICE, DRAM, 1000)], base_weight: 0, byte_fee: 2, weight_to_fee: 1, diff --git a/lib-serml/transaction-payment/src/tests.rs b/lib-serml/transaction-payment/src/tests.rs index 8538bf934..6cff15739 100644 --- a/lib-serml/transaction-payment/src/tests.rs +++ b/lib-serml/transaction-payment/src/tests.rs @@ -26,17 +26,18 @@ use frame_support::{ weights::{DispatchClass, DispatchInfo, Pays}, }; use mock::{ - AccountId, BlockWeights, Call, Currencies, SetheumDEX, ExtBuilder, Origin, Runtime, TransactionPayment, DNAR, ALICE, - SETR, BOB, CHARLIE, DOT, FEE_UNBALANCED_AMOUNT, TIP_UNBALANCED_AMOUNT, + AccountId, BlockWeights, Call, Currencies, SetheumDEX, ExtBuilder, MockPriceSource, Origin, Runtime, + TransactionPayment, DNAR, ALICE, SETR, BOB, CHARLIE, DRAM, FEE_UNBALANCED_AMOUNT, TIP_UNBALANCED_AMOUNT, }; use orml_traits::MultiCurrency; use sp_runtime::{testing::TestXt, traits::One}; +use support::Price; const CALL: &::Call = - &Call::Currencies(setheum_currencies::Call::transfer(BOB, SETR, 12)); + &Call::Currencies(setheum_currencies::Call::transfer(BOB, SETR, 12, false)); const CALL2: &::Call = - &Call::Currencies(setheum_currencies::Call::transfer_native_currency(BOB, 12)); + &Call::Currencies(setheum_currencies::Call::transfer_native_currency(BOB, 12, false)); const INFO: DispatchInfo = DispatchInfo { weight: 1000, @@ -56,10 +57,10 @@ fn charges_fee_when_native_is_enough_but_cannot_keep_alive() { assert_ok!(Currencies::update_balance( Origin::root(), ALICE, - SETR, + DNAR, fee.unique_saturated_into(), )); - assert_eq!(Currencies::free_balance(SETR, &ALICE), fee); + assert_eq!(Currencies::free_balance(DNAR, &ALICE), fee); assert_noop!( ChargeTransactionPayment::::from(0).validate(&ALICE, CALL, &INFO, 23), TransactionValidityError::Invalid(InvalidTransaction::Payment) @@ -82,7 +83,7 @@ fn charges_fee_when_native_is_enough_but_cannot_keep_alive() { .priority, fee2.saturated_into::() ); - assert_eq!(Currencies::free_balance(SETR, &ALICE), Currencies::minimum_balance(DNAR)); + assert_eq!(Currencies::free_balance(DNAR, &ALICE), Currencies::minimum_balance(DNAR)); }); } @@ -198,10 +199,6 @@ fn charges_fee_when_validate_and_native_is_not_enough() { .one_hundred_thousand_for_alice_n_charlie() .build() .execute_with(|| { - assert_ok!(>::transfer(SETR, &ALICE, &BOB, 1000)); - assert_eq!(>::free_balance(DNAR, &BOB), 0); - assert_eq!(>::free_balance(SETR, &BOB), 1000); - // add liquidity to DEX assert_ok!(SetheumDEX::add_liquidity( Origin::signed(ALICE), @@ -210,10 +207,15 @@ fn charges_fee_when_validate_and_native_is_not_enough() { 10000, 1000, 0, - false )); + assert_ok!(>::transfer(SETR, &ALICE, &BOB, 1000)); + assert_eq!(SetheumDEX::get_liquidity_pool(DNAR, SETR), (10000, 1000)); + assert_eq!(Currencies::total_balance(DNAR, &BOB), 0); + assert_eq!(>::free_balance(DNAR, &BOB), 0); + assert_eq!(>::free_balance(SETR, &BOB), 1000); + // total balance is lt ED, will swap fee and ED let fee = 500 * 2 + 1000; // len * byte + weight assert_eq!( ChargeTransactionPayment::::from(0) @@ -222,29 +224,103 @@ fn charges_fee_when_validate_and_native_is_not_enough() { .priority, fee ); - - assert_eq!(Currencies::free_balance(DNAR, &BOB), Currencies::minimum_balance(DNAR)); + assert_eq!(Currencies::total_balance(DNAR, &BOB), 10); + assert_eq!(Currencies::free_balance(DNAR, &BOB), 10); assert_eq!(Currencies::free_balance(SETR, &BOB), 748); - assert_eq!(SetheumDEX::get_liquidity_pool(DNAR, SETR), (10000 - 2000 - 10, 1252)); + assert_eq!( + SetheumDEX::get_liquidity_pool(DNAR, SETR), + (10000 - 2000 - 10, 1000 + 252) + ); + + // total balance is gte ED, but cannot keep alive after charge, + // will swap extra gap to keep alive + let fee_2 = 100 * 2 + 1000; // len * byte + weight + assert_eq!( + ChargeTransactionPayment::::from(0) + .validate(&BOB, CALL2, &INFO, 100) + .unwrap() + .priority, + fee_2 + ); + assert_eq!(Currencies::total_balance(DNAR, &BOB), 10); + assert_eq!(Currencies::free_balance(DNAR, &BOB), 10); + assert_eq!(Currencies::free_balance(SETR, &BOB), 526); + assert_eq!(SetheumDEX::get_liquidity_pool(DNAR, SETR), (7990 - 1200, 1252 + 222)); + }); +} + +#[test] +fn charges_fee_failed_by_slippage_limit() { + ExtBuilder::default() + .one_hundred_thousand_for_alice_n_charlie() + .build() + .execute_with(|| { + // add liquidity to DEX + assert_ok!(SetheumDEX::add_liquidity( + Origin::signed(ALICE), + DNAR, + SETR, + 10000, + 1000, + 0, + )); + assert_ok!(>::transfer(SETR, &ALICE, &BOB, 1000)); + + assert_eq!(SetheumDEX::get_liquidity_pool(DNAR, SETR), (10000, 1000)); + assert_eq!(Currencies::total_balance(DNAR, &BOB), 0); + assert_eq!(>::free_balance(DNAR, &BOB), 0); + assert_eq!(>::free_balance(SETR, &BOB), 1000); + + // pool is enough, but slippage limit the swap + MockPriceSource::set_relative_price(Some(Price::saturating_from_rational(252, 4020))); + assert_eq!(SetheumDEX::get_swap_supply_amount(&[SETR, DNAR], 2010), Some(252)); + assert_eq!(SetheumDEX::get_swap_target_amount(&[SETR, DNAR], 1000), Some(5000)); + + assert_noop!( + ChargeTransactionPayment::::from(0).validate(&BOB, CALL2, &INFO, 500), + TransactionValidityError::Invalid(InvalidTransaction::Payment) + ); + assert_eq!(SetheumDEX::get_liquidity_pool(DNAR, SETR), (10000, 1000)); }); } #[test] -fn set_default_fee_token_work() { +fn set_alternative_fee_swap_path_work() { ExtBuilder::default().build().execute_with(|| { - assert_eq!(TransactionPayment::default_fee_currency_id(&ALICE), None); - assert_ok!(TransactionPayment::set_default_fee_token( + assert_eq!(TransactionPayment::alternative_fee_swap_path(&ALICE), None); + assert_ok!(TransactionPayment::set_alternative_fee_swap_path( Origin::signed(ALICE), - Some(SETR) + Some(vec![SETR, DNAR]) )); - assert_eq!(TransactionPayment::default_fee_currency_id(&ALICE), Some(SETR)); - assert_ok!(TransactionPayment::set_default_fee_token(Origin::signed(ALICE), None)); - assert_eq!(TransactionPayment::default_fee_currency_id(&ALICE), None); + assert_eq!( + TransactionPayment::alternative_fee_swap_path(&ALICE).unwrap(), + vec![SETR, DNAR] + ); + assert_ok!(TransactionPayment::set_alternative_fee_swap_path( + Origin::signed(ALICE), + None + )); + assert_eq!(TransactionPayment::alternative_fee_swap_path(&ALICE), None); + + assert_noop!( + TransactionPayment::set_alternative_fee_swap_path(Origin::signed(ALICE), Some(vec![DNAR])), + Error::::InvalidSwapPath + ); + + assert_noop!( + TransactionPayment::set_alternative_fee_swap_path(Origin::signed(ALICE), Some(vec![SETR, DRAM])), + Error::::InvalidSwapPath + ); + + assert_noop!( + TransactionPayment::set_alternative_fee_swap_path(Origin::signed(ALICE), Some(vec![DNAR, DNAR])), + Error::::InvalidSwapPath + ); }); } #[test] -fn charge_fee_by_default_fee_token() { +fn charge_fee_by_default_swap_path() { ExtBuilder::default() .one_hundred_thousand_for_alice_n_charlie() .build() @@ -257,28 +333,29 @@ fn charge_fee_by_default_fee_token() { 10000, 1000, 0, - false )); assert_ok!(SetheumDEX::add_liquidity( Origin::signed(ALICE), - DOT, + DRAM, SETR, 100, 1000, 0, - false )); assert_eq!(SetheumDEX::get_liquidity_pool(DNAR, SETR), (10000, 1000)); - assert_eq!(SetheumDEX::get_liquidity_pool(DOT, SETR), (100, 1000)); - assert_ok!(TransactionPayment::set_default_fee_token( + assert_eq!(SetheumDEX::get_liquidity_pool(DRAM, SETR), (100, 1000)); + assert_ok!(TransactionPayment::set_alternative_fee_swap_path( Origin::signed(BOB), - Some(DOT) + Some(vec![DRAM, DNAR]) )); - assert_eq!(TransactionPayment::default_fee_currency_id(&BOB), Some(DOT)); - assert_ok!(>::transfer(DOT, &ALICE, &BOB, 100)); + assert_eq!( + TransactionPayment::alternative_fee_swap_path(&BOB).unwrap(), + vec![DRAM, DNAR] + ); + assert_ok!(>::transfer(DRAM, &ALICE, &BOB, 100)); assert_eq!(>::free_balance(DNAR, &BOB), 0); assert_eq!(>::free_balance(SETR, &BOB), 0); - assert_eq!(>::free_balance(DOT, &BOB), 100); + assert_eq!(>::free_balance(DRAM, &BOB), 100); let fee = 500 * 2 + 1000; // len * byte + weight assert_eq!( @@ -291,9 +368,9 @@ fn charge_fee_by_default_fee_token() { assert_eq!(Currencies::free_balance(DNAR, &BOB), Currencies::minimum_balance(DNAR)); assert_eq!(Currencies::free_balance(SETR, &BOB), 0); - assert_eq!(Currencies::free_balance(DOT, &BOB), 100 - 34); + assert_eq!(Currencies::free_balance(DRAM, &BOB), 100 - 34); assert_eq!(SetheumDEX::get_liquidity_pool(DNAR, SETR), (10000 - 2000 - 10, 1252)); - assert_eq!(SetheumDEX::get_liquidity_pool(DOT, SETR), (100 + 34, 1000 - 252)); + assert_eq!(SetheumDEX::get_liquidity_pool(DRAM, SETR), (100 + 34, 1000 - 252)); }); } diff --git a/lib-serml/transaction-payment/src/weights.rs b/lib-serml/transaction-payment/src/weights.rs index b3ed872a0..3948ba7d1 100644 --- a/lib-serml/transaction-payment/src/weights.rs +++ b/lib-serml/transaction-payment/src/weights.rs @@ -47,14 +47,14 @@ use sp_std::marker::PhantomData; /// Weight functions needed for setheum_transaction_payment. pub trait WeightInfo { - fn set_default_fee_token() -> Weight; + fn set_alternative_fee_swap_path() -> Weight; fn on_finalize() -> Weight; } /// Weights for setheum_transaction_payment using the Setheum node and recommended hardware. pub struct SetheumWeight(PhantomData); impl WeightInfo for SetheumWeight { - fn set_default_fee_token() -> Weight { + fn set_alternative_fee_swap_path() -> Weight { (3_000_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } @@ -67,7 +67,7 @@ impl WeightInfo for SetheumWeight { // For backwards compatibility and tests impl WeightInfo for () { - fn set_default_fee_token() -> Weight { + fn set_alternative_fee_swap_path() -> Weight { (3_000_000 as Weight) .saturating_add(RocksDbWeight::get().writes(1 as Weight)) } From 9fd2c8f77f4e53693e5ec7745b5c3bd1c5bb6fb6 Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Tue, 31 Aug 2021 19:22:15 +0800 Subject: [PATCH 03/22] Update ST --- lib-serml/serp/serp-treasury/src/lib.rs | 10 +++++----- lib-serml/serp/serp-treasury/src/mock.rs | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lib-serml/serp/serp-treasury/src/lib.rs b/lib-serml/serp/serp-treasury/src/lib.rs index 480f77833..f6d9b23c8 100644 --- a/lib-serml/serp/serp-treasury/src/lib.rs +++ b/lib-serml/serp/serp-treasury/src/lib.rs @@ -112,7 +112,7 @@ pub mod module { /// Default fee swap path list #[pallet::constant] - type DefaultFeeSwapPathList: Get>>; + type DefaultSwapPathList: Get>>; /// When swap with DEX, the acceptable max slippage for the price from oracle. #[pallet::constant] @@ -477,7 +477,7 @@ impl SerpTreasuryExtended for Pallet { let dinar_currency_id = T::GetNativeCurrencyId::get(); let setter_currency_id = T::SetterCurrencyId::get(); - let default_fee_swap_path_list = T::DefaultFeeSwapPathList::get(); + let default_fee_swap_path_list = T::DefaultSwapPathList::get(); let swap_path: Vec> = if let Some(path) = AlternativeFeeSwapPath::::get(&Self::account_id()) { vec![vec![path.into_inner()], default_fee_swap_path_list].concat() @@ -539,7 +539,7 @@ impl SerpTreasuryExtended for Pallet { let native_currency_id = T::GetNativeCurrencyId::get(); let setter_currency_id = T::SetterCurrencyId::get(); - let default_fee_swap_path_list = T::DefaultFeeSwapPathList::get(); + let default_fee_swap_path_list = T::DefaultSwapPathList::get(); let swap_path: Vec> = if let Some(path) = AlternativeFeeSwapPath::::get(&Self::account_id()) { vec![vec![path.into_inner()], default_fee_swap_path_list].concat() @@ -601,7 +601,7 @@ impl SerpTreasuryExtended for Pallet { let dinar_currency_id = T::GetNativeCurrencyId::get(); let currency_id = T::SetterCurrencyId::get(); - let default_fee_swap_path_list = T::DefaultFeeSwapPathList::get(); + let default_fee_swap_path_list = T::DefaultSwapPathList::get(); let swap_path: Vec> = if let Some(path) = AlternativeFeeSwapPath::::get(&Self::account_id()) { vec![vec![path.into_inner()], default_fee_swap_path_list].concat() @@ -658,7 +658,7 @@ impl SerpTreasuryExtended for Pallet { let native_currency_id = T::GetNativeCurrencyId::get(); let dinar_currency_id = T::GetNativeCurrencyId::get(); - let default_fee_swap_path_list = T::DefaultFeeSwapPathList::get(); + let default_fee_swap_path_list = T::DefaultSwapPathList::get(); let swap_path: Vec> = if let Some(path) = AlternativeFeeSwapPath::::get(&Self::account_id()) { vec![vec![path.into_inner()], default_fee_swap_path_list].concat() diff --git a/lib-serml/serp/serp-treasury/src/mock.rs b/lib-serml/serp/serp-treasury/src/mock.rs index e3ba17d46..de4162cfe 100644 --- a/lib-serml/serp/serp-treasury/src/mock.rs +++ b/lib-serml/serp/serp-treasury/src/mock.rs @@ -246,7 +246,7 @@ parameter_type_with_key! { parameter_types! { pub MaxSwapSlippageCompareToOracle: Ratio = Ratio::saturating_from_rational(1, 2); - pub DefaultFeeSwapPathList: Vec> = vec![vec![SETR, DNAR], vec![SETUSD, SETR, DNAR]]; + pub DefaultSwapPathList: Vec> = vec![vec![SETR, DNAR], vec![SETUSD, SETR, DNAR]]; } ord_parameter_types! { @@ -266,7 +266,7 @@ impl Config for Runtime { type SettPayTreasuryAccountId = SettPayTreasuryAccountId; type CashDropVaultAccountId = CashDropVaultAccountId; type CharityFundAccountId = CharityFundAccountId; - type DefaultFeeSwapPathList = DefaultFeeSwapPathList; + type DefaultSwapPathList = DefaultSwapPathList; type Dex = SetheumDEX; type MaxSwapSlippageCompareToOracle = MaxSwapSlippageCompareToOracle; type TradingPathLimit = TradingPathLimit; From a3d54f30fa96bbffacd3f80c10bad718b7ac0a5b Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Tue, 31 Aug 2021 21:28:15 +0800 Subject: [PATCH 04/22] Update LPs and Runtimes: #459, #513 --- primitives/src/currency.rs | 64 +-- runtime/newrome/src/constants.rs | 4 +- runtime/setheum/src/constants.rs | 4 +- runtime/setheum/src/lib.rs | 774 ++++++++++++------------------- 4 files changed, 298 insertions(+), 548 deletions(-) diff --git a/primitives/src/currency.rs b/primitives/src/currency.rs index 906469185..f4bcb9f57 100644 --- a/primitives/src/currency.rs +++ b/primitives/src/currency.rs @@ -128,44 +128,15 @@ macro_rules! create_currency_id { ]; let mut lp_tokens = vec![ - // DNAR paired LPs - Token { - symbol: "LP_DRAM_DNAR".to_string(), - address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(DRAM), DexShare::Token(DNAR))).unwrap(), - }, - Token { - symbol: "LP_SETUSD_DNAR".to_string(), - address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(SETUSD), DexShare::Token(DNAR))).unwrap(), - }, - Token { - symbol: "LP_SETEUR_DNAR".to_string(), - address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(SETEUR), DexShare::Token(DNAR))).unwrap(), - }, - Token { - symbol: "LP_SETGBP_DNAR".to_string(), - address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(SETGBP), DexShare::Token(DNAR))).unwrap(), - }, - Token { - symbol: "LP_SETCHF_DNAR".to_string(), - address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(SETCHF), DexShare::Token(DNAR))).unwrap(), - }, - Token { - symbol: "LP_SETSAR_DNAR".to_string(), - address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(SETSAR), DexShare::Token(DNAR))).unwrap(), - }, + // SETR paired LPs Token { - symbol: "LP_RENBTC_DNAR".to_string(), - address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(RENBTC), DexShare::Token(DNAR))).unwrap(), + symbol: "LP_DRAM_SETR".to_string(), + address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(DRAM), DexShare::Token(SETR))).unwrap(), }, - // SETR paired LPs Token { symbol: "LP_DNAR_SETR".to_string(), address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(DNAR), DexShare::Token(SETR))).unwrap(), }, - Token { - symbol: "LP_DRAM_SETR".to_string(), - address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(DRAM), DexShare::Token(SETR))).unwrap(), - }, Token { symbol: "LP_SETUSD_SETR".to_string(), address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(SETUSD), DexShare::Token(SETR))).unwrap(), @@ -190,31 +161,6 @@ macro_rules! create_currency_id { symbol: "LP_RENBTC_SETR".to_string(), address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(RENBTC), DexShare::Token(SETR))).unwrap(), }, - // SETUSD paired LPs - Token { - symbol: "LP_DRAM_SETUSD".to_string(), - address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(DRAM), DexShare::Token(SETUSD))).unwrap(), - }, - Token { - symbol: "LP_SETEUR_SETUSD".to_string(), - address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(SETEUR), DexShare::Token(SETUSD))).unwrap(), - }, - Token { - symbol: "LP_SETGBP_SETUSD".to_string(), - address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(SETGBP), DexShare::Token(SETUSD))).unwrap(), - }, - Token { - symbol: "LP_SETCHF_SETUSD".to_string(), - address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(SETCHF), DexShare::Token(SETUSD))).unwrap(), - }, - Token { - symbol: "LP_SETSAR_SETUSD".to_string(), - address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(SETSAR), DexShare::Token(SETUSD))).unwrap(), - }, - Token { - symbol: "LP_RENBTC_SETUSD".to_string(), - address: EvmAddress::try_from(CurrencyId::DexShare(DexShare::Token(RENBTC), DexShare::Token(SETUSD))).unwrap(), - }, ]; tokens.append(&mut lp_tokens); @@ -233,8 +179,8 @@ create_currency_id! { #[repr(u8)] pub enum TokenSymbol { /// Setheum Network - DNAR("Setheum Dinar", 12) = 0, - DRAM("Setheum Dirham", 12) = 1, + DRAM("Setheum Dirham", 12) = 0, + DNAR("Setheum Dinar", 12) = 1, SETR("Setter", 12) = 2, // SetCurrencies SETUSD("SetDollar", 12) = 3, diff --git a/runtime/newrome/src/constants.rs b/runtime/newrome/src/constants.rs index 8a810ecc7..7ab7945a8 100644 --- a/runtime/newrome/src/constants.rs +++ b/runtime/newrome/src/constants.rs @@ -50,7 +50,7 @@ pub mod fee { constants::ExtrinsicBaseWeight, WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, }; use primitives::Balance; - use runtime_common::{cent, DNAR}; + use runtime_common::{cent, DRAM}; use smallvec::smallvec; use sp_runtime::Perbill; @@ -75,7 +75,7 @@ pub mod fee { fn polynomial() -> WeightToFeeCoefficients { // in Setheum, extrinsic base weight (smallest non-zero weight) is mapped to 1/10 // CENT: - let p = cent(DNAR) / 10; // 10_000_000_000; + let p = cent(DRAM) / 10; // 10_000_000_000; let q = Balance::from(ExtrinsicBaseWeight::get()); // 125_000_000 smallvec![WeightToFeeCoefficient { degree: 1, diff --git a/runtime/setheum/src/constants.rs b/runtime/setheum/src/constants.rs index 064e83747..fbfbe73ab 100644 --- a/runtime/setheum/src/constants.rs +++ b/runtime/setheum/src/constants.rs @@ -50,7 +50,7 @@ pub mod fee { constants::ExtrinsicBaseWeight, WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, }; use primitives::Balance; - use runtime_common::{cent, DNAR}; + use runtime_common::{cent, DRAM}; use smallvec::smallvec; use sp_runtime::Perbill; @@ -75,7 +75,7 @@ pub mod fee { fn polynomial() -> WeightToFeeCoefficients { // in Setheum, extrinsic base weight (smallest non-zero weight) is mapped to 1/10 // CENT: - let p = cent(DNAR) / 10; // 10_000_000_000 + let p = cent(DRAM) / 10; // 10_000_000_000 let q = Balance::from(ExtrinsicBaseWeight::get()); // 125_000_000 smallvec![WeightToFeeCoefficient { degree: 1, diff --git a/runtime/setheum/src/lib.rs b/runtime/setheum/src/lib.rs index e1a10f9f9..812ffaf9e 100644 --- a/runtime/setheum/src/lib.rs +++ b/runtime/setheum/src/lib.rs @@ -106,10 +106,19 @@ pub use primitives::{ }; pub use runtime_common::{ cent, deposit, dollar, microcent, millicent, BlockLength, BlockWeights, - ExchangeRate, GasToWeight, OffchainSolutionWeightLimit, Price, Rate, Ratio, - RuntimeBlockLength, RuntimeBlockWeights,SystemContractsFilter, TimeStampedPrice, - DNAR, DRAM, SETR, SETUSD, SETEUR, SETGBP, SETCHF, SETSAR RENBTC, - USD, EUR, GBP, CHF, SAR, KWD, JOD, BHD, KYD, OMR, GIP + EnsureRootOrAllGeneralCouncil, EnsureRootOrAllTechnicalCommittee, + EnsureRootOrHalfFinancialCouncil, EnsureRootOrHalfGeneralCouncil, + EnsureRootOrHalfHomaCouncil, EnsureRootOrOneThirdsTechnicalCommittee, + EnsureRootOrThreeFourthsGeneralCouncil, EnsureRootOrTwoThirdsGeneralCouncil, + EnsureRootOrTwoThirdsTechnicalCommittee, ExchangeRate, FinancialCouncilInstance, + FinancialCouncilMembershipInstance, GasToWeight, GeneralCouncilInstance, + GeneralCouncilMembershipInstance, OperatorMembershipInstanceSetheum, + OffchainSolutionWeightLimit, Price, ProxyType, Rate, Ratio, RuntimeBlockLength, + RuntimeBlockWeights, SystemContractsFilter, EnsureRootOrAllShuraCouncil, + EnsureRootOrHalfShuraCouncil, EnsureRootOrThreeFourthsShuraCouncil, + EnsureRootOrTwoThirdsShuraCouncil, ShuraCouncilInstance, + ShuraCouncilMembershipInstance, TimeStampedPrice, + DNAR, DRAM, SETR, SETUSD, SETEUR, SETGBP, SETCHF, SETSAR, RENBTC, }; mod authority; mod benchmarking; @@ -117,10 +126,10 @@ mod constants; /// This runtime version. pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("newrome"), - impl_name: create_runtime_str!("newrome"), + spec_name: create_runtime_str!("setheum"), + impl_name: create_runtime_str!("setheum"), authoring_version: 1, - spec_version: 1000, + spec_version: 258, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -165,7 +174,7 @@ pub fn get_all_module_accounts() -> Vec { } parameter_types! { - pub const BlockHashCount: BlockNumber = 1200; // mortal tx can be valid up to 4 hour after signing + pub const BlockHashCount: BlockNumber = 3600; // mortal tx can be valid up to 4 hour after signing pub const Version: RuntimeVersion = VERSION; pub const SS58Prefix: u16 = 258; // Ss58AddressFormat::SetheumAccount } @@ -181,14 +190,30 @@ impl Filter for BaseCallFilter { Call::Scheduler(_) | Call::Utility(_) | Call::Multisig(_) | // Sudo Call::Sudo(_) | - // PoA - Call::Authority(_) | Call::GeneralCouncil(_) | Call::GeneralCouncilMembership(_) | - Call::SetheumJury(_) | Call::SetheumJuryMembership(_) | + // Councils + Call::Authority(_) | + Call::ShuraCouncil(_) | Call::ShuraCouncilMembership(_) | + Call::GeneralCouncil(_) | Call::GeneralCouncilMembership(_) | Call::FinancialCouncil(_) | Call::FinancialCouncilMembership(_) | - Call::ExchangeCouncil(_) | Call::ExchangeCouncilMembership(_) | Call::TechnicalCommittee(_) | Call::TechnicalCommitteeMembership(_) | // Oracle Call::SetheumOracle(_) | Call::OperatorMembershipSetheum(_) + // Democracy + Call::Democracy(_) | Call::Treasury(_) | Call::Bounties(_) | Call::Tips(_) | + // Vesting + Call::Vesting(_) | + // TransactionPayment + Call::TransactionPayment(_) | + // Tokens + Call::Balances(_) | Call::Currencies(_) | + // NFT + Call::NFT(_) | + // DEX + Call::Dex(_) | + // Serp + Call::Prices(_) | Call::SerpTreasury(_) | + // Serttmint + Call::SettmintGateway(_)| Call::SettmintEngine(_) ) } } @@ -259,7 +284,7 @@ impl pallet_grandpa::Config for Runtime { } parameter_types! { - pub IndexDeposit: Balance = dollar(DNAR); + pub IndexDeposit: Balance = dollar(DRAM); } impl pallet_indices::Config for Runtime { @@ -294,7 +319,7 @@ impl pallet_authorship::Config for Runtime { } parameter_types! { - pub NativeTokenExistentialDeposit: Balance = 10 * cent(DNAR); // 0.1 DNAR + pub NativeTokenExistentialDeposit: Balance = 10 * cent(DRAM); // 0.1 DRAM // For weight estimation, we assume that the most locks on an individual account will be 50. // This number may need to be adjusted in the future if this assumption no longer holds true. pub const MaxLocks: u32 = 50; @@ -314,7 +339,7 @@ impl pallet_balances::Config for Runtime { } parameter_types! { - pub TransactionByteFee: Balance = millicent(DNAR); + pub TransactionByteFee: Balance = millicent(DRAM); /// The portion of the `NORMAL_DISPATCH_RATIO` that we adjust the fees with. Blocks filled less /// than this will decrease the weight and more will increase. pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25); @@ -335,233 +360,37 @@ impl pallet_sudo::Config for Runtime { type Call = Call; } -type EnsureRootOrAllGeneralCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, GeneralCouncilInstance>, ->; - -type EnsureRootOrAllSetheumJury = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, SetheumJuryInstance>, ->; - -type EnsureAllSetheumJuryOrAllGeneralCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, GeneralCouncilInstance>, ->; - -type EnsureRootOrOneThirdSetheumJury = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _3, AccountId, SetheumJuryInstance>, ->; - -type EnsureRootOrTwoThirdsSetheumJury = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, SetheumJuryInstance>, ->; - -type EnsureRootOrHalfSetheumJury = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, ->; - -type EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, GeneralCouncilInstance>, ->; - -type EnsureQuarterSetheumJuryOrHalfGeneralCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _4, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, GeneralCouncilInstance>, ->; - -type EnsureOneThirdSetheumJuryOrHalfGeneralCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _3, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, GeneralCouncilInstance>, ->; - -type EnsureHalfSetheumJuryOrHalfGeneralCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, GeneralCouncilInstance>, ->; - -type EnsureRootOrHalfGeneralCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, GeneralCouncilInstance>, ->; - -type EnsureRootOrHalfFinancialCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, FinancialCouncilInstance>, ->; - -type EnsureHalfSetheumJuryOrHalfFinancialCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, FinancialCouncilInstance>, ->; - -type EnsureRootOrTwoThirdsFinancialCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, FinancialCouncilInstance>, ->; - -type EnsureHalfSetheumJuryOrTwoThirdsFinancialCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, FinancialCouncilInstance>, ->; - -type EnsureRootOrAllFinancialCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, FinancialCouncilInstance>, ->; - -type EnsureHalfSetheumJuryOrAllFinancialCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, FinancialCouncilInstance>, ->; - -type EnsureTwoThirdsSetheumJuryOrAllFinancialCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, FinancialCouncilInstance>, ->; - -type EnsureAllSetheumJuryOrAllFinancialCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, FinancialCouncilInstance>, ->; - -type EnsureTwoThirdsFinancialCouncilOrTwoThirdsExchangeCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, FinancialCouncilInstance>, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureRootOrHalfExchangeCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureHalfSetheumJuryOrHalfExchangeCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureRootOrTwoThirdsExchangeCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureHalfFinancialCouncilOrTwoThirdsExchangeCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, FinancialCouncilInstance>, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureHalfSetheumJuryOrTwoThirdsExchangeCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureRootOrAllExchangeCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureHalfSetheumJuryOrAllExchangeCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureTwoThirdsSetheumJuryOrAllExchangeCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureAllSetheumJuryOrAllExchangeCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureRootOrTwoThirdsGeneralCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, GeneralCouncilInstance>, ->; - -type EnsureTwoThirdsSetheumJuryOrTwoThirdsGeneralCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, GeneralCouncilInstance>, ->; - -type EnsureRootOrThreeFourthsGeneralCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_3, _4, AccountId, GeneralCouncilInstance>, ->; - -type EnsureRootOrThreeFourthsSetheumJury = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_3, _4, AccountId, SetheumJuryInstance>, ->; - -type EnsureThreeFourthsSetheumJuryOrThreeFourthsGeneralCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_3, _4, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_3, _4, AccountId, GeneralCouncilInstance>, ->; - -type EnsureRootOrOneThirdsTechnicalCommittee = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _3, AccountId, TechnicalCommitteeInstance>, ->; - -type EnsureOneThirdsSetheumJuryOrOneThirdsTechnicalCommittee = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _3, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _3, AccountId, TechnicalCommitteeInstance>, ->; +parameter_types! { + pub const ShuraCouncilMotionDuration: BlockNumber = 3 * DAYS; + pub const ShuraCouncilMaxProposals: u32 = 20; + pub const ShuraCouncilMaxMembers: u32 = 30; +} -type EnsureTwoThirdsSetheumJuryOrTwoThirdsTechnicalCommittee = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, TechnicalCommitteeInstance>, ->; +type ShuraCouncilInstance = pallet_collective::Instance2; +impl pallet_collective::Config for Runtime { + type Origin = Origin; + type Proposal = Call; + type Event = Event; + type MotionDuration = ShuraCouncilMotionDuration; + type MaxProposals = ShuraCouncilMaxProposals; + type MaxMembers = ShuraCouncilMaxMembers; + type DefaultVote = pallet_collective::PrimeDefaultVote; + type WeightInfo = (); +} -type EnsureRootOrTwoThirdsTechnicalCommittee = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, TechnicalCommitteeInstance>, ->; +type ShuraCouncilMembershipInstance = pallet_membership::Instance2; +impl pallet_membership::Config for Runtime { + type Event = Event; + type AddOrigin = EnsureRootOrThreeFourthsShuraCouncil; + type RemoveOrigin = EnsureRootOrThreeFourthsShuraCouncil; + type SwapOrigin = EnsureRootOrThreeFourthsShuraCouncil; + type ResetOrigin = EnsureRootOrThreeFourthsShuraCouncil; + type PrimeOrigin = EnsureRootOrThreeFourthsShuraCouncil; + type MembershipInitialized = ShuraCouncil; + type MembershipChanged = ShuraCouncil; + type MaxMembers = ShuraCouncilMaxMembers; + type WeightInfo = (); +} parameter_types! { pub const GeneralCouncilMotionDuration: BlockNumber = 3 * DAYS; @@ -584,53 +413,21 @@ impl pallet_collective::Config for Runtime { type GeneralCouncilMembershipInstance = pallet_membership::Instance1; impl pallet_membership::Config for Runtime { type Event = Event; - type AddOrigin = EnsureRootOrThreeFourthsGeneralCouncil; - type RemoveOrigin = EnsureRootOrThreeFourthsGeneralCouncil; - type SwapOrigin = EnsureRootOrThreeFourthsGeneralCouncil; - type ResetOrigin = EnsureRootOrThreeFourthsGeneralCouncil; - type PrimeOrigin = EnsureRootOrThreeFourthsGeneralCouncil; + type AddOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type RemoveOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type SwapOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type ResetOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type PrimeOrigin = EnsureRootOrTwoThirdsShuraCouncil; type MembershipInitialized = GeneralCouncil; type MembershipChanged = GeneralCouncil; type MaxMembers = GeneralCouncilMaxMembers; type WeightInfo = (); } -parameter_types! { - pub const SetheumJuryMotionDuration: BlockNumber = 3 * DAYS; - pub const SetheumJuryMaxProposals: u32 = 50; - pub const SetheumJuryMaxMembers: u32 = 50; -} - -type SetheumJuryInstance = pallet_collective::Instance2; -impl pallet_collective::Config for Runtime { - type Origin = Origin; - type Proposal = Call; - type Event = Event; - type MotionDuration = SetheumJuryMotionDuration; - type MaxProposals = SetheumJuryMaxProposals; - type MaxMembers = SetheumJuryMaxMembers; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = (); -} - -type SetheumJuryMembershipInstance = pallet_membership::Instance2; -impl pallet_membership::Config for Runtime { - type Event = Event; - type AddOrigin = EnsureRootOrThreeFourthsSetheumJury; - type RemoveOrigin = EnsureRootOrThreeFourthsSetheumJury; - type SwapOrigin = EnsureRootOrThreeFourthsSetheumJury; - type ResetOrigin = EnsureRootOrThreeFourthsSetheumJury; - type PrimeOrigin = EnsureRootOrThreeFourthsSetheumJury; - type MembershipInitialized = SetheumJury; - type MembershipChanged = SetheumJury; - type MaxMembers = SetheumJuryMaxMembers; - type WeightInfo = (); -} - parameter_types! { pub const FinancialCouncilMotionDuration: BlockNumber = 3 * DAYS; - pub const FinancialCouncilMaxProposals: u32 = 50; - pub const FinancialCouncilMaxMembers: u32 = 50; + pub const FinancialCouncilMaxProposals: u32 = 20; + pub const FinancialCouncilMaxMembers: u32 = 30; } type FinancialCouncilInstance = pallet_collective::Instance3; @@ -648,56 +445,24 @@ impl pallet_collective::Config for Runtime { type FinancialCouncilMembershipInstance = pallet_membership::Instance3; impl pallet_membership::Config for Runtime { type Event = Event; - type AddOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type RemoveOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type SwapOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type ResetOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type PrimeOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. + type AddOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type RemoveOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type SwapOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type ResetOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type PrimeOrigin = EnsureRootOrTwoThirdsShuraCouncil; type MembershipInitialized = FinancialCouncil; type MembershipChanged = FinancialCouncil; type MaxMembers = FinancialCouncilMaxMembers; type WeightInfo = (); } -parameter_types! { - pub const ExchangeCouncilMotionDuration: BlockNumber = 3 * DAYS; - pub const ExchangeCouncilMaxProposals: u32 = 50; - pub const ExchangeCouncilMaxMembers: u32 = 50; -} - -type ExchangeCouncilInstance = pallet_collective::Instance4; -impl pallet_collective::Config for Runtime { - type Origin = Origin; - type Proposal = Call; - type Event = Event; - type MotionDuration = ExchangeCouncilMotionDuration; - type MaxProposals = ExchangeCouncilMaxProposals; - type MaxMembers = ExchangeCouncilMaxMembers; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = (); -} - -type ExchangeCouncilMembershipInstance = pallet_membership::Instance4; -impl pallet_membership::Config for Runtime { - type Event = Event; - type AddOrigin = EnsureRootOrTwoThirdsExchangeCouncil; - type RemoveOrigin = EnsureRootOrTwoThirdsExchangeCouncil; - type SwapOrigin = EnsureRootOrTwoThirdsExchangeCouncil; - type ResetOrigin = EnsureRootOrTwoThirdsExchangeCouncil; - type PrimeOrigin = EnsureRootOrTwoThirdsExchangeCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsFinancialCouncilOrTwoThirdsExchangeCouncil`. - type MembershipInitialized = ExchangeCouncil; - type MembershipChanged = ExchangeCouncil; - type MaxMembers = ExchangeCouncilMaxMembers; - type WeightInfo = (); -} - parameter_types! { pub const TechnicalCommitteeMotionDuration: BlockNumber = 3 * DAYS; pub const TechnicalCommitteeMaxProposals: u32 = 50; pub const TechnicalCouncilMaxMembers: u32 = 50; } -type TechnicalCommitteeInstance = pallet_collective::Instance5; +type TechnicalCommitteeInstance = pallet_collective::Instance4; impl pallet_collective::Config for Runtime { type Origin = Origin; type Proposal = Call; @@ -709,15 +474,15 @@ impl pallet_collective::Config for Runtime { type WeightInfo = (); } -type TechnicalCommitteeMembershipInstance = pallet_membership::Instance5; +type TechnicalCommitteeMembershipInstance = pallet_membership::Instance4; impl pallet_membership::Config for Runtime { type Event = Event; - type AddOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type RemoveOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type SwapOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type ResetOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type PrimeOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. + type AddOrigin = EnsureRootOrTwoThirdsGeneralCouncil; + type RemoveOrigin = EnsureRootOrTwoThirdsGeneralCouncil; + type SwapOrigin = EnsureRootOrTwoThirdsGeneralCouncil; + type ResetOrigin = EnsureRootOrTwoThirdsGeneralCouncil; + type PrimeOrigin = EnsureRootOrTwoThirdsGeneralCouncil; type MembershipInitialized = TechnicalCommittee; type MembershipChanged = TechnicalCommittee; type MaxMembers = TechnicalCouncilMaxMembers; @@ -728,6 +493,24 @@ parameter_types! { pub const OracleMaxMembers: u32 = 50; } +type OperatorMembershipInstanceSetheum = pallet_membership::Instance5; +impl pallet_membership::Config for Runtime { + type Event = Event; + type AddOrigin = EnsureRootOrTwoThirdsFinancialCouncil; + type RemoveOrigin = EnsureRootOrTwoThirdsFinancialCouncil; + type SwapOrigin = EnsureRootOrTwoThirdsFinancialCouncil; + type ResetOrigin = EnsureRootOrTwoThirdsFinancialCouncil; + type PrimeOrigin = EnsureRootOrTwoThirdsFinancialCouncil; + type MembershipInitialized = (); + type MembershipChanged = SetheumOracle; + type MaxMembers = OracleMaxMembers; + type WeightInfo = (); +} + +parameter_types! { + pub const OracleMaxMembers: u32 = 50; +} + type OperatorMembershipInstanceSetheum = pallet_membership::Instance6; impl pallet_membership::Config for Runtime { type Event = Event; @@ -791,7 +574,7 @@ impl ContainsLengthBound for GeneralCouncilProvider { parameter_types! { pub const ProposalBond: Permill = Permill::from_percent(5); - pub ProposalBondMinimum: Balance = 2 * dollar(DNAR); + pub ProposalBondMinimum: Balance = 2 * dollar(DRAM); pub const SpendPeriod: BlockNumber = 7 * DAYS; pub const Burn: Permill = Permill::from_percent(0); @@ -802,7 +585,7 @@ parameter_types! { pub const BountyDepositPayoutDelay: BlockNumber = 3 * DAYS; pub const BountyUpdatePeriod: BlockNumber = 30 * DAYS; pub const BountyCuratorDeposit: Permill = Permill::from_percent(50); - pub BountyValueMinimum: Balance = 5 * dollar(DNAR); + pub BountyValueMinimum: Balance = 5 * dollar(DRAM); pub DataDepositPerByte: Balance = deposit(0, 1); pub const MaximumReasonLength: u32 = 16384; pub const MaxApprovals: u32 = 100; @@ -812,7 +595,7 @@ impl pallet_treasury::Config for Runtime { type PalletId = TreasuryPalletId; type Currency = Balances; type ApproveOrigin = EnsureRootOrHalfGeneralCouncil; - type RejectOrigin = EnsureRootOrHalfGeneralCouncil; // TODO: When root is removed, change to `EnsureHalfSetheumJuryOrHalfGeneralCouncil`. + type RejectOrigin = EnsureRootOrHalfGeneralCouncil; type Event = Event; type OnSlash = (); type ProposalBond = ProposalBond; @@ -848,7 +631,6 @@ impl pallet_tips::Config for Runtime { type WeightInfo = (); } -// TODO: Update to `serp-staking` and it's allied implementations parameter_types! { pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17); } @@ -883,16 +665,10 @@ pallet_staking_reward_curve::build! { } parameter_types! { - pub const SessionsPerEra: sp_staking::SessionIndex = 2; // 2 hours - pub const BondingDuration: serp_staking::EraIndex = 2; // 4 hours - pub const SlashDeferDuration: serp_staking::EraIndex = 2; // 4 hours + pub const SessionsPerEra: sp_staking::SessionIndex = 3; // 3 hours + pub const BondingDuration: pallet_staking::EraIndex = 4; // 12 hours + pub const SlashDeferDuration: pallet_staking::EraIndex = 2; // 6 hours pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE; - /// The number of eras between each halvening, - /// 8_064 eras (2 years, each era is 2 hours) halving interval. - pub const HalvingInterval: EraIndex = 8_064; - /// The per-era issuance before any halvenings. - /// Decimal places should be accounted for here. - pub const InitialIssuance: Balance = 7_200 * dollar(DNAR); pub const MaxNominatorRewardedPerValidator: u32 = 64; pub const ElectionLookahead: BlockNumber = EPOCH_DURATION_IN_BLOCKS / 4; pub const MaxIterations: u32 = 5; @@ -900,17 +676,14 @@ parameter_types! { pub MinSolutionScoreBump: Perbill = Perbill::from_rational_approximation(5u32, 10_000); } -impl serp_staking::Config for Runtime { +impl pallet_staking::Config for Runtime { type Currency = Balances; type UnixTime = Timestamp; type CurrencyToVote = U128CurrencyToVote; - type RewardRemainder = Treasury; + type RewardRemainder = AcalaTreasury; type Event = Event; - type Slash = Treasury; // send the slashed funds to the pallet treasury. + type Slash = AcalaTreasury; // send the slashed funds to the pallet treasury. type Reward = (); // rewards are minted from the void - type HalvingInterval = HalvingInterval; // halving interval for native currency rewards. - type InitialIssuance = InitialIssuance; // initial issuance for native currency rewards. - type SerpTreasury = SerpTreasury; type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; type SlashDeferDuration = SlashDeferDuration; @@ -930,10 +703,10 @@ impl serp_staking::Config for Runtime { } parameter_types! { - pub ConfigDepositBase: Balance = 10 * cent(DNAR); - pub FriendDepositFactor: Balance = cent(DNAR); + pub ConfigDepositBase: Balance = 10 * cent(DRAM); + pub FriendDepositFactor: Balance = cent(DRAM); pub const MaxFriends: u16 = 9; - pub RecoveryDeposit: Balance = 10 * cent(DNAR); + pub RecoveryDeposit: Balance = 10 * cent(DRAM); } impl pallet_recovery::Config for Runtime { @@ -951,68 +724,44 @@ parameter_types! { pub const VotingPeriod: BlockNumber = 28 * DAYS; pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS; pub MinimumDeposit: Balance = 100 * dollar(); - pub GoldenMinimumDepositMultiple: u32 = 1; // 1x of the `MinimumDeposit` is minimum deposit for DNAR (1). - pub SetterMinimumDepositMultiple: u32 = 2; // 2x of the `MinimumDeposit` is minimum deposit for SETR (2). - pub SilverMinimumDepositMultiple: u32 = 3; // 3x of the `MinimumDeposit` is minimum deposit for DRAM (3). pub const EnactmentPeriod: BlockNumber = 28 * DAYS; pub const CooloffPeriod: BlockNumber = 7 * DAYS; + pub PreimageByteDeposit: Balance = cent(DRAM); + pub const InstantAllowed: bool = true; pub const MaxVotes: u32 = 100; pub const MaxProposals: u32 = 100; - pub PreimageByteDeposit: Balance = cent(DNAR); - pub const InstantAllowed: bool = true; - pub const GovernanceCurrencyIds: Vec = vec![DNAR, SETR, DRAM]; } -parameter_types! { - pub const GetNativeCurrencyId: CurrencyId = DNAR; - pub const SetterCurrencyId: CurrencyId = SETR; - pub const DirhamCurrencyId: CurrencyId = DRAM; - pub const GetSetUSDCurrencyId: CurrencyId = SETUSD; - pub const GetFiatCHFCurrencyId: CurrencyId = CHF; - pub const GetFiatEURCurrencyId: CurrencyId = EUR; - pub const GetFiatGBPCurrencyId: CurrencyId = GBP; - pub const GetFiatSARCurrencyId: CurrencyId = SAR; - pub const GetFiatUSDCurrencyId: CurrencyId = USD; -} - -impl setheum_democracy::Config for Runtime { +impl pallet_democracy::Config for Runtime { type Proposal = Call; type Event = Event; type Currency = Balances; - type MultiCurrency = Tokens; type EnactmentPeriod = EnactmentPeriod; type LaunchPeriod = LaunchPeriod; type VotingPeriod = VotingPeriod; - type GovernanceCurrencyIds = GovernanceCurrencyIds; - type NativeCurrencyId = NativeCurrencyId; - type DirhamCurrencyId = DirhamCurrencyId; - type SetterCurrencyId = SetterCurrencyId; type MinimumDeposit = MinimumDeposit; - type GoldenMinimumDepositMultiple = GoldenMinimumDepositMultiple; - type SetterMinimumDepositMultiple = SetterMinimumDepositMultiple; - type SilverMinimumDepositMultiple = SilverMinimumDepositMultiple; /// A straight majority of the council can decide what their next motion is. - type ExternalOrigin = EnsureRootOrHalfGeneralCouncil; // TODO: When root is removed, change to `EnsureHalfSetheumJuryOrHalfGeneralCouncil`. + type ExternalOrigin = EnsureRootOrHalfGeneralCouncil; /// A majority can have the next scheduled referendum be a straight majority-carries vote. - type ExternalMajorityOrigin = EnsureRootOrHalfGeneralCouncil; // TODO: When root is removed, change to `EnsureHalfSetheumJuryOrHalfGeneralCouncil`. + type ExternalMajorityOrigin = EnsureRootOrHalfGeneralCouncil; /// A unanimous council can have the next scheduled referendum be a straight default-carries /// (NTB) vote. - type ExternalDefaultOrigin = EnsureRootOrAllGeneralCouncil; // TODO: When root is removed, change to `EnsureAllSetheumJuryOrAllGeneralCouncil`. + type ExternalDefaultOrigin = EnsureRootOrAllGeneralCouncil; /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote /// be tabled immediately and with a shorter voting/enactment period. - type FastTrackOrigin = EnsureRootOrTwoThirdsTechnicalCommittee; // TODO: When root is removed, change to `EnsureTwoThirdsSetheumJuryOrTwoThirdsTechnicalCommittee`. - type InstantOrigin = EnsureRootOrAllTechnicalCommittee; // TODO: When root is removed, change to `EnsureAllSetheumJuryOrAllTechnicalCommittee`. + type FastTrackOrigin = EnsureRootOrTwoThirdsTechnicalCommittee; + type InstantOrigin = EnsureRootOrAllTechnicalCommittee; type InstantAllowed = InstantAllowed; type FastTrackVotingPeriod = FastTrackVotingPeriod; // To cancel a proposal which has been passed, 2/3 of the council must agree to it. - type CancellationOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureHalfSetheumJuryOrTwoThirdsGeneralCouncil`. - type BlacklistOrigin = EnsureRootOrHalfSetheumJury; + type CancellationOrigin = EnsureRootOrTwoThirdsGeneralCouncil; + type BlacklistOrigin = EnsureRoot; // To cancel a proposal before it has been passed, the technical committee must be unanimous or - // Root must agree or half of SetheumJury must agree. - type CancelProposalOrigin = EnsureRootOrAllTechnicalCommittee; // TODO: When root is removed, change to `EnsureAllSetheumJuryOrAllTechnicalCommittee`. + // Root must agree. + type CancelProposalOrigin = EnsureRootOrAllTechnicalCommittee; // Any single technical committee member may veto a coming council proposal, however they can // only do it once and it lasts only for the cooloff period. - type VetoOrigin = pallet_collective::EnsureMember || EnsureMember; + type VetoOrigin = pallet_collective::EnsureMember; type CooloffPeriod = CooloffPeriod; type PreimageByteDeposit = PreimageByteDeposit; type OperationalPreimageOrigin = pallet_collective::EnsureMember; @@ -1020,7 +769,8 @@ impl setheum_democracy::Config for Runtime { type Scheduler = Scheduler; type PalletsOrigin = OriginCaller; type MaxVotes = MaxVotes; - type WeightInfo = setheum_democracy::weights::SubstrateWeight; + //TODO: might need to weight for Setheum + type WeightInfo = pallet_democracy::weights::SubstrateWeight; type MaxProposals = MaxProposals; } @@ -1068,13 +818,16 @@ impl DataFeeder for AggregatedDataProvider { } } +parameter_types! { + pub const GetNativeCurrencyId: CurrencyId = DRAM; + pub const SetterCurrencyId: CurrencyId = SETR; + pub const GetSetUSDCurrencyId: CurrencyId = SETUSD; +} + parameter_type_with_key! { pub ExistentialDeposits: |_currency_id: CurrencyId| -> Balance { match currency_id { CurrencyId::Token(symbol) => match symbol { - TokenSymbol::DNAR => Balance::max_value(), // unsupported - TokenSymbol::DRAM => Balance::max_value(*currency_id), // unsupported - TokenSymbol::SETR => cent(*currency_id), TokenSymbol::SETUSD => cent(*currency_id), TokenSymbol::SETEUR => cent(*currency_id), @@ -1082,16 +835,19 @@ parameter_type_with_key! { TokenSymbol::SETCHF => cent(*currency_id), TokenSymbol::SETSAR => cent(*currency_id) + TokenSymbol::DNAR | + TokenSymbol::DRAM | TokenSymbol::RENBTC | }, - CurrencyId::DexShare(_, _) => { - let dec = as CurrencyIdMapping>::decimals(*currency_id); - if let Some(dec) = dec { - // TODO: verify if this makes sense - 10u128.saturating_pow(dec as u32) + CurrencyId::DexShare(dex_share_0, _) => { + let currency_id_0: CurrencyId = (*dex_share_0).into(); + + // initial dex share amount is calculated based on currency_id_0, + // use the ED of currency_id_0 as the ED of lp token. + if currency_id_0 == GetNativeCurrencyId::get() { + NativeTokenExistentialDeposit::get() } else { - // TODO: update this before we enable ERC20 in DEX - Balance::max_value() // unsupported + Self::get(¤cy_id_0) } }, CurrencyId::Erc20(_) => Balance::max_value(), // not handled by orml-tokens @@ -1125,48 +881,14 @@ impl orml_tokens::Config for Runtime { parameter_types! { pub FiatUsdFixedPrice: Price = Price::saturating_from_rational(1, 1); - - pub const GetSetterPegOneCurrencyId: CurrencyId = GBP; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegTwoCurrencyId: CurrencyId = EUR; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegThreeCurrencyId: CurrencyId = KWD; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegFourCurrencyId: CurrencyId = JOD; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegFiveCurrencyId: CurrencyId = BHD; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegSixCurrencyId: CurrencyId = KYD; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegSevenCurrencyId: CurrencyId = OMR; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegEightCurrencyId: CurrencyId = CHF; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegNineCurrencyId: CurrencyId = GIP; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegTenCurrencyId: CurrencyId = USD; // Fiat pegs of the Setter (SETR). - - pub StableCurrencyIds: Vec = vec![ - SETR, SETUSD, SETEUR, SETGBP, SETCHF, SETSAR - ]; - pub FiatCurrencyIds: Vec = vec![ - USD, EUR, GBP, CHF, SAR, KWD, JOD, BHD, KYD, OMR, GIP - ]; } impl serp_prices::Config for Runtime { type Event = Event; type Source = AggregatedDataProvider; - type SetterCurrencyId = SetterCurrencyId; type GetSetUSDCurrencyId = GetSetUSDCurrencyId; - type GetFiatCHFCurrencyId = GetFiatCHFCurrencyId; - type GetFiatEURCurrencyId = GetFiatEURCurrencyId; - type GetFiatGBPCurrencyId = GetFiatGBPCurrencyId; - type GetFiatSARCurrencyId = GetFiatSARCurrencyId; - type GetFiatUSDCurrencyId = GetFiatUSDCurrencyId; type FiatUsdFixedPrice = FiatUsdFixedPrice; - type GetSetterPegOneCurrencyId = GetSetterPegOneCurrencyId; - type GetSetterPegTwoCurrencyId = GetSetterPegTwoCurrencyId; - type GetSetterPegThreeCurrencyId = GetSetterPegThreeCurrencyId; - type GetSetterPegFourCurrencyId = GetSetterPegFourCurrencyId; - type GetSetterPegFiveCurrencyId = GetSetterPegFiveCurrencyId; - type GetSetterPegSixCurrencyId = GetSetterPegSixCurrencyId; - type GetSetterPegSevenCurrencyId = GetSetterPegSevenCurrencyId; - type GetSetterPegEightCurrencyId = GetSetterPegEightCurrencyId; - type GetSetterPegNineCurrencyId = GetSetterPegNineCurrencyId; - type GetSetterPegTenCurrencyId = GetSetterPegTenCurrencyId; - type LockOrigin = EnsureRootOrTwoThirdsGeneralCouncil; + type LockOrigin = EnsureRootOrTwoThirdsFinancialCouncil; type DEX = Dex; type Currency = Currencies; type CurrencyIdMapping = EvmCurrencyIdMapping; @@ -1178,6 +900,7 @@ impl setheum_currencies::Config for Runtime { type MultiCurrency = Tokens; type NativeCurrency = BasicCurrencyAdapter; type GetNativeCurrencyId = GetNativeCurrencyId; + type SerpTreasury = SerpTreasury; type WeightInfo = weights::setheum_currencies::WeightInfo; type AddressMapping = EvmAddressMapping; type EVMBridge = EVMBridge; @@ -1332,7 +1055,6 @@ impl settmint_engine::Config for Runtime { type DefaultStandardExchangeRate = DefaultStandardExchangeRate; type MinimumStandardValue = MinimumStandardValue; type ReserveCurrencyId = GetReserveCurrencyId; - type PriceSource = SerpPrices; } parameter_types! { @@ -1347,30 +1069,29 @@ impl settmint_gateway::Config for Runtime { } parameter_types! { + pub const GetExchangeFee: (u32, u32) = (1, 1000); // 0.1% pub const TradingPathLimit: u32 = 3; pub EnabledTradingPairs: Vec = vec![ TradingPair::new(SETR, DNAR), TradingPair::new(SETR, DRAM), - TradingPair::new(SETR, SETUSD), TradingPair::new(SETR, SETEUR), TradingPair::new(SETR, SETGBP), TradingPair::new(SETR, SETCHF), TradingPair::new(SETR, SETSAR), - TradingPair::new(SETR, RENBTC), ]; } -impl dex::Config for Runtime { +impl setheum_dex::Config for Runtime { type Event = Event; type Currency = Currencies; + type GetExchangeFee = GetExchangeFee; type TradingPathLimit = TradingPathLimit; type PalletId = DexPalletId; type CurrencyIdMapping = EvmCurrencyIdMapping; - type WeightInfo = weights::dex::WeightInfo; - type UpdateOrigin = EnsureRootOrHalfExchangeCouncil; // TODO: When root is removed, change to `EnsureHalfSetheumJuryOrHalfExchangeCouncil`. - type ListingOrigin = EnsureRootOrHalfExchangeCouncil; // TODO: When root is removed, change to `EnsureHalfSetheumJuryOrHalfExchangeCouncil`. + type WeightInfo = weights::setheum_dex::WeightInfo; + type ListingOrigin = EnsureRootOrHalfFinancialCouncil; } parameter_types! { @@ -1411,6 +1132,27 @@ parameter_type_with_key! { }; } +parameter_types! { + pub MaxSwapSlippageCompareToOracle: Ratio = Ratio::saturating_from_rational(1, 2); + pub StableCurrencyIds: Vec = vec![SETR, SETUSD, SETEUR, SETGBP, SETCHF, SETSAR]; + pub DefaultFeeSwapPathList: Vec> = vec![ + vec![SETR, DNAR], + vec![SETUSD, SETR, DRAM] + vec![SETEUR, SETR, DRAM] + vec![SETGBP, SETR, DRAM] + vec![SETCHF, SETR, DRAM] + vec![SETSAR, SETR, DRAM] + ]; + pub DefaultSwapPathList: Vec> = vec![ + vec![SETR, DNAR], + vec![SETUSD, SETR, DNAR] + vec![SETEUR, SETR, DNAR] + vec![SETGBP, SETR, DNAR] + vec![SETCHF, SETR, DNAR] + vec![SETSAR, SETR, DNAR] + ]; +} + parameter_types! { pub MaxSwapSlippageCompareToOracle: Ratio = Ratio::saturating_from_rational(1, 2); pub DefaultFeeSwapPathList: Vec> = vec![vec![SETR, DNAR], vec![SETUSD, SETR, DNAR]]; @@ -1424,41 +1166,35 @@ impl serp_treasury::Config for Runtime { type GetNativeCurrencyId = GetNativeCurrencyId; type SetterCurrencyId = SetterCurrencyId; type GetSetUSDCurrencyId = GetSetUSDCurrencyId; - type DirhamCurrencyId = DirhamCurrencyId; + type DirhamCurrencyId = GetNativeCurrencyId; type CashDropPeriod = CashDropPeriod; type SettPayTreasuryAccountId = OneAccountId; type CashDropVaultAccountId = TwoAccountId; type CharityFundAccountId = CharityFundAccount; - type DefaultFeeSwapPathList = DefaultFeeSwapPathList; + type DefaultSwapPathList = DefaultSwapPathList; type Dex = Dex; type MaxSwapSlippageCompareToOracle = MaxSwapSlippageCompareToOracle; type TradingPathLimit = TradingPathLimit; type PriceSource = SerpPrices; type MinimumClaimableTransferAmounts = MinimumClaimableTransferAmounts; - type UpdateOrigin = EnsureSignedBy; + type UpdateOrigin = EnsureRootOrHalfFinancialCouncil; type PalletId = SerpTreasuryPalletId; type WeightInfo = weights::serp_treasury::WeightInfo; } -parameter_types! { - // All currency types except for native currency, Sort by fee charge order - pub AllNonNativeCurrencyIds: Vec = vec![ - DRAM, SETR, SETUSD, SETEUR, SETGBP, SETCHF, SETSAR, RENBTC - ]; -} - impl setheum_transaction_payment::Config for Runtime { - type AllNonNativeCurrencyIds = AllNonNativeCurrencyIds; type NativeCurrencyId = GetNativeCurrencyId; - type SetterCurrencyId = SetterCurrencyId; + type DefaultFeeSwapPathList = DefaultFeeSwapPathList; type Currency = Balances; type MultiCurrency = Currencies; type OnTransactionPayment = Treasury; type TransactionByteFee = TransactionByteFee; type WeightToFee = WeightToFee; - type FeeMultiplierUpdate = TargetedFeeAdjustment; + type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; type Dex = Dex; - type MaxSlippageSwapWithDex = MaxSlippageSwapWithDex; + type MaxSwapSlippageCompareToOracle = MaxSwapSlippageCompareToOracle; + type TradingPathLimit = TradingPathLimit; + type PriceSource = SerpPrices; type WeightInfo = weights::setheum_transaction_payment::WeightInfo; } @@ -1493,15 +1229,19 @@ impl setheum_evm_manager::Config for Runtime { } parameter_types! { - pub CreateClassDeposit: Balance = 20 * millicent(DNAR); - pub CreateTokenDeposit: Balance = 2 * millicent(DNAR); + pub CreateClassDeposit: Balance = 20 * millicent(DRAM); + pub CreateTokenDeposit: Balance = 2 * millicent(DRAM); + pub MaxAttributesBytes: u32 = 2048; } impl setheum_nft::Config for Runtime { type Event = Event; + type Currency = Balances; type CreateClassDeposit = CreateClassDeposit; type CreateTokenDeposit = CreateTokenDeposit; + type DataDepositPerByte = DataDepositPerByte; type PalletId = NftPalletId; + type MaxAttributesBytes = MaxAttributesBytes; type WeightInfo = weights::setheum_nft::WeightInfo; } @@ -1530,6 +1270,48 @@ parameter_types! { pub const MaxPending: u16 = 32; } +impl InstanceFilter for ProxyType { + fn filter(&self, c: &Call) -> bool { + match self { + // Always allowed Call::Utility no matter type. + // Only transactions allowed by Proxy.filter can be executed, + // otherwise `BadOrigin` will be returned in Call::Utility. + _ if matches!(c, Call::Utility(..)) => true, + ProxyType::Any => true, + ProxyType::CancelProxy => matches!(c, Call::Proxy(pallet_proxy::Call::reject_announcement(..))), + ProxyType::Governance => { + matches!( + c, + Call::Authority(..) + | Call::Democracy(..) + | Call::ShuraCouncil(..) + | Call::GeneralCouncil(..) + | Call::FinancialCouncil(..) + | Call::TechnicalCommittee(..) + | Call::Treasury(..) + | Call::Bounties(..) + | Call::Tips(..) + ) + } + ProxyType::Swap => { + matches!( + c, + Call::Dex(setheum_dex::Call::swap_with_exact_supply(..)) + | Call::Dex(setheum_dex::Call::swap_with_exact_target(..)) + ) + } + } + } + fn is_superset(&self, o: &Self) -> bool { + match (self, o) { + (x, y) if x == y => true, + (ProxyType::Any, _) => true, + (_, ProxyType::Any) => false, + _ => false, + } + } +} + impl pallet_proxy::Config for Runtime { type Event = Event; type Call = Call; @@ -1624,7 +1406,7 @@ impl setheum_evm::Config for Runtime { type DeveloperDeposit = DeveloperDeposit; type DeploymentFee = DeploymentFee; type TreasuryAccount = TreasuryAccount; - type FreeDeploymentOrigin = EnsureRootOrHalfGeneralCouncil; // TODO: When root is removed, change to `EnsureHalfSetheumJuryOrHalfGeneralCouncil`. + type FreeDeploymentOrigin = EnsureRootOrHalfGeneralCouncil; type WeightInfo = weights::setheum_evm::WeightInfo; } @@ -1653,11 +1435,27 @@ construct_runtime!( NFT: setheum_nft::{Pallet, Call, Event} = 7, Vesting: orml_vesting::{Pallet, Storage, Call, Event, Config} = 8, TransactionPayment: setheum_transaction_payment::{Pallet, Call, Storage} = 9, + // AirDrop: setheum_airdrop::{Pallet, Call, Storage, Event, Config} = 10, // Treasury - Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event} = 10, - Bounties: pallet_bounties::{Pallet, Call, Storage, Event} = 11, - Tips: pallet_tips::{Pallet, Call, Storage, Event} = 12, + Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event} = 11, + Bounties: pallet_bounties::{Pallet, Call, Storage, Event} = 12, + Tips: pallet_tips::{Pallet, Call, Storage, Event} = 13, + + // Utility + Utility: pallet_utility::{Pallet, Call, Event} = 14, + Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 15, + Recovery: pallet_recovery::{Pallet, Call, Storage, Event} = 16, + Proxy: pallet_proxy::{Pallet, Call, Storage, Event} = 17 , + Indices: pallet_indices::{Pallet, Call, Storage, Config, Event} = 18, + + // Consensus & Staking + Authorship: pallet_authorship::{Pallet, Call, Storage, Inherent} = 19, + Babe: pallet_babe::{Pallet, Call, Storage, Config, Inherent, ValidateUnsigned} = 20, + Grandpa: pallet_grandpa::{Pallet, Call, Storage, Config, Event, ValidateUnsigned} = 21, + Staking: pallet_staking::{Module, Call, Config, Storage, Event}, = 22 + Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 23, + Historical: pallet_session_historical::{Module} = 24, // Utility Utility: pallet_utility::{Pallet, Call, Event} = 13, @@ -1670,56 +1468,54 @@ construct_runtime!( Authorship: pallet_authorship::{Pallet, Call, Storage, Inherent} = 18, Babe: pallet_babe::{Pallet, Call, Storage, Config, Inherent, ValidateUnsigned} = 19, Grandpa: pallet_grandpa::{Pallet, Call, Storage, Config, Event, ValidateUnsigned} = 20, - Staking: serp_staking::{Pallet, Call, Config, Storage, Event} = 21, + Staking: pallet_staking::{Module, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 22, Historical: pallet_session_historical::{Module} = 23, // Governance - GeneralCouncil: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 24, - GeneralCouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 25, - SetheumJury: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 26, - SetheumJuryMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 27, - FinancialCouncil: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 28, - FinancialCouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 29, - ExchangeCouncil: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 30, - ExchangeCouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 31, - TechnicalCommittee: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 32, - TechnicalCommitteeMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 33, - Authority: orml_authority::{Pallet, Call, Event, Origin} = 34, + ShuraCouncil: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 25, + ShuraCouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 26, + GeneralCouncil: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 27, + GeneralCouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 28, + FinancialCouncil: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 29, + FinancialCouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 30, + TechnicalCommittee: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 31, + TechnicalCommitteeMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 32, + Authority: orml_authority::{Pallet, Call, Event, Origin} = 33, + Democracy: pallet_democracy::{Pallet, Call, Storage, Config, Event} = 34, // Oracle // // NOTE: OperatorMembership must be placed after Oracle or else will have race condition on initialization SetheumOracle: orml_oracle::::{Pallet, Storage, Call, Config, Event} = 35, - // OperatorMembership must be placed after Oracle or else will have race condition on initialization - OperatorMembershipSetheum: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 36, + OperatorMembershipSetheum: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 36, // ORML Core - OrmlNFT: orml_nft::{Pallet, Storage, Config} = 39, + OrmlNFT: orml_nft::{Pallet, Storage, Config} = 37, // SERP Core - SerpPrices: serp_prices::{Pallet, Storage, Call, Event} = 41, - SerpTreasury: serp_treasury::{Pallet, Storage, Call, Config, Event} = 43, + SerpPrices: serp_prices::{Pallet, Storage, Call, Event} = 38, + SerpTreasury: serp_treasury::{Pallet, Storage, Call, Config, Event} = 39, // Dex - Dex: dex::{Pallet, Storage, Call, Event, Config} = 44, + Dex: setheum_dex::{Pallet, Storage, Call, Event, Config} = 40, // Settmint - SettmintEngine: settmint_engine::{Pallet, Storage, Call, Event, Config, ValidateUnsigned} = 46, - SettmintGateway: settmint_gateway::{Pallet, Storage, Call, Event} = 47, - SettmintManager: settmint_manager::{Pallet, Storage, Call, Event} = 48, + SettmintEngine: settmint_engine::{Pallet, Storage, Call, Event, Config, ValidateUnsigned} = 41, + SettmintGateway: settmint_gateway::{Pallet, Storage, Call, Event} = 42, + SettmintManager: settmint_manager::{Pallet, Storage, Call, Event} = 43, // Smart contracts // Setheum EVM (SEVM) - EVM: setheum_evm::{Pallet, Config, Call, Storage, Event} = 49, - EVMBridge: setheum_evm_bridge::{Pallet} = 50, - EvmAccounts: setheum_evm_accounts::{Pallet, Call, Storage, Event} = 51, - EvmManager: setheum_evm_manager::{Pallet, Storage} = 52, + EVM: setheum_evm::{Pallet, Config, Call, Storage, Event} = 44, + EVMBridge: setheum_evm_bridge::{Pallet} = 45, + EvmAccounts: setheum_evm_accounts::{Pallet, Call, Storage, Event} = 46, + EvmManager: setheum_evm_manager::{Pallet, Storage} = 47, // Bridges - // RenVmBridge: setheum_renvm_bridge::{Pallet, Call, Config, Storage, Event, ValidateUnsigned} = 53, - // ChainBridge: chainbridge::{Pallet, Call, Storage, Event} = 54, - // SetheumChainBridge: setheum_chainbridge::{Pallet, Call, Storage, Event} = 55, + // RenVmBridge: setheum_renvm_bridge::{Pallet, Call, Config, Storage, Event, ValidateUnsigned} = 48, + // ChainBridge: chainbridge::{Pallet, Call, Storage, Event} = 49, + // SetheumChainBridge: setheum_chainbridge::{Pallet, Call, Storage, Event} = 50, // Dev Sudo: pallet_sudo::{Pallet, Call, Config, Storage, Event} = 255, @@ -2082,7 +1878,7 @@ impl_runtime_apis! { // TODO: Update! orml_add_benchmark!(params, batches, orml_authority, benchmarking::authority); orml_add_benchmark!(params, batches, orml_currencies, benchmarking::currencies); - orml_add_benchmark!(params, batches, dex, benchmarking::dex); + orml_add_benchmark!(params, batches, setheum_dex, benchmarking::setheum_dex); orml_add_benchmark!(params, batches, setheum_evm_accounts, benchmarking::evm_accounts); orml_add_benchmark!(params, batches, setheum_evm, benchmarking::evm); orml_add_benchmark!(params, batches, orml_oracle, benchmarking::oracle); @@ -2094,6 +1890,8 @@ impl_runtime_apis! { add_benchmark!(params, batches, nft, NftBench::); + orml_add_benchmark!(params, batches, setheum_chainbridge, benchmarking::setheum_chainbridge); + if batches.is_empty() { return Err("Benchmark not found for this module.".into()) } Ok(batches) } @@ -2127,4 +1925,10 @@ mod tests { ); } -} \ No newline at end of file +} + +#[test] +fn transfer() { + let t = Call::System(frame_system::Call::remark(vec![1, 2, 3])).encode(); + println!("t: {:?}", t); +} From 34492515537eaba555c85eddedaeaa0ab6862274 Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Tue, 31 Aug 2021 21:28:28 +0800 Subject: [PATCH 05/22] Update Runtimes --- runtime/common/src/lib.rs | 150 +++++++- runtime/newrome/src/lib.rs | 760 +++++++++++++------------------------ 2 files changed, 411 insertions(+), 499 deletions(-) diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index de0541f7c..123416088 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -58,7 +58,6 @@ pub type TimeStampedPrice = orml_oracle::TimestampedValue Balance { items as Balance * 15 * cent(currency_id) + (bytes as Balance) * 6 * cent(currency_id) } +pub type GeneralCouncilInstance = pallet_collective::Instance1; +pub type ShuraCouncilInstance = pallet_collective::Instance2; +pub type FinancialCouncilInstance = pallet_collective::Instance3; +pub type TechnicalCommitteeInstance = pallet_collective::Instance4; + +pub type GeneralCouncilMembershipInstance = pallet_membership::Instance1; +pub type ShuraCouncilMembershipInstance = pallet_membership::Instance2; +pub type FinancialCouncilMembershipInstance = pallet_membership::Instance3; +pub type TechnicalCommitteeMembershipInstance = pallet_membership::Instance4; +pub type OperatorMembershipInstanceSetheum = pallet_membership::Instance5; + +// General Council +pub type EnsureRootOrAllGeneralCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, GeneralCouncilInstance>, +>; + +pub type EnsureRootOrHalfGeneralCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, GeneralCouncilInstance>, +>; + +pub type EnsureRootOrOneThirdsGeneralCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_1, _3, AccountId, GeneralCouncilInstance>, +>; + +pub type EnsureRootOrTwoThirdsGeneralCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, GeneralCouncilInstance>, +>; + +pub type EnsureRootOrThreeFourthsGeneralCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, GeneralCouncilInstance>, +>; + +// Shura Council +pub type EnsureRootOrAllShuraCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, ShuraCouncilInstance>, +>; + +pub type EnsureRootOrHalfShuraCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, ShuraCouncilInstance>, +>; + +pub type EnsureRootOrOneThirdsShuraCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_1, _3, AccountId, ShuraCouncilInstance>, +>; + +pub type EnsureRootOrTwoThirdsShuraCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, ShuraCouncilInstance>, +>; + +pub type EnsureRootOrThreeFourthsShuraCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, ShuraCouncilInstance>, +>; + +// Financial Council +pub type EnsureRootOrAllFinancialCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, FinancialCouncilInstance>, +>; + +pub type EnsureRootOrHalfFinancialCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, FinancialCouncilInstance>, +>; + +pub type EnsureRootOrOneThirdsFinancialCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_1, _3, AccountId, FinancialCouncilInstance>, +>; + +pub type EnsureRootOrTwoThirdsFinancialCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, FinancialCouncilInstance>, +>; + +pub type EnsureRootOrThreeFourthsFinancialCouncil = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, FinancialCouncilInstance>, +>; + +// Technical Committee Council +pub type EnsureRootOrAllTechnicalCommittee = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCommitteeInstance>, +>; + +pub type EnsureRootOrHalfTechnicalCommittee = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, TechnicalCommitteeInstance>, +>; + +pub type EnsureRootOrOneThirdsTechnicalCommittee = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_1, _3, AccountId, TechnicalCommitteeInstance>, +>; + +pub type EnsureRootOrTwoThirdsTechnicalCommittee = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCommitteeInstance>, +>; + +pub type EnsureRootOrThreeFourthsTechnicalCommittee = EnsureOneOf< + AccountId, + EnsureRoot, + pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, TechnicalCommitteeInstance>, +>; + +/// The type used to represent the kinds of proxying allowed. +#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, MaxEncodedLen)] +pub enum ProxyType { + Any, + CancelProxy, + Governance, + Swap, +} +impl Default for ProxyType { + fn default() -> Self { + Self::Any + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/runtime/newrome/src/lib.rs b/runtime/newrome/src/lib.rs index 8c1a66809..d5bcaa199 100644 --- a/runtime/newrome/src/lib.rs +++ b/runtime/newrome/src/lib.rs @@ -106,10 +106,19 @@ pub use primitives::{ }; pub use runtime_common::{ cent, deposit, dollar, microcent, millicent, BlockLength, BlockWeights, - ExchangeRate, GasToWeight, OffchainSolutionWeightLimit, Price, Rate, Ratio, - RuntimeBlockLength, RuntimeBlockWeights,SystemContractsFilter, TimeStampedPrice, + EnsureRootOrAllGeneralCouncil, EnsureRootOrAllTechnicalCommittee, + EnsureRootOrHalfFinancialCouncil, EnsureRootOrHalfGeneralCouncil, + EnsureRootOrHalfHomaCouncil, EnsureRootOrOneThirdsTechnicalCommittee, + EnsureRootOrThreeFourthsGeneralCouncil, EnsureRootOrTwoThirdsGeneralCouncil, + EnsureRootOrTwoThirdsTechnicalCommittee, ExchangeRate, FinancialCouncilInstance, + FinancialCouncilMembershipInstance, GasToWeight, GeneralCouncilInstance, + GeneralCouncilMembershipInstance, OperatorMembershipInstanceSetheum, + OffchainSolutionWeightLimit, Price, ProxyType, Rate, Ratio, RuntimeBlockLength, + RuntimeBlockWeights, SystemContractsFilter, EnsureRootOrAllShuraCouncil, + EnsureRootOrHalfShuraCouncil, EnsureRootOrThreeFourthsShuraCouncil, + EnsureRootOrTwoThirdsShuraCouncil, ShuraCouncilInstance, + ShuraCouncilMembershipInstance, TimeStampedPrice, DNAR, DRAM, SETR, SETUSD, SETEUR, SETGBP, SETCHF, SETSAR, RENBTC, - USD, EUR, GBP, CHF, SAR, KWD, JOD, BHD, KYD, OMR, GIP }; mod authority; mod benchmarking; @@ -120,7 +129,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("newrome"), impl_name: create_runtime_str!("newrome"), authoring_version: 1, - spec_version: 1000, + spec_version: 258, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -165,7 +174,7 @@ pub fn get_all_module_accounts() -> Vec { } parameter_types! { - pub const BlockHashCount: BlockNumber = 900; // mortal tx can be valid up to 4 hour after signing + pub const BlockHashCount: BlockNumber = 3600; // mortal tx can be valid up to 4 hour after signing pub const Version: RuntimeVersion = VERSION; pub const SS58Prefix: u16 = 258; // Ss58AddressFormat::SetheumAccount } @@ -181,14 +190,30 @@ impl Filter for BaseCallFilter { Call::Scheduler(_) | Call::Utility(_) | Call::Multisig(_) | // Sudo Call::Sudo(_) | - // PoA - Call::Authority(_) | Call::GeneralCouncil(_) | Call::GeneralCouncilMembership(_) | - Call::SetheumJury(_) | Call::SetheumJuryMembership(_) | + // Councils + Call::Authority(_) | + Call::ShuraCouncil(_) | Call::ShuraCouncilMembership(_) | + Call::GeneralCouncil(_) | Call::GeneralCouncilMembership(_) | Call::FinancialCouncil(_) | Call::FinancialCouncilMembership(_) | - Call::ExchangeCouncil(_) | Call::ExchangeCouncilMembership(_) | Call::TechnicalCommittee(_) | Call::TechnicalCommitteeMembership(_) | // Oracle Call::SetheumOracle(_) | Call::OperatorMembershipSetheum(_) + // Democracy + Call::Democracy(_) | Call::Treasury(_) | Call::Bounties(_) | Call::Tips(_) | + // Vesting + Call::Vesting(_) | + // TransactionPayment + Call::TransactionPayment(_) | + // Tokens + Call::Balances(_) | Call::Currencies(_) | + // NFT + Call::NFT(_) | + // DEX + Call::Dex(_) | + // Serp + Call::Prices(_) | Call::SerpTreasury(_) | + // Serttmint + Call::SettmintGateway(_)| Call::SettmintEngine(_) ) } } @@ -259,7 +284,7 @@ impl pallet_grandpa::Config for Runtime { } parameter_types! { - pub IndexDeposit: Balance = dollar(DNAR); + pub IndexDeposit: Balance = dollar(DRAM); } impl pallet_indices::Config for Runtime { @@ -294,7 +319,7 @@ impl pallet_authorship::Config for Runtime { } parameter_types! { - pub NativeTokenExistentialDeposit: Balance = 10 * cent(DNAR); // 0.1 DNAR + pub NativeTokenExistentialDeposit: Balance = 10 * cent(DRAM); // 0.1 DRAM // For weight estimation, we assume that the most locks on an individual account will be 50. // This number may need to be adjusted in the future if this assumption no longer holds true. pub const MaxLocks: u32 = 50; @@ -314,7 +339,7 @@ impl pallet_balances::Config for Runtime { } parameter_types! { - pub TransactionByteFee: Balance = millicent(DNAR); + pub TransactionByteFee: Balance = millicent(DRAM); /// The portion of the `NORMAL_DISPATCH_RATIO` that we adjust the fees with. Blocks filled less /// than this will decrease the weight and more will increase. pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25); @@ -335,233 +360,37 @@ impl pallet_sudo::Config for Runtime { type Call = Call; } -type EnsureRootOrAllGeneralCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, GeneralCouncilInstance>, ->; - -type EnsureRootOrAllSetheumJury = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, SetheumJuryInstance>, ->; - -type EnsureAllSetheumJuryOrAllGeneralCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, GeneralCouncilInstance>, ->; - -type EnsureRootOrOneThirdSetheumJury = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _3, AccountId, SetheumJuryInstance>, ->; - -type EnsureRootOrTwoThirdsSetheumJury = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, SetheumJuryInstance>, ->; - -type EnsureRootOrHalfSetheumJury = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, ->; - -type EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, GeneralCouncilInstance>, ->; - -type EnsureQuarterSetheumJuryOrHalfGeneralCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _4, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, GeneralCouncilInstance>, ->; - -type EnsureOneThirdSetheumJuryOrHalfGeneralCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _3, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, GeneralCouncilInstance>, ->; - -type EnsureHalfSetheumJuryOrHalfGeneralCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, GeneralCouncilInstance>, ->; - -type EnsureRootOrHalfGeneralCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, GeneralCouncilInstance>, ->; - -type EnsureRootOrHalfFinancialCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, FinancialCouncilInstance>, ->; - -type EnsureHalfSetheumJuryOrHalfFinancialCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, FinancialCouncilInstance>, ->; - -type EnsureRootOrTwoThirdsFinancialCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, FinancialCouncilInstance>, ->; - -type EnsureHalfSetheumJuryOrTwoThirdsFinancialCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, FinancialCouncilInstance>, ->; - -type EnsureRootOrAllFinancialCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, FinancialCouncilInstance>, ->; - -type EnsureHalfSetheumJuryOrAllFinancialCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, FinancialCouncilInstance>, ->; - -type EnsureTwoThirdsSetheumJuryOrAllFinancialCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, FinancialCouncilInstance>, ->; - -type EnsureAllSetheumJuryOrAllFinancialCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, FinancialCouncilInstance>, ->; - -type EnsureTwoThirdsFinancialCouncilOrTwoThirdsExchangeCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, FinancialCouncilInstance>, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureRootOrHalfExchangeCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureHalfSetheumJuryOrHalfExchangeCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureRootOrTwoThirdsExchangeCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureHalfFinancialCouncilOrTwoThirdsExchangeCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, FinancialCouncilInstance>, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureHalfSetheumJuryOrTwoThirdsExchangeCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureRootOrAllExchangeCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureHalfSetheumJuryOrAllExchangeCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureTwoThirdsSetheumJuryOrAllExchangeCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureAllSetheumJuryOrAllExchangeCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _1, AccountId, ExchangeCouncilInstance>, ->; - -type EnsureRootOrTwoThirdsGeneralCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, GeneralCouncilInstance>, ->; - -type EnsureTwoThirdsSetheumJuryOrTwoThirdsGeneralCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, GeneralCouncilInstance>, ->; - -type EnsureRootOrThreeFourthsGeneralCouncil = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_3, _4, AccountId, GeneralCouncilInstance>, ->; - -type EnsureRootOrThreeFourthsSetheumJury = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_3, _4, AccountId, SetheumJuryInstance>, ->; - -type EnsureThreeFourthsSetheumJuryOrThreeFourthsGeneralCouncil = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_3, _4, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_3, _4, AccountId, GeneralCouncilInstance>, ->; - -type EnsureRootOrOneThirdsTechnicalCommittee = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_1, _3, AccountId, TechnicalCommitteeInstance>, ->; - -type EnsureOneThirdsSetheumJuryOrOneThirdsTechnicalCommittee = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_1, _3, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_1, _3, AccountId, TechnicalCommitteeInstance>, ->; +parameter_types! { + pub const ShuraCouncilMotionDuration: BlockNumber = 3 * DAYS; + pub const ShuraCouncilMaxProposals: u32 = 20; + pub const ShuraCouncilMaxMembers: u32 = 30; +} -type EnsureTwoThirdsSetheumJuryOrTwoThirdsTechnicalCommittee = EnsureOneOf< - AccountId, - EnsureRoot, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, TechnicalCommitteeInstance>, ->; +type ShuraCouncilInstance = pallet_collective::Instance2; +impl pallet_collective::Config for Runtime { + type Origin = Origin; + type Proposal = Call; + type Event = Event; + type MotionDuration = ShuraCouncilMotionDuration; + type MaxProposals = ShuraCouncilMaxProposals; + type MaxMembers = ShuraCouncilMaxMembers; + type DefaultVote = pallet_collective::PrimeDefaultVote; + type WeightInfo = (); +} -type EnsureRootOrTwoThirdsTechnicalCommittee = EnsureOneOf< - AccountId, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, SetheumJuryInstance>, - pallet_collective::EnsureProportionMoreThan<_2, _3, AccountId, TechnicalCommitteeInstance>, ->; +type ShuraCouncilMembershipInstance = pallet_membership::Instance2; +impl pallet_membership::Config for Runtime { + type Event = Event; + type AddOrigin = EnsureRootOrThreeFourthsShuraCouncil; + type RemoveOrigin = EnsureRootOrThreeFourthsShuraCouncil; + type SwapOrigin = EnsureRootOrThreeFourthsShuraCouncil; + type ResetOrigin = EnsureRootOrThreeFourthsShuraCouncil; + type PrimeOrigin = EnsureRootOrThreeFourthsShuraCouncil; + type MembershipInitialized = ShuraCouncil; + type MembershipChanged = ShuraCouncil; + type MaxMembers = ShuraCouncilMaxMembers; + type WeightInfo = (); +} parameter_types! { pub const GeneralCouncilMotionDuration: BlockNumber = 3 * DAYS; @@ -584,53 +413,21 @@ impl pallet_collective::Config for Runtime { type GeneralCouncilMembershipInstance = pallet_membership::Instance1; impl pallet_membership::Config for Runtime { type Event = Event; - type AddOrigin = EnsureRootOrThreeFourthsGeneralCouncil; - type RemoveOrigin = EnsureRootOrThreeFourthsGeneralCouncil; - type SwapOrigin = EnsureRootOrThreeFourthsGeneralCouncil; - type ResetOrigin = EnsureRootOrThreeFourthsGeneralCouncil; - type PrimeOrigin = EnsureRootOrThreeFourthsGeneralCouncil; + type AddOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type RemoveOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type SwapOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type ResetOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type PrimeOrigin = EnsureRootOrTwoThirdsShuraCouncil; type MembershipInitialized = GeneralCouncil; type MembershipChanged = GeneralCouncil; type MaxMembers = GeneralCouncilMaxMembers; type WeightInfo = (); } -parameter_types! { - pub const SetheumJuryMotionDuration: BlockNumber = 3 * DAYS; - pub const SetheumJuryMaxProposals: u32 = 50; - pub const SetheumJuryMaxMembers: u32 = 50; -} - -type SetheumJuryInstance = pallet_collective::Instance2; -impl pallet_collective::Config for Runtime { - type Origin = Origin; - type Proposal = Call; - type Event = Event; - type MotionDuration = SetheumJuryMotionDuration; - type MaxProposals = SetheumJuryMaxProposals; - type MaxMembers = SetheumJuryMaxMembers; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = (); -} - -type SetheumJuryMembershipInstance = pallet_membership::Instance2; -impl pallet_membership::Config for Runtime { - type Event = Event; - type AddOrigin = EnsureRootOrThreeFourthsSetheumJury; - type RemoveOrigin = EnsureRootOrThreeFourthsSetheumJury; - type SwapOrigin = EnsureRootOrThreeFourthsSetheumJury; - type ResetOrigin = EnsureRootOrThreeFourthsSetheumJury; - type PrimeOrigin = EnsureRootOrThreeFourthsSetheumJury; - type MembershipInitialized = SetheumJury; - type MembershipChanged = SetheumJury; - type MaxMembers = SetheumJuryMaxMembers; - type WeightInfo = (); -} - parameter_types! { pub const FinancialCouncilMotionDuration: BlockNumber = 3 * DAYS; - pub const FinancialCouncilMaxProposals: u32 = 50; - pub const FinancialCouncilMaxMembers: u32 = 50; + pub const FinancialCouncilMaxProposals: u32 = 20; + pub const FinancialCouncilMaxMembers: u32 = 30; } type FinancialCouncilInstance = pallet_collective::Instance3; @@ -648,56 +445,24 @@ impl pallet_collective::Config for Runtime { type FinancialCouncilMembershipInstance = pallet_membership::Instance3; impl pallet_membership::Config for Runtime { type Event = Event; - type AddOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type RemoveOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type SwapOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type ResetOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type PrimeOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. + type AddOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type RemoveOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type SwapOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type ResetOrigin = EnsureRootOrTwoThirdsShuraCouncil; + type PrimeOrigin = EnsureRootOrTwoThirdsShuraCouncil; type MembershipInitialized = FinancialCouncil; type MembershipChanged = FinancialCouncil; type MaxMembers = FinancialCouncilMaxMembers; type WeightInfo = (); } -parameter_types! { - pub const ExchangeCouncilMotionDuration: BlockNumber = 3 * DAYS; - pub const ExchangeCouncilMaxProposals: u32 = 50; - pub const ExchangeCouncilMaxMembers: u32 = 50; -} - -type ExchangeCouncilInstance = pallet_collective::Instance4; -impl pallet_collective::Config for Runtime { - type Origin = Origin; - type Proposal = Call; - type Event = Event; - type MotionDuration = ExchangeCouncilMotionDuration; - type MaxProposals = ExchangeCouncilMaxProposals; - type MaxMembers = ExchangeCouncilMaxMembers; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = (); -} - -type ExchangeCouncilMembershipInstance = pallet_membership::Instance4; -impl pallet_membership::Config for Runtime { - type Event = Event; - type AddOrigin = EnsureRootOrTwoThirdsExchangeCouncil; - type RemoveOrigin = EnsureRootOrTwoThirdsExchangeCouncil; - type SwapOrigin = EnsureRootOrTwoThirdsExchangeCouncil; - type ResetOrigin = EnsureRootOrTwoThirdsExchangeCouncil; - type PrimeOrigin = EnsureRootOrTwoThirdsExchangeCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsFinancialCouncilOrTwoThirdsExchangeCouncil`. - type MembershipInitialized = ExchangeCouncil; - type MembershipChanged = ExchangeCouncil; - type MaxMembers = ExchangeCouncilMaxMembers; - type WeightInfo = (); -} - parameter_types! { pub const TechnicalCommitteeMotionDuration: BlockNumber = 3 * DAYS; pub const TechnicalCommitteeMaxProposals: u32 = 50; pub const TechnicalCouncilMaxMembers: u32 = 50; } -type TechnicalCommitteeInstance = pallet_collective::Instance5; +type TechnicalCommitteeInstance = pallet_collective::Instance4; impl pallet_collective::Config for Runtime { type Origin = Origin; type Proposal = Call; @@ -709,15 +474,15 @@ impl pallet_collective::Config for Runtime { type WeightInfo = (); } -type TechnicalCommitteeMembershipInstance = pallet_membership::Instance5; +type TechnicalCommitteeMembershipInstance = pallet_membership::Instance4; impl pallet_membership::Config for Runtime { type Event = Event; - type AddOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type RemoveOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type SwapOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type ResetOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type PrimeOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. + type AddOrigin = EnsureRootOrTwoThirdsGeneralCouncil; + type RemoveOrigin = EnsureRootOrTwoThirdsGeneralCouncil; + type SwapOrigin = EnsureRootOrTwoThirdsGeneralCouncil; + type ResetOrigin = EnsureRootOrTwoThirdsGeneralCouncil; + type PrimeOrigin = EnsureRootOrTwoThirdsGeneralCouncil; type MembershipInitialized = TechnicalCommittee; type MembershipChanged = TechnicalCommittee; type MaxMembers = TechnicalCouncilMaxMembers; @@ -728,14 +493,14 @@ parameter_types! { pub const OracleMaxMembers: u32 = 50; } -type OperatorMembershipInstanceSetheum = pallet_membership::Instance6; +type OperatorMembershipInstanceSetheum = pallet_membership::Instance5; impl pallet_membership::Config for Runtime { type Event = Event; - type AddOrigin = EnsureRootOrTwoThirdsGeneralCouncil; - type RemoveOrigin = EnsureRootOrTwoThirdsGeneralCouncil; - type SwapOrigin = EnsureRootOrTwoThirdsGeneralCouncil; - type ResetOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. - type PrimeOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureTwoThirdsJuryOrTwoThirdsGeneralCouncil`. + type AddOrigin = EnsureRootOrTwoThirdsFinancialCouncil; + type RemoveOrigin = EnsureRootOrTwoThirdsFinancialCouncil; + type SwapOrigin = EnsureRootOrTwoThirdsFinancialCouncil; + type ResetOrigin = EnsureRootOrTwoThirdsFinancialCouncil; + type PrimeOrigin = EnsureRootOrTwoThirdsFinancialCouncil; type MembershipInitialized = (); type MembershipChanged = SetheumOracle; type MaxMembers = OracleMaxMembers; @@ -791,7 +556,7 @@ impl ContainsLengthBound for GeneralCouncilProvider { parameter_types! { pub const ProposalBond: Permill = Permill::from_percent(5); - pub ProposalBondMinimum: Balance = 2 * dollar(DNAR); + pub ProposalBondMinimum: Balance = 2 * dollar(DRAM); pub const SpendPeriod: BlockNumber = 7 * DAYS; pub const Burn: Permill = Permill::from_percent(0); @@ -802,7 +567,7 @@ parameter_types! { pub const BountyDepositPayoutDelay: BlockNumber = DAYS; pub const BountyUpdatePeriod: BlockNumber = 7 * DAYS; pub const BountyCuratorDeposit: Permill = Permill::from_percent(50); - pub BountyValueMinimum: Balance = 5 * dollar(DNAR); + pub BountyValueMinimum: Balance = 5 * dollar(DRAM); pub DataDepositPerByte: Balance = deposit(0, 1); pub const MaximumReasonLength: u32 = 16384; pub const MaxApprovals: u32 = 100; @@ -812,7 +577,7 @@ impl pallet_treasury::Config for Runtime { type PalletId = TreasuryPalletId; type Currency = Balances; type ApproveOrigin = EnsureRootOrHalfGeneralCouncil; - type RejectOrigin = EnsureRootOrHalfGeneralCouncil; // TODO: When root is removed, change to `EnsureHalfSetheumJuryOrHalfGeneralCouncil`. + type RejectOrigin = EnsureRootOrHalfGeneralCouncil; type Event = Event; type OnSlash = (); type ProposalBond = ProposalBond; @@ -848,7 +613,6 @@ impl pallet_tips::Config for Runtime { type WeightInfo = (); } -// TODO: Update to `serp-staking` and it's allied implementations parameter_types! { pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17); } @@ -883,17 +647,10 @@ pallet_staking_reward_curve::build! { } parameter_types! { - // TODO: Update to match a 1:100 ratio of setheum's halving system. - pub const SessionsPerEra: sp_staking::SessionIndex = 1; // 1 hours - pub const BondingDuration: serp_staking::EraIndex = 2; // 2 hours - pub const SlashDeferDuration: serp_staking::EraIndex = 2; // 2 hours + pub const SessionsPerEra: sp_staking::SessionIndex = 3; // 3 hours + pub const BondingDuration: pallet_staking::EraIndex = 4; // 12 hours + pub const SlashDeferDuration: pallet_staking::EraIndex = 2; // 6 hours pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE; - /// The number of eras between each halvening, - /// 168 eras (7 days, each era is 1 hour) halving interval. - pub const HalvingInterval: EraIndex = 168; - /// The per-era issuance before any halvenings. - /// Decimal places should be accounted for here. - pub const InitialIssuance: Balance = 5_760_000 * dollar(DNAR); pub const MaxNominatorRewardedPerValidator: u32 = 64; pub const ElectionLookahead: BlockNumber = EPOCH_DURATION_IN_BLOCKS / 4; pub const MaxIterations: u32 = 5; @@ -901,17 +658,14 @@ parameter_types! { pub MinSolutionScoreBump: Perbill = Perbill::from_rational_approximation(5u32, 10_000); } -impl serp_staking::Config for Runtime { +impl pallet_staking::Config for Runtime { type Currency = Balances; type UnixTime = Timestamp; type CurrencyToVote = U128CurrencyToVote; - type RewardRemainder = Treasury; + type RewardRemainder = AcalaTreasury; type Event = Event; - type Slash = Treasury; // send the slashed funds to the pallet treasury. + type Slash = AcalaTreasury; // send the slashed funds to the pallet treasury. type Reward = (); // rewards are minted from the void - type HalvingInterval = HalvingInterval; // halving interval for native currency rewards. - type InitialIssuance = InitialIssuance; // initial issuance for native currency rewards. - type SerpTreasury = SerpTreasury; type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; type SlashDeferDuration = SlashDeferDuration; @@ -931,10 +685,10 @@ impl serp_staking::Config for Runtime { } parameter_types! { - pub ConfigDepositBase: Balance = 10 * cent(DNAR); - pub FriendDepositFactor: Balance = cent(DNAR); + pub ConfigDepositBase: Balance = 10 * cent(DRAM); + pub FriendDepositFactor: Balance = cent(DRAM); pub const MaxFriends: u16 = 9; - pub RecoveryDeposit: Balance = 10 * cent(DNAR); + pub RecoveryDeposit: Balance = 10 * cent(DRAM); } impl pallet_recovery::Config for Runtime { @@ -948,72 +702,48 @@ impl pallet_recovery::Config for Runtime { } parameter_types! { - pub const LaunchPeriod: BlockNumber = 28 * DAYS; - pub const VotingPeriod: BlockNumber = 28 * DAYS; + pub const LaunchPeriod: BlockNumber = 5 * DAYS; + pub const VotingPeriod: BlockNumber = 5 * DAYS; pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS; - pub MinimumDeposit: Balance = 100 * dollar(); - pub GoldenMinimumDepositMultiple: u32 = 1; // 1x of the `MinimumDeposit` is minimum deposit for DNAR (1). - pub SetterMinimumDepositMultiple: u32 = 2; // 2x of the `MinimumDeposit` is minimum deposit for SETR (2). - pub SilverMinimumDepositMultiple: u32 = 3; // 3x of the `MinimumDeposit` is minimum deposit for DRAM (3). - pub const EnactmentPeriod: BlockNumber = 28 * DAYS; + pub MinimumDeposit: Balance = 100 * dollar(DRAM); + pub const EnactmentPeriod: BlockNumber = 2 * DAYS; pub const CooloffPeriod: BlockNumber = 7 * DAYS; + pub PreimageByteDeposit: Balance = deposit(0, 1); + pub const InstantAllowed: bool = true; pub const MaxVotes: u32 = 100; pub const MaxProposals: u32 = 100; - pub PreimageByteDeposit: Balance = cent(DNAR); - pub const InstantAllowed: bool = true; - pub const GovernanceCurrencyIds: Vec = vec![DNAR, SETR, DRAM]; } -parameter_types! { - pub const GetNativeCurrencyId: CurrencyId = DNAR; - pub const SetterCurrencyId: CurrencyId = SETR; - pub const DirhamCurrencyId: CurrencyId = DRAM; - pub const GetSetUSDCurrencyId: CurrencyId = SETUSD; - pub const GetFiatCHFCurrencyId: CurrencyId = CHF; - pub const GetFiatEURCurrencyId: CurrencyId = EUR; - pub const GetFiatGBPCurrencyId: CurrencyId = GBP; - pub const GetFiatSARCurrencyId: CurrencyId = SAR; - pub const GetFiatUSDCurrencyId: CurrencyId = USD; -} - -impl setheum_democracy::Config for Runtime { +impl pallet_democracy::Config for Runtime { type Proposal = Call; type Event = Event; type Currency = Balances; - type MultiCurrency = Tokens; type EnactmentPeriod = EnactmentPeriod; type LaunchPeriod = LaunchPeriod; type VotingPeriod = VotingPeriod; - type GovernanceCurrencyIds = GovernanceCurrencyIds; - type NativeCurrencyId = NativeCurrencyId; - type DirhamCurrencyId = DirhamCurrencyId; - type SetterCurrencyId = SetterCurrencyId; type MinimumDeposit = MinimumDeposit; - type GoldenMinimumDepositMultiple = GoldenMinimumDepositMultiple; - type SetterMinimumDepositMultiple = SetterMinimumDepositMultiple; - type SilverMinimumDepositMultiple = SilverMinimumDepositMultiple; /// A straight majority of the council can decide what their next motion is. - type ExternalOrigin = EnsureRootOrHalfGeneralCouncil; // TODO: When root is removed, change to `EnsureHalfSetheumJuryOrHalfGeneralCouncil`. + type ExternalOrigin = EnsureRootOrHalfGeneralCouncil; /// A majority can have the next scheduled referendum be a straight majority-carries vote. - type ExternalMajorityOrigin = EnsureRootOrHalfGeneralCouncil; // TODO: When root is removed, change to `EnsureHalfSetheumJuryOrHalfGeneralCouncil`. + type ExternalMajorityOrigin = EnsureRootOrHalfGeneralCouncil; /// A unanimous council can have the next scheduled referendum be a straight default-carries /// (NTB) vote. - type ExternalDefaultOrigin = EnsureRootOrAllGeneralCouncil; // TODO: When root is removed, change to `EnsureAllSetheumJuryOrAllGeneralCouncil`. + type ExternalDefaultOrigin = EnsureRootOrAllGeneralCouncil; /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote /// be tabled immediately and with a shorter voting/enactment period. - type FastTrackOrigin = EnsureRootOrTwoThirdsTechnicalCommittee; // TODO: When root is removed, change to `EnsureTwoThirdsSetheumJuryOrTwoThirdsTechnicalCommittee`. - type InstantOrigin = EnsureRootOrAllTechnicalCommittee; // TODO: When root is removed, change to `EnsureAllSetheumJuryOrAllTechnicalCommittee`. + type FastTrackOrigin = EnsureRootOrTwoThirdsTechnicalCommittee; + type InstantOrigin = EnsureRootOrAllTechnicalCommittee; type InstantAllowed = InstantAllowed; type FastTrackVotingPeriod = FastTrackVotingPeriod; // To cancel a proposal which has been passed, 2/3 of the council must agree to it. - type CancellationOrigin = EnsureRootOrTwoThirdsGeneralCouncil; // TODO: When root is removed, change to `EnsureHalfSetheumJuryOrTwoThirdsGeneralCouncil`. - type BlacklistOrigin = EnsureRootOrHalfSetheumJury; + type CancellationOrigin = EnsureRootOrTwoThirdsGeneralCouncil; + type BlacklistOrigin = EnsureRoot; // To cancel a proposal before it has been passed, the technical committee must be unanimous or - // Root must agree or half of SetheumJury must agree. - type CancelProposalOrigin = EnsureRootOrAllTechnicalCommittee; // TODO: When root is removed, change to `EnsureAllSetheumJuryOrAllTechnicalCommittee`. + // Root must agree. + type CancelProposalOrigin = EnsureRootOrAllTechnicalCommittee; // Any single technical committee member may veto a coming council proposal, however they can // only do it once and it lasts only for the cooloff period. - type VetoOrigin = pallet_collective::EnsureMember || EnsureMember; + type VetoOrigin = pallet_collective::EnsureMember; type CooloffPeriod = CooloffPeriod; type PreimageByteDeposit = PreimageByteDeposit; type OperationalPreimageOrigin = pallet_collective::EnsureMember; @@ -1021,7 +751,8 @@ impl setheum_democracy::Config for Runtime { type Scheduler = Scheduler; type PalletsOrigin = OriginCaller; type MaxVotes = MaxVotes; - type WeightInfo = setheum_democracy::weights::SubstrateWeight; + //TODO: might need to weight for Setheum + type WeightInfo = pallet_democracy::weights::SubstrateWeight; type MaxProposals = MaxProposals; } @@ -1071,13 +802,16 @@ impl DataFeeder for AggregatedDataProvider { } } +parameter_types! { + pub const GetNativeCurrencyId: CurrencyId = DRAM; + pub const SetterCurrencyId: CurrencyId = SETR; + pub const GetSetUSDCurrencyId: CurrencyId = SETUSD; +} + parameter_type_with_key! { pub ExistentialDeposits: |_currency_id: CurrencyId| -> Balance { match currency_id { CurrencyId::Token(symbol) => match symbol { - TokenSymbol::DNAR => Balance::max_value(), // unsupported - TokenSymbol::DRAM => Balance::max_value(*currency_id), // unsupported - TokenSymbol::SETR => cent(*currency_id), TokenSymbol::SETUSD => cent(*currency_id), TokenSymbol::SETEUR => cent(*currency_id), @@ -1085,16 +819,19 @@ parameter_type_with_key! { TokenSymbol::SETCHF => cent(*currency_id), TokenSymbol::SETSAR => cent(*currency_id) + TokenSymbol::DNAR | + TokenSymbol::DRAM | TokenSymbol::RENBTC | }, - CurrencyId::DexShare(_, _) => { - let dec = as CurrencyIdMapping>::decimals(*currency_id); - if let Some(dec) = dec { - // TODO: verify if this makes sense - 10u128.saturating_pow(dec as u32) + CurrencyId::DexShare(dex_share_0, _) => { + let currency_id_0: CurrencyId = (*dex_share_0).into(); + + // initial dex share amount is calculated based on currency_id_0, + // use the ED of currency_id_0 as the ED of lp token. + if currency_id_0 == GetNativeCurrencyId::get() { + NativeTokenExistentialDeposit::get() } else { - // TODO: update this before we enable ERC20 in DEX - Balance::max_value() // unsupported + Self::get(¤cy_id_0) } }, CurrencyId::Erc20(_) => Balance::max_value(), // not handled by orml-tokens @@ -1128,44 +865,14 @@ impl orml_tokens::Config for Runtime { parameter_types! { pub FiatUsdFixedPrice: Price = Price::saturating_from_rational(1, 1); - - pub const GetSetterPegOneCurrencyId: CurrencyId = GBP; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegTwoCurrencyId: CurrencyId = EUR; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegThreeCurrencyId: CurrencyId = KWD; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegFourCurrencyId: CurrencyId = JOD; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegFiveCurrencyId: CurrencyId = BHD; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegSixCurrencyId: CurrencyId = KYD; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegSevenCurrencyId: CurrencyId = OMR; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegEightCurrencyId: CurrencyId = CHF; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegNineCurrencyId: CurrencyId = GIP; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegTenCurrencyId: CurrencyId = USD; // Fiat pegs of the Setter (SETR). - - pub StableCurrencyIds: Vec = vec![SETR, SETUSD, SETEUR, SETGBP, SETCHF, SETSAR]; - pub FiatCurrencyIds: Vec = vec![USD, EUR, GBP, CHF, SAR, KWD, JOD, BHD, KYD, OMR, GIP]; } impl serp_prices::Config for Runtime { type Event = Event; type Source = AggregatedDataProvider; - type SetterCurrencyId = SetterCurrencyId; type GetSetUSDCurrencyId = GetSetUSDCurrencyId; - type GetFiatCHFCurrencyId = GetFiatCHFCurrencyId; - type GetFiatEURCurrencyId = GetFiatEURCurrencyId; - type GetFiatGBPCurrencyId = GetFiatGBPCurrencyId; - type GetFiatSARCurrencyId = GetFiatSARCurrencyId; - type GetFiatUSDCurrencyId = GetFiatUSDCurrencyId; type FiatUsdFixedPrice = FiatUsdFixedPrice; - type GetSetterPegOneCurrencyId = GetSetterPegOneCurrencyId; - type GetSetterPegTwoCurrencyId = GetSetterPegTwoCurrencyId; - type GetSetterPegThreeCurrencyId = GetSetterPegThreeCurrencyId; - type GetSetterPegFourCurrencyId = GetSetterPegFourCurrencyId; - type GetSetterPegFiveCurrencyId = GetSetterPegFiveCurrencyId; - type GetSetterPegSixCurrencyId = GetSetterPegSixCurrencyId; - type GetSetterPegSevenCurrencyId = GetSetterPegSevenCurrencyId; - type GetSetterPegEightCurrencyId = GetSetterPegEightCurrencyId; - type GetSetterPegNineCurrencyId = GetSetterPegNineCurrencyId; - type GetSetterPegTenCurrencyId = GetSetterPegTenCurrencyId; - type LockOrigin = EnsureRootOrTwoThirdsGeneralCouncil; + type LockOrigin = EnsureRootOrTwoThirdsFinancialCouncil; type DEX = Dex; type Currency = Currencies; type CurrencyIdMapping = EvmCurrencyIdMapping; @@ -1177,6 +884,7 @@ impl setheum_currencies::Config for Runtime { type MultiCurrency = Tokens; type NativeCurrency = BasicCurrencyAdapter; type GetNativeCurrencyId = GetNativeCurrencyId; + type SerpTreasury = SerpTreasury; type WeightInfo = weights::setheum_currencies::WeightInfo; type AddressMapping = EvmAddressMapping; type EVMBridge = EVMBridge; @@ -1331,7 +1039,6 @@ impl settmint_engine::Config for Runtime { type DefaultStandardExchangeRate = DefaultStandardExchangeRate; type MinimumStandardValue = MinimumStandardValue; type ReserveCurrencyId = GetReserveCurrencyId; - type PriceSource = SerpPrices; } parameter_types! { @@ -1351,26 +1058,24 @@ parameter_types! { pub EnabledTradingPairs: Vec = vec![ TradingPair::new(SETR, DNAR), TradingPair::new(SETR, DRAM), - TradingPair::new(SETR, SETUSD), TradingPair::new(SETR, SETEUR), TradingPair::new(SETR, SETGBP), TradingPair::new(SETR, SETCHF), TradingPair::new(SETR, SETSAR), - TradingPair::new(SETR, RENBTC), ]; } -impl dex::Config for Runtime { +impl setheum_dex::Config for Runtime { type Event = Event; type Currency = Currencies; type GetExchangeFee = GetExchangeFee; type TradingPathLimit = TradingPathLimit; type PalletId = DexPalletId; type CurrencyIdMapping = EvmCurrencyIdMapping; - type WeightInfo = weights::dex::WeightInfo; - type ListingOrigin = EnsureRootOrHalfExchangeCouncil; // TODO: When root is removed, change to `EnsureHalfSetheumJuryOrHalfExchangeCouncil`. + type WeightInfo = weights::setheum_dex::WeightInfo; + type ListingOrigin = EnsureRootOrHalfFinancialCouncil; } parameter_types! { @@ -1412,6 +1117,27 @@ parameter_type_with_key! { }; } +parameter_types! { + pub MaxSwapSlippageCompareToOracle: Ratio = Ratio::saturating_from_rational(1, 2); + pub StableCurrencyIds: Vec = vec![SETR, SETUSD, SETEUR, SETGBP, SETCHF, SETSAR]; + pub DefaultFeeSwapPathList: Vec> = vec![ + vec![SETR, DNAR], + vec![SETUSD, SETR, DRAM] + vec![SETEUR, SETR, DRAM] + vec![SETGBP, SETR, DRAM] + vec![SETCHF, SETR, DRAM] + vec![SETSAR, SETR, DRAM] + ]; + pub DefaultSwapPathList: Vec> = vec![ + vec![SETR, DNAR], + vec![SETUSD, SETR, DNAR] + vec![SETEUR, SETR, DNAR] + vec![SETGBP, SETR, DNAR] + vec![SETCHF, SETR, DNAR] + vec![SETSAR, SETR, DNAR] + ]; +} + parameter_types! { pub MaxSwapSlippageCompareToOracle: Ratio = Ratio::saturating_from_rational(1, 2); pub DefaultFeeSwapPathList: Vec> = vec![vec![SETR, DNAR], vec![SETUSD, SETR, DNAR]]; @@ -1425,33 +1151,25 @@ impl serp_treasury::Config for Runtime { type GetNativeCurrencyId = GetNativeCurrencyId; type SetterCurrencyId = SetterCurrencyId; type GetSetUSDCurrencyId = GetSetUSDCurrencyId; - type DirhamCurrencyId = DirhamCurrencyId; + type DirhamCurrencyId = GetNativeCurrencyId; type CashDropPeriod = CashDropPeriod; type SettPayTreasuryAccountId = OneAccountId; type CashDropVaultAccountId = TwoAccountId; type CharityFundAccountId = CharityFundAccount; - type DefaultFeeSwapPathList = DefaultFeeSwapPathList; + type DefaultSwapPathList = DefaultSwapPathList; type Dex = Dex; type MaxSwapSlippageCompareToOracle = MaxSwapSlippageCompareToOracle; type TradingPathLimit = TradingPathLimit; type PriceSource = SerpPrices; type MinimumClaimableTransferAmounts = MinimumClaimableTransferAmounts; - type UpdateOrigin = EnsureSignedBy; + type UpdateOrigin = EnsureRootOrHalfFinancialCouncil; type PalletId = SerpTreasuryPalletId; type WeightInfo = weights::serp_treasury::WeightInfo; } -parameter_types! { - // All currency types except for native currency, Sort by fee charge order - pub AllNonNativeCurrencyIds: Vec = vec![ - DRAM, SETR, SETUSD, SETEUR, SETGBP, SETCHF, SETSAR, RENBTC - ]; -} - impl setheum_transaction_payment::Config for Runtime { - type AllNonNativeCurrencyIds = AllNonNativeCurrencyIds; type NativeCurrencyId = GetNativeCurrencyId; - type SetterCurrencyId = SetterCurrencyId; + type DefaultFeeSwapPathList = DefaultFeeSwapPathList; type Currency = Balances; type MultiCurrency = Currencies; type OnTransactionPayment = Treasury; @@ -1459,7 +1177,9 @@ impl setheum_transaction_payment::Config for Runtime { type WeightToFee = WeightToFee; type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; type Dex = Dex; - type MaxSlippageSwapWithDex = MaxSlippageSwapWithDex; + type MaxSwapSlippageCompareToOracle = MaxSwapSlippageCompareToOracle; + type TradingPathLimit = TradingPathLimit; + type PriceSource = SerpPrices; type WeightInfo = weights::setheum_transaction_payment::WeightInfo; } @@ -1498,15 +1218,19 @@ impl setheum_airdrop::Config for Runtime { } parameter_types! { - pub CreateClassDeposit: Balance = 20 * millicent(DNAR); - pub CreateTokenDeposit: Balance = 2 * millicent(DNAR); + pub CreateClassDeposit: Balance = 20 * millicent(DRAM); + pub CreateTokenDeposit: Balance = 2 * millicent(DRAM); + pub MaxAttributesBytes: u32 = 2048; } impl setheum_nft::Config for Runtime { type Event = Event; + type Currency = Balances; type CreateClassDeposit = CreateClassDeposit; type CreateTokenDeposit = CreateTokenDeposit; + type DataDepositPerByte = DataDepositPerByte; type PalletId = NftPalletId; + type MaxAttributesBytes = MaxAttributesBytes; type WeightInfo = weights::setheum_nft::WeightInfo; } @@ -1535,11 +1259,53 @@ parameter_types! { pub const MaxPending: u16 = 32; } +impl InstanceFilter for ProxyType { + fn filter(&self, c: &Call) -> bool { + match self { + // Always allowed Call::Utility no matter type. + // Only transactions allowed by Proxy.filter can be executed, + // otherwise `BadOrigin` will be returned in Call::Utility. + _ if matches!(c, Call::Utility(..)) => true, + ProxyType::Any => true, + ProxyType::CancelProxy => matches!(c, Call::Proxy(pallet_proxy::Call::reject_announcement(..))), + ProxyType::Governance => { + matches!( + c, + Call::Authority(..) + | Call::Democracy(..) + | Call::ShuraCouncil(..) + | Call::GeneralCouncil(..) + | Call::FinancialCouncil(..) + | Call::TechnicalCommittee(..) + | Call::Treasury(..) + | Call::Bounties(..) + | Call::Tips(..) + ) + } + ProxyType::Swap => { + matches!( + c, + Call::Dex(setheum_dex::Call::swap_with_exact_supply(..)) + | Call::Dex(setheum_dex::Call::swap_with_exact_target(..)) + ) + } + } + } + fn is_superset(&self, o: &Self) -> bool { + match (self, o) { + (x, y) if x == y => true, + (ProxyType::Any, _) => true, + (_, ProxyType::Any) => false, + _ => false, + } + } +} + impl pallet_proxy::Config for Runtime { type Event = Event; type Call = Call; type Currency = Balances; - type ProxyType = (); + type ProxyType = ProxyType; type ProxyDepositBase = ProxyDepositBase; type ProxyDepositFactor = ProxyDepositFactor; type MaxProxies = MaxProxies; @@ -1645,7 +1411,7 @@ impl setheum_evm::Config for Runtime { type DeveloperDeposit = DeveloperDeposit; type DeploymentFee = DeploymentFee; type TreasuryAccount = TreasuryAccount; - type FreeDeploymentOrigin = EnsureRootOrHalfGeneralCouncil; // TODO: When root is removed, change to `EnsureHalfSetheumJuryOrHalfGeneralCouncil`. + type FreeDeploymentOrigin = EnsureRootOrHalfGeneralCouncil; type WeightInfo = weights::setheum_evm::WeightInfo; #[cfg(feature = "with-ethereum-compatibility")] @@ -1730,74 +1496,72 @@ construct_runtime!( NFT: setheum_nft::{Pallet, Call, Event} = 7, Vesting: orml_vesting::{Pallet, Storage, Call, Event, Config} = 8, TransactionPayment: setheum_transaction_payment::{Pallet, Call, Storage} = 9, - AirDrop: setheum_airdrop::{Pallet, Call, Storage, Event, Config} = 142, + AirDrop: setheum_airdrop::{Pallet, Call, Storage, Event, Config} = 10, // Treasury - Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event} = 10, - Bounties: pallet_bounties::{Pallet, Call, Storage, Event} = 11, - Tips: pallet_tips::{Pallet, Call, Storage, Event} = 12, + Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event} = 11, + Bounties: pallet_bounties::{Pallet, Call, Storage, Event} = 12, + Tips: pallet_tips::{Pallet, Call, Storage, Event} = 13, // Utility - Utility: pallet_utility::{Pallet, Call, Event} = 13, - Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 14, - Recovery: pallet_recovery::{Pallet, Call, Storage, Event} = 15, - Proxy: pallet_proxy::{Pallet, Call, Storage, Event} = 16 , - Indices: pallet_indices::{Pallet, Call, Storage, Config, Event} = 17, + Utility: pallet_utility::{Pallet, Call, Event} = 14, + Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 15, + Recovery: pallet_recovery::{Pallet, Call, Storage, Event} = 16, + Proxy: pallet_proxy::{Pallet, Call, Storage, Event} = 17 , + Indices: pallet_indices::{Pallet, Call, Storage, Config, Event} = 18, // Consensus & Staking - Authorship: pallet_authorship::{Pallet, Call, Storage, Inherent} = 18, - Babe: pallet_babe::{Pallet, Call, Storage, Config, Inherent, ValidateUnsigned} = 19, - Grandpa: pallet_grandpa::{Pallet, Call, Storage, Config, Event, ValidateUnsigned} = 20, - Staking: serp_staking::{Pallet, Call, Config, Storage, Event} = 21, - Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 22, - Historical: pallet_session_historical::{Module} = 23, + Authorship: pallet_authorship::{Pallet, Call, Storage, Inherent} = 19, + Babe: pallet_babe::{Pallet, Call, Storage, Config, Inherent, ValidateUnsigned} = 20, + Grandpa: pallet_grandpa::{Pallet, Call, Storage, Config, Event, ValidateUnsigned} = 21, + Staking: pallet_staking::{Module, Call, Config, Storage, Event}, = 22 + Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 23, + Historical: pallet_session_historical::{Module} = 24, // Governance - GeneralCouncil: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 24, - GeneralCouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 25, - SetheumJury: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 26, - SetheumJuryMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 27, - FinancialCouncil: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 28, - FinancialCouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 29, - ExchangeCouncil: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 30, - ExchangeCouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 31, - TechnicalCommittee: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 32, - TechnicalCommitteeMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 33, - Authority: orml_authority::{Pallet, Call, Event, Origin} = 34, + ShuraCouncil: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 25, + ShuraCouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 26, + GeneralCouncil: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 27, + GeneralCouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 28, + FinancialCouncil: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 29, + FinancialCouncilMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 30, + TechnicalCommittee: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 31, + TechnicalCommitteeMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 32, + Authority: orml_authority::{Pallet, Call, Event, Origin} = 33, + Democracy: pallet_democracy::{Pallet, Call, Storage, Config, Event} = 34, // Oracle // // NOTE: OperatorMembership must be placed after Oracle or else will have race condition on initialization SetheumOracle: orml_oracle::::{Pallet, Storage, Call, Config, Event} = 35, - // OperatorMembership must be placed after Oracle or else will have race condition on initialization - OperatorMembershipSetheum: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 36, + OperatorMembershipSetheum: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 36, // ORML Core - OrmlNFT: orml_nft::{Pallet, Storage, Config} = 39, + OrmlNFT: orml_nft::{Pallet, Storage, Config} = 37, // SERP Core - SerpPrices: serp_prices::{Pallet, Storage, Call, Event} = 41, - SerpTreasury: serp_treasury::{Pallet, Storage, Call, Config, Event} = 43, + SerpPrices: serp_prices::{Pallet, Storage, Call, Event} = 38, + SerpTreasury: serp_treasury::{Pallet, Storage, Call, Config, Event} = 39, // Dex - Dex: dex::{Pallet, Storage, Call, Event, Config} = 44, + Dex: setheum_dex::{Pallet, Storage, Call, Event, Config} = 40, // Settmint - SettmintEngine: settmint_engine::{Pallet, Storage, Call, Event, Config, ValidateUnsigned} = 46, - SettmintGateway: settmint_gateway::{Pallet, Storage, Call, Event} = 47, - SettmintManager: settmint_manager::{Pallet, Storage, Call, Event} = 48, + SettmintEngine: settmint_engine::{Pallet, Storage, Call, Event, Config, ValidateUnsigned} = 41, + SettmintGateway: settmint_gateway::{Pallet, Storage, Call, Event} = 42, + SettmintManager: settmint_manager::{Pallet, Storage, Call, Event} = 43, // Smart contracts // Setheum EVM (SEVM) - EVM: setheum_evm::{Pallet, Config, Call, Storage, Event} = 49, - EVMBridge: setheum_evm_bridge::{Pallet} = 50, - EvmAccounts: setheum_evm_accounts::{Pallet, Call, Storage, Event} = 51, - EvmManager: setheum_evm_manager::{Pallet, Storage} = 52, + EVM: setheum_evm::{Pallet, Config, Call, Storage, Event} = 44, + EVMBridge: setheum_evm_bridge::{Pallet} = 45, + EvmAccounts: setheum_evm_accounts::{Pallet, Call, Storage, Event} = 46, + EvmManager: setheum_evm_manager::{Pallet, Storage} = 47, // Bridges - // RenVmBridge: setheum_renvm_bridge::{Pallet, Call, Config, Storage, Event, ValidateUnsigned} = 53, - // ChainBridge: chainbridge::{Pallet, Call, Storage, Event} = 54, - // SetheumChainBridge: setheum_chainbridge::{Pallet, Call, Storage, Event} = 55, + RenVmBridge: setheum_renvm_bridge::{Pallet, Call, Config, Storage, Event, ValidateUnsigned} = 48, + ChainBridge: chainbridge::{Pallet, Call, Storage, Event} = 49, + SetheumChainBridge: setheum_chainbridge::{Pallet, Call, Storage, Event} = 50, // Dev Sudo: pallet_sudo::{Pallet, Call, Config, Storage, Event} = 255, @@ -2130,7 +1894,7 @@ impl_runtime_apis! { // TODO: Update! orml_add_benchmark!(params, batches, orml_authority, benchmarking::authority); orml_add_benchmark!(params, batches, orml_currencies, benchmarking::currencies); - orml_add_benchmark!(params, batches, dex, benchmarking::dex); + orml_add_benchmark!(params, batches, setheum_dex, benchmarking::setheum_dex); orml_add_benchmark!(params, batches, setheum_evm_accounts, benchmarking::evm_accounts); orml_add_benchmark!(params, batches, setheum_evm, benchmarking::evm); orml_add_benchmark!(params, batches, orml_oracle, benchmarking::oracle); From e25ed627c4f66ef7c2c38ae56d39aebfd4cd0249 Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 07:15:28 +0800 Subject: [PATCH 06/22] Fix runtimes --- Cargo.lock | 651 +------------------------------------ Cargo.toml | 2 - runtime/newrome/Cargo.toml | 3 - runtime/setheum/Cargo.toml | 3 - 4 files changed, 3 insertions(+), 656 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b28f524fc..8a853da1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1840,25 +1840,6 @@ dependencies = [ "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", ] -[[package]] -name = "frame-benchmarking" -version = "3.1.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "linregress", - "log", - "parity-scale-codec", - "paste", - "sp-api 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "frame-benchmarking" version = "3.1.0" @@ -1901,19 +1882,6 @@ dependencies = [ "structopt", ] -[[package]] -name = "frame-election-provider-support" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "parity-scale-codec", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-npos-elections 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "frame-executive" version = "3.0.0" @@ -1940,17 +1908,6 @@ dependencies = [ "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", ] -[[package]] -name = "frame-metadata" -version = "13.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "parity-scale-codec", - "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "frame-metadata" version = "13.0.0" @@ -2000,33 +1957,6 @@ dependencies = [ "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", ] -[[package]] -name = "frame-support" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "bitflags", - "frame-metadata 13.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "frame-support-procedural 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "impl-trait-for-tuples 0.2.1", - "log", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "once_cell", - "parity-scale-codec", - "paste", - "serde", - "smallvec 1.6.1", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-staking 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "frame-support" version = "3.0.0" @@ -2093,18 +2023,6 @@ dependencies = [ "syn", ] -[[package]] -name = "frame-support-procedural" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "Inflector", - "frame-support-procedural-tools 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "frame-support-procedural" version = "3.0.0" @@ -2141,18 +2059,6 @@ dependencies = [ "syn", ] -[[package]] -name = "frame-support-procedural-tools" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "frame-support-procedural-tools-derive 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "proc-macro-crate 1.0.0", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "frame-support-procedural-tools" version = "3.0.0" @@ -2187,16 +2093,6 @@ dependencies = [ "syn", ] -[[package]] -name = "frame-support-procedural-tools-derive" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "frame-support-procedural-tools-derive" version = "3.0.0" @@ -2234,23 +2130,6 @@ dependencies = [ "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", ] -[[package]] -name = "frame-system" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "impl-trait-for-tuples 0.2.1", - "log", - "parity-scale-codec", - "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-version 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "frame-system" version = "3.0.0" @@ -4126,17 +4005,6 @@ dependencies = [ "primitive-types", ] -[[package]] -name = "max-encoded-len" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "impl-trait-for-tuples 0.2.1", - "max-encoded-len-derive 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "parity-scale-codec", - "primitive-types", -] - [[package]] name = "max-encoded-len" version = "3.0.0" @@ -4170,17 +4038,6 @@ dependencies = [ "syn", ] -[[package]] -name = "max-encoded-len-derive" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "proc-macro-crate 1.0.0", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "max-encoded-len-derive" version = "3.0.0" @@ -4541,7 +4398,6 @@ dependencies = [ "runtime-common", "serde", "serp-prices", - "serp-staking", "serp-treasury", "setheum-airdrop", "setheum-chainbridge", @@ -5094,21 +4950,6 @@ dependencies = [ "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", ] -[[package]] -name = "pallet-democracy" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "frame-support 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "parity-scale-codec", - "serde", - "sp-io 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "pallet-elections-phragmen" version = "4.0.0" @@ -5120,7 +4961,7 @@ dependencies = [ "parity-scale-codec", "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-npos-elections 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-npos-elections", "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", ] @@ -7857,44 +7698,6 @@ dependencies = [ "substrate-fixed", ] -[[package]] -name = "serp-staking" -version = "0.9.0" -dependencies = [ - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-election-provider-support", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "hex", - "log", - "orml-currencies", - "orml-tokens", - "orml-traits", - "orml-utilities", - "pallet-authorship", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "pallet-session", - "pallet-staking-reward-curve", - "pallet-timestamp", - "parity-scale-codec", - "parking_lot 0.11.1", - "paste", - "rand_chacha 0.2.2", - "serde", - "setheum-primitives", - "setheum-support", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-staking 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "static_assertions", - "substrate-test-utils", -] - [[package]] name = "serp-treasury" version = "0.9.0" @@ -8006,33 +7809,6 @@ dependencies = [ "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", ] -[[package]] -name = "setheum-democracy" -version = "0.8.0" -dependencies = [ - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "hex-literal 0.3.3", - "orml-currencies", - "orml-tokens", - "orml-traits", - "orml-utilities", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "pallet-democracy", - "pallet-scheduler", - "parity-scale-codec", - "serde", - "setheum-primitives", - "setheum-support", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "substrate-test-utils", -] - [[package]] name = "setheum-dex" version = "0.8.0" @@ -8340,7 +8116,6 @@ dependencies = [ "runtime-common", "serde", "serp-prices", - "serp-staking", "serp-treasury", "setheum-airdrop", "setheum-chainbridge", @@ -8455,7 +8230,7 @@ dependencies = [ [[package]] name = "setheum-transaction-payment" -version = "0.9.0" +version = "0.8.0" dependencies = [ "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", @@ -8793,23 +8568,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "sp-api" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "hash-db", - "log", - "parity-scale-codec", - "sp-api-proc-macro 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-version 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "thiserror", -] - [[package]] name = "sp-api" version = "3.0.0" @@ -8839,18 +8597,6 @@ dependencies = [ "syn", ] -[[package]] -name = "sp-api-proc-macro" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "blake2-rfc", - "proc-macro-crate 1.0.0", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "sp-api-proc-macro" version = "3.0.0" @@ -8876,19 +8622,6 @@ dependencies = [ "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", ] -[[package]] -name = "sp-application-crypto" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "max-encoded-len 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "parity-scale-codec", - "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "sp-application-crypto" version = "3.0.0" @@ -8929,20 +8662,6 @@ dependencies = [ "static_assertions", ] -[[package]] -name = "sp-arithmetic" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "integer-sqrt", - "num-traits", - "parity-scale-codec", - "serde", - "sp-debug-derive 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "static_assertions", -] - [[package]] name = "sp-arithmetic" version = "3.0.0" @@ -9146,51 +8865,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "sp-core" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "base58", - "blake2-rfc", - "byteorder", - "dyn-clonable", - "ed25519-dalek", - "futures 0.3.16", - "hash-db", - "hash256-std-hasher", - "hex", - "impl-serde", - "lazy_static", - "libsecp256k1", - "log", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "merlin", - "num-traits", - "parity-scale-codec", - "parity-util-mem", - "parking_lot 0.11.1", - "primitive-types", - "rand 0.7.3", - "regex", - "schnorrkel", - "secrecy", - "serde", - "sha2 0.9.5", - "sp-debug-derive 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "substrate-bip39", - "thiserror", - "tiny-bip39", - "tiny-keccak", - "twox-hash", - "wasmi", - "zeroize", -] - [[package]] name = "sp-core" version = "3.0.0" @@ -9300,16 +8974,6 @@ dependencies = [ "syn", ] -[[package]] -name = "sp-debug-derive" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "sp-debug-derive" version = "3.0.0" @@ -9341,17 +9005,6 @@ dependencies = [ "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", ] -[[package]] -name = "sp-externalities" -version = "0.9.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "environmental", - "parity-scale-codec", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "sp-externalities" version = "0.9.0" @@ -9405,20 +9058,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "sp-inherents" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "async-trait", - "impl-trait-for-tuples 0.2.1", - "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "thiserror", -] - [[package]] name = "sp-inherents" version = "3.0.0" @@ -9472,31 +9111,6 @@ dependencies = [ "tracing-core", ] -[[package]] -name = "sp-io" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "futures 0.3.16", - "hash-db", - "libsecp256k1", - "log", - "parity-scale-codec", - "parking_lot 0.11.1", - "sp-core 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-maybe-compressed-blob 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-trie 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-wasm-interface 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "tracing", - "tracing-core", -] - [[package]] name = "sp-io" version = "3.0.0" @@ -9574,22 +9188,6 @@ dependencies = [ "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", ] -[[package]] -name = "sp-keystore" -version = "0.9.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "async-trait", - "derive_more", - "futures 0.3.16", - "merlin", - "parity-scale-codec", - "parking_lot 0.11.1", - "schnorrkel", - "sp-core 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "sp-keystore" version = "0.9.0" @@ -9641,15 +9239,6 @@ dependencies = [ "zstd", ] -[[package]] -name = "sp-maybe-compressed-blob" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "ruzstd", - "zstd", -] - [[package]] name = "sp-maybe-compressed-blob" version = "3.0.0" @@ -9668,19 +9257,6 @@ dependencies = [ "zstd", ] -[[package]] -name = "sp-npos-elections" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "parity-scale-codec", - "serde", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-npos-elections-compact 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "sp-npos-elections" version = "3.0.0" @@ -9690,21 +9266,10 @@ dependencies = [ "serde", "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-npos-elections-compact 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-npos-elections-compact", "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", ] -[[package]] -name = "sp-npos-elections-compact" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "proc-macro-crate 1.0.0", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "sp-npos-elections-compact" version = "3.0.0" @@ -9734,14 +9299,6 @@ dependencies = [ "backtrace", ] -[[package]] -name = "sp-panic-handler" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "backtrace", -] - [[package]] name = "sp-panic-handler" version = "3.0.0" @@ -9791,28 +9348,6 @@ dependencies = [ "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", ] -[[package]] -name = "sp-runtime" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "either", - "hash256-std-hasher", - "impl-trait-for-tuples 0.2.1", - "log", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "parity-scale-codec", - "parity-util-mem", - "paste", - "rand 0.7.3", - "serde", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "sp-runtime" version = "3.0.0" @@ -9874,23 +9409,6 @@ dependencies = [ "static_assertions", ] -[[package]] -name = "sp-runtime-interface" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "impl-trait-for-tuples 0.2.1", - "parity-scale-codec", - "primitive-types", - "sp-externalities 0.9.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-runtime-interface-proc-macro 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-wasm-interface 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "static_assertions", -] - [[package]] name = "sp-runtime-interface" version = "3.0.0" @@ -9937,18 +9455,6 @@ dependencies = [ "syn", ] -[[package]] -name = "sp-runtime-interface-proc-macro" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "Inflector", - "proc-macro-crate 1.0.0", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "sp-runtime-interface-proc-macro" version = "3.0.0" @@ -10005,16 +9511,6 @@ dependencies = [ "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", ] -[[package]] -name = "sp-staking" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "parity-scale-codec", - "sp-runtime 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "sp-staking" version = "3.0.0" @@ -10058,29 +9554,6 @@ dependencies = [ "trie-root", ] -[[package]] -name = "sp-state-machine" -version = "0.9.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "hash-db", - "log", - "num-traits", - "parity-scale-codec", - "parking_lot 0.11.1", - "rand 0.7.3", - "smallvec 1.6.1", - "sp-core 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-panic-handler 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-trie 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "thiserror", - "tracing", - "trie-db", - "trie-root", -] - [[package]] name = "sp-state-machine" version = "0.9.0" @@ -10132,11 +9605,6 @@ name = "sp-std" version = "3.0.0" source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -[[package]] -name = "sp-std" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" - [[package]] name = "sp-std" version = "3.0.0" @@ -10160,19 +9628,6 @@ dependencies = [ "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", ] -[[package]] -name = "sp-storage" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "impl-serde", - "parity-scale-codec", - "ref-cast", - "serde", - "sp-debug-derive 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "sp-storage" version = "3.0.0" @@ -10247,24 +9702,6 @@ dependencies = [ "tracing-subscriber", ] -[[package]] -name = "sp-tracing" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "erased-serde", - "log", - "parity-scale-codec", - "parking_lot 0.10.2", - "serde", - "serde_json", - "slog", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "tracing", - "tracing-core", - "tracing-subscriber", -] - [[package]] name = "sp-tracing" version = "3.0.0" @@ -10346,20 +9783,6 @@ dependencies = [ "trie-root", ] -[[package]] -name = "sp-trie" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "hash-db", - "memory-db", - "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "trie-db", - "trie-root", -] - [[package]] name = "sp-trie" version = "3.0.0" @@ -10413,19 +9836,6 @@ dependencies = [ "sp-version-proc-macro 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", ] -[[package]] -name = "sp-version" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "impl-serde", - "parity-scale-codec", - "serde", - "sp-runtime 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "sp-version-proc-macro 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "sp-version" version = "3.0.0" @@ -10464,18 +9874,6 @@ dependencies = [ "syn", ] -[[package]] -name = "sp-version-proc-macro" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "parity-scale-codec", - "proc-macro-crate 1.0.0", - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "sp-version-proc-macro" version = "3.0.0" @@ -10511,17 +9909,6 @@ dependencies = [ "wasmi", ] -[[package]] -name = "sp-wasm-interface" -version = "3.0.0" -source = "git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "impl-trait-for-tuples 0.2.1", - "parity-scale-codec", - "sp-std 3.0.0 (git+https://github.com/paritytech//substrate?branch=polkadot-v0.9.8)", - "wasmi", -] - [[package]] name = "sp-wasm-interface" version = "3.0.0" @@ -10716,26 +10103,6 @@ dependencies = [ "tokio 0.2.25", ] -[[package]] -name = "substrate-test-utils" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "futures 0.3.16", - "substrate-test-utils-derive", - "tokio 0.2.25", -] - -[[package]] -name = "substrate-test-utils-derive" -version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "proc-macro-crate 1.0.0", - "quote", - "syn", -] - [[package]] name = "substrate-wasm-builder" version = "4.0.0" @@ -10996,7 +10363,6 @@ dependencies = [ "pin-project-lite 0.1.12", "signal-hook-registry", "slab", - "tokio-macros", "winapi 0.3.9", ] @@ -11074,17 +10440,6 @@ dependencies = [ "log", ] -[[package]] -name = "tokio-macros" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e44da00bfc73a25f814cd8d7e57a68a5c31b74b3152a0a1d1f590c97ed06265a" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "tokio-named-pipes" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 0e0f33127..e6b5f21fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,12 +7,10 @@ members = [ "lib-serml/airdrop", "lib-serml/bridges/*", - "lib-serml/democracy", "lib-serml/dex/*", "lib-serml/evm/*", "lib-serml/example", "lib-serml/serp/serp-prices", - "lib-serml/serp/serp-staking", "lib-serml/serp/serp-treasury", "lib-serml/settmint/*", "lib-serml/support", diff --git a/runtime/newrome/Cargo.toml b/runtime/newrome/Cargo.toml index bc05773cc..4e4b4089d 100644 --- a/runtime/newrome/Cargo.toml +++ b/runtime/newrome/Cargo.toml @@ -87,7 +87,6 @@ setheum-evm-manager = { path = "../../lib-serml/evm/evm-manager", default-featur setheum-evm-rpc-runtime-api = { path = "../../lib-serml/evm/evm/rpc/runtime_api", default-features = false } # - serp serp-prices = { path = "../../lib-serml/serp/serp-prices", default-features = false } -serp-staking = { path = "../../lib-serml/serp/serp-staking", default-features = false } serp-treasury = { path = "../../lib-serml/serp/serp-treasury", default-features = false } # - settmint settmint-engine = { path = "../../lib-serml/settmint/settmint-engine", default-features = false } @@ -174,7 +173,6 @@ std = [ "setheum-evm-bridge/std", "setheum-evm-manager/std", "serp-prices/std", - "serp-staking/std", "serp-treasury/std", "settmint-engine/std", "settmint-gateway/std", @@ -234,7 +232,6 @@ try-runtime = [ "pallet-recovery/try-runtime", "pallet-scheduler/try-runtime", "pallet-session/try-runtime", - "serp-staking/try-runtime", "pallet-sudo/try-runtime", "pallet-timestamp/try-runtime", "pallet-tips/try-runtime", diff --git a/runtime/setheum/Cargo.toml b/runtime/setheum/Cargo.toml index 651dc8c75..ff375e652 100644 --- a/runtime/setheum/Cargo.toml +++ b/runtime/setheum/Cargo.toml @@ -84,7 +84,6 @@ setheum-evm-manager = { path = "../../lib-serml/evm/evm-manager", default-featur setheum-evm-rpc-runtime-api = { path = "../../lib-serml/evm/evm/rpc/runtime_api", default-features = false } # - serp serp-prices = { path = "../../lib-serml/serp/serp-prices", default-features = false } -serp-staking = { path = "../../lib-serml/serp/serp-staking", default-features = false } serp-treasury = { path = "../../lib-serml/serp/serp-treasury", default-features = false } # - settmint settmint-engine = { path = "../../lib-serml/settmint/settmint-engine", default-features = false } @@ -171,7 +170,6 @@ std = [ "setheum-evm-bridge/std", "setheum-evm-manager/std", "serp-prices/std", - "serp-staking/std", "serp-treasury/std", "settmint-engine/std", "settmint-gateway/std", @@ -232,7 +230,6 @@ try-runtime = [ "pallet-recovery/try-runtime", "pallet-scheduler/try-runtime", "pallet-session/try-runtime", - "serp-staking/try-runtime", "pallet-sudo/try-runtime", "pallet-timestamp/try-runtime", "pallet-tips/try-runtime", From 5f666dc0965700753efd80eca81320c7e6454dfc Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 09:37:44 +0800 Subject: [PATCH 07/22] update chainbridge --- lib-serml/bridges/chainbridge/src/lib.rs | 4 +- lib-serml/bridges/chainbridge/src/mock.rs | 18 +-- lib-serml/bridges/chainbridge/src/tests.rs | 118 +++++++++---------- lib-serml/bridges/chainbridge/src/weights.rs | 30 +++-- 4 files changed, 91 insertions(+), 79 deletions(-) diff --git a/lib-serml/bridges/chainbridge/src/lib.rs b/lib-serml/bridges/chainbridge/src/lib.rs index e39fc2ce6..b7ecc49b6 100644 --- a/lib-serml/bridges/chainbridge/src/lib.rs +++ b/lib-serml/bridges/chainbridge/src/lib.rs @@ -198,10 +198,10 @@ impl Pallet { if Self::is_origin_chain_resource(resource_id) { // transfer tokens to bridge account to lock - T::Currency::transfer(currency_id, &from, &bridge_account_id, amount)?; + T::Currency::transfer(currency_id, from, &bridge_account_id, amount)?; } else { // burn tokens - T::Currency::withdraw(currency_id, &from, amount)?; + T::Currency::withdraw(currency_id, from, amount)?; } chainbridge::Module::::transfer_fungible( diff --git a/lib-serml/bridges/chainbridge/src/mock.rs b/lib-serml/bridges/chainbridge/src/mock.rs index 53d883810..d72620155 100644 --- a/lib-serml/bridges/chainbridge/src/mock.rs +++ b/lib-serml/bridges/chainbridge/src/mock.rs @@ -1,6 +1,6 @@ -// This file is part of Setheum. +// This file is part of DRAMla. -// Copyright (C) 2019-2021 Setheum Labs. +// Copyright (C) 2020-2021 DRAMla Foundation. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! Mocks for the chainbridge module. +//! Mocks for the chainsafe module. #![cfg(test)] @@ -33,7 +33,7 @@ pub type AccountId = u128; pub const ALICE: AccountId = 1; -mod setheum_chainbridge { +mod ecosystem_chainsafe { pub use super::super::*; } @@ -92,8 +92,8 @@ ord_parameter_types! { parameter_types! { pub const LocalChainId: chainbridge::ChainId = 2; pub const ProposalLifetime: BlockNumber = 10; - pub DNARResourceId: chainbridge::ResourceId = chainbridge::derive_resource_id(LocalChainId::get(), b"set"); - pub const DNAR: CurrencyId = CurrencyId::Token(TokenSymbol::DNAR); + pub DRAMResourceId: chainbridge::ResourceId = chainbridge::derive_resource_id(LocalChainId::get(), b"DRAM"); + pub const DRAM: CurrencyId = CurrencyId::Token(TokenSymbol::DRAM); pub WETHResourceId: chainbridge::ResourceId = chainbridge::derive_resource_id(0, b"weth"); pub WETH: CurrencyId = CurrencyId::ChainSafe(WETHResourceId::get()); } @@ -113,7 +113,7 @@ ord_parameter_types! { impl Config for Runtime { type Event = Event; type Currency = Tokens; - type NativeCurrencyId = DNAR; + type NativeCurrencyId = DRAM; type RegistorOrigin = EnsureSignedBy; type BridgeOrigin = chainbridge::EnsureBridge; type WeightInfo = (); @@ -131,7 +131,7 @@ construct_runtime!( System: frame_system::{Pallet, Call, Storage, Config, Event}, Tokens: orml_tokens::{Pallet, Storage, Event, Config}, ChainBridge: chainbridge::{Pallet, Call, Storage, Event}, - SetheumChainBridge: setheum_chainbridge::{Pallet, Call, Storage, Event}, + ChainSafeTransfer: ecosystem_chainsafe::{Pallet, Call, Storage, Event}, } ); @@ -142,7 +142,7 @@ pub struct ExtBuilder { impl Default for ExtBuilder { fn default() -> Self { Self { - balances: vec![(ALICE, DNAR::get(), 1_000u128)], + balances: vec![(ALICE, DRAM::get(), 1_000u128)], } } } diff --git a/lib-serml/bridges/chainbridge/src/tests.rs b/lib-serml/bridges/chainbridge/src/tests.rs index 8b4a4f36d..6bfda7765 100644 --- a/lib-serml/bridges/chainbridge/src/tests.rs +++ b/lib-serml/bridges/chainbridge/src/tests.rs @@ -30,49 +30,49 @@ fn register_resource_id_work() { ExtBuilder::default().build().execute_with(|| { System::set_block_number(1); - assert_eq!(SetheumChainBridge::resource_ids(DNAR::get()), None); - assert_eq!(SetheumChainBridge::currency_ids(DNARResourceId::get()), None); + assert_eq!(ChainSafeTransfer::resource_ids(DRAM::get()), None); + assert_eq!(ChainSafeTransfer::currency_ids(DRAMResourceId::get()), None); assert_noop!( - SetheumChainBridge::register_resource_id(Origin::signed(ALICE), DNARResourceId::get(), DNAR::get()), + ChainSafeTransfer::register_resource_id(Origin::signed(ALICE), DRAMResourceId::get(), DRAM::get()), BadOrigin, ); assert_noop!( - SetheumChainBridge::register_resource_id( + ChainSafeTransfer::register_resource_id( Origin::signed(RegistorOrigin::get()), - DNARResourceId::get(), + DRAMResourceId::get(), WETH::get() ), Error::::ResourceIdCurrencyIdNotMatch, ); assert_noop!( - SetheumChainBridge::register_resource_id( + ChainSafeTransfer::register_resource_id( Origin::signed(RegistorOrigin::get()), WETHResourceId::get(), - DNAR::get() + DRAM::get() ), Error::::ResourceIdCurrencyIdNotMatch, ); - assert_ok!(SetheumChainBridge::register_resource_id( + assert_ok!(ChainSafeTransfer::register_resource_id( Origin::signed(RegistorOrigin::get()), - DNARResourceId::get(), - DNAR::get() + DRAMResourceId::get(), + DRAM::get() )); let register_event = - Event::SetheumChainBridge(crate::Event::RegisterResourceId(DNARResourceId::get(), DNAR::get())); + Event::ChainSafeTransfer(crate::Event::RegisterResourceId(DRAMResourceId::get(), DRAM::get())); assert!(System::events().iter().any(|record| record.event == register_event)); - assert_eq!(SetheumChainBridge::resource_ids(DNAR::get()), Some(DNARResourceId::get())); - assert_eq!(SetheumChainBridge::currency_ids(DNARResourceId::get()), Some(DNAR::get())); + assert_eq!(ChainSafeTransfer::resource_ids(DRAM::get()), Some(DRAMResourceId::get())); + assert_eq!(ChainSafeTransfer::currency_ids(DRAMResourceId::get()), Some(DRAM::get())); assert_noop!( - SetheumChainBridge::register_resource_id( + ChainSafeTransfer::register_resource_id( Origin::signed(RegistorOrigin::get()), - DNARResourceId::get(), - DNAR::get() + DRAMResourceId::get(), + DRAM::get() ), Error::::ResourceIdAlreadyRegistered, ); @@ -84,25 +84,25 @@ fn remove_resource_id_work() { ExtBuilder::default().build().execute_with(|| { System::set_block_number(1); - assert_ok!(SetheumChainBridge::register_resource_id( + assert_ok!(ChainSafeTransfer::register_resource_id( Origin::signed(RegistorOrigin::get()), - DNARResourceId::get(), - DNAR::get() + DRAMResourceId::get(), + DRAM::get() )); - assert_eq!(SetheumChainBridge::resource_ids(DNAR::get()), Some(DNARResourceId::get())); - assert_eq!(SetheumChainBridge::currency_ids(DNARResourceId::get()), Some(DNAR::get())); + assert_eq!(ChainSafeTransfer::resource_ids(DRAM::get()), Some(DRAMResourceId::get())); + assert_eq!(ChainSafeTransfer::currency_ids(DRAMResourceId::get()), Some(DRAM::get())); assert_noop!( - SetheumChainBridge::remove_resource_id(Origin::signed(ALICE), DNARResourceId::get()), + ChainSafeTransfer::remove_resource_id(Origin::signed(ALICE), DRAMResourceId::get()), BadOrigin, ); - assert_ok!(SetheumChainBridge::remove_resource_id( + assert_ok!(ChainSafeTransfer::remove_resource_id( Origin::signed(RegistorOrigin::get()), - DNARResourceId::get() + DRAMResourceId::get() )); let unregister_event = - Event::SetheumChainBridge(crate::Event::UnregisterResourceId(DNARResourceId::get(), DNAR::get())); + Event::ChainSafeTransfer(crate::Event::UnregisterResourceId(DRAMResourceId::get(), DRAM::get())); assert!(System::events().iter().any(|record| record.event == unregister_event)); }); } @@ -110,9 +110,9 @@ fn remove_resource_id_work() { #[test] fn is_origin_chain_resource_work() { ExtBuilder::default().build().execute_with(|| { - assert_eq!(SetheumChainBridge::is_origin_chain_resource(DNARResourceId::get()), true); + assert_eq!(ChainSafeTransfer::is_origin_chain_resource(DRAMResourceId::get()), true); assert_eq!( - SetheumChainBridge::is_origin_chain_resource(WETHResourceId::get()), + ChainSafeTransfer::is_origin_chain_resource(WETHResourceId::get()), false ); }); @@ -124,7 +124,7 @@ fn do_transfer_to_bridge_work() { let dest_chain_id: chainbridge::ChainId = 0; assert_noop!( - SetheumChainBridge::do_transfer_to_bridge(&ALICE, DNAR::get(), dest_chain_id, vec![1], 10), + ChainSafeTransfer::do_transfer_to_bridge(&ALICE, DRAM::get(), dest_chain_id, vec![1], 10), Error::::InvalidDestChainId, ); @@ -133,31 +133,31 @@ fn do_transfer_to_bridge_work() { dest_chain_id )); assert_noop!( - SetheumChainBridge::do_transfer_to_bridge(&ALICE, DNAR::get(), dest_chain_id, vec![1], 10), + ChainSafeTransfer::do_transfer_to_bridge(&ALICE, DRAM::get(), dest_chain_id, vec![1], 10), Error::::ResourceIdNotRegistered, ); - assert_ok!(SetheumChainBridge::register_resource_id( + assert_ok!(ChainSafeTransfer::register_resource_id( Origin::signed(RegistorOrigin::get()), - DNARResourceId::get(), - DNAR::get() + DRAMResourceId::get(), + DRAM::get() )); - assert_eq!(Tokens::total_issuance(DNAR::get()), 1000); - assert_eq!(Tokens::free_balance(DNAR::get(), &ALICE), 1000); - assert_eq!(Tokens::free_balance(DNAR::get(), &ChainBridge::account_id()), 0); + assert_eq!(Tokens::total_issuance(DRAM::get()), 1000); + assert_eq!(Tokens::free_balance(DRAM::get(), &ALICE), 1000); + assert_eq!(Tokens::free_balance(DRAM::get(), &ChainBridge::account_id()), 0); - assert_ok!(SetheumChainBridge::do_transfer_to_bridge( + assert_ok!(ChainSafeTransfer::do_transfer_to_bridge( &ALICE, - DNAR::get(), + DRAM::get(), dest_chain_id, vec![1], 10 )); - assert_eq!(Tokens::total_issuance(DNAR::get()), 1000); - assert_eq!(Tokens::free_balance(DNAR::get(), &ALICE), 990); - assert_eq!(Tokens::free_balance(DNAR::get(), &ChainBridge::account_id()), 10); + assert_eq!(Tokens::total_issuance(DRAM::get()), 1000); + assert_eq!(Tokens::free_balance(DRAM::get(), &ALICE), 990); + assert_eq!(Tokens::free_balance(DRAM::get(), &ChainBridge::account_id()), 10); - assert_ok!(SetheumChainBridge::register_resource_id( + assert_ok!(ChainSafeTransfer::register_resource_id( Origin::signed(RegistorOrigin::get()), WETHResourceId::get(), WETH::get() @@ -167,7 +167,7 @@ fn do_transfer_to_bridge_work() { assert_eq!(Tokens::free_balance(WETH::get(), &ALICE), 1000); assert_eq!(Tokens::free_balance(WETH::get(), &ChainBridge::account_id()), 0); - assert_ok!(SetheumChainBridge::do_transfer_to_bridge( + assert_ok!(ChainSafeTransfer::do_transfer_to_bridge( &ALICE, WETH::get(), dest_chain_id, @@ -184,41 +184,41 @@ fn do_transfer_to_bridge_work() { fn transfer_from_bridge_work() { ExtBuilder::default().build().execute_with(|| { assert_noop!( - SetheumChainBridge::transfer_from_bridge(Origin::signed(ALICE), ALICE, 500, DNARResourceId::get()), + ChainSafeTransfer::transfer_from_bridge(Origin::signed(ALICE), ALICE, 500, DRAMResourceId::get()), BadOrigin, ); assert_noop!( - SetheumChainBridge::transfer_from_bridge( + ChainSafeTransfer::transfer_from_bridge( Origin::signed(ChainBridge::account_id()), ALICE, 500, - DNARResourceId::get() + DRAMResourceId::get() ), Error::::ResourceIdNotRegistered, ); - assert_ok!(SetheumChainBridge::register_resource_id( + assert_ok!(ChainSafeTransfer::register_resource_id( Origin::signed(RegistorOrigin::get()), - DNARResourceId::get(), - DNAR::get() + DRAMResourceId::get(), + DRAM::get() )); - assert_ok!(Tokens::deposit(DNAR::get(), &ChainBridge::account_id(), 1000)); - assert_eq!(Tokens::total_issuance(DNAR::get()), 2000); - assert_eq!(Tokens::free_balance(DNAR::get(), &ALICE), 1000); - assert_eq!(Tokens::free_balance(DNAR::get(), &ChainBridge::account_id()), 1000); + assert_ok!(Tokens::deposit(DRAM::get(), &ChainBridge::account_id(), 1000)); + assert_eq!(Tokens::total_issuance(DRAM::get()), 2000); + assert_eq!(Tokens::free_balance(DRAM::get(), &ALICE), 1000); + assert_eq!(Tokens::free_balance(DRAM::get(), &ChainBridge::account_id()), 1000); - assert_ok!(SetheumChainBridge::transfer_from_bridge( + assert_ok!(ChainSafeTransfer::transfer_from_bridge( Origin::signed(ChainBridge::account_id()), ALICE, 500, - DNARResourceId::get() + DRAMResourceId::get() )); - assert_eq!(Tokens::total_issuance(DNAR::get()), 2000); - assert_eq!(Tokens::free_balance(DNAR::get(), &ALICE), 1500); - assert_eq!(Tokens::free_balance(DNAR::get(), &ChainBridge::account_id()), 500); + assert_eq!(Tokens::total_issuance(DRAM::get()), 2000); + assert_eq!(Tokens::free_balance(DRAM::get(), &ALICE), 1500); + assert_eq!(Tokens::free_balance(DRAM::get(), &ChainBridge::account_id()), 500); - assert_ok!(SetheumChainBridge::register_resource_id( + assert_ok!(ChainSafeTransfer::register_resource_id( Origin::signed(RegistorOrigin::get()), WETHResourceId::get(), WETH::get() @@ -227,7 +227,7 @@ fn transfer_from_bridge_work() { assert_eq!(Tokens::free_balance(WETH::get(), &ALICE), 0); assert_eq!(Tokens::free_balance(WETH::get(), &ChainBridge::account_id()), 0); - assert_ok!(SetheumChainBridge::transfer_from_bridge( + assert_ok!(ChainSafeTransfer::transfer_from_bridge( Origin::signed(ChainBridge::account_id()), ALICE, 500, diff --git a/lib-serml/bridges/chainbridge/src/weights.rs b/lib-serml/bridges/chainbridge/src/weights.rs index 02c88170b..c1395ccba 100644 --- a/lib-serml/bridges/chainbridge/src/weights.rs +++ b/lib-serml/bridges/chainbridge/src/weights.rs @@ -49,9 +49,9 @@ use sp_std::marker::PhantomData; pub trait WeightInfo { fn register_resource_id() -> Weight; fn remove_resource_id() -> Weight; - fn transfer_origin_chain_token_to_bridge() -> Weight; - fn transfer_other_chain_token_to_bridge() -> Weight; - fn transfer_native_to_bridge() -> Weight; + fn transfer_origin_chain_token_to_bridge(b: u32, ) -> Weight; + fn transfer_other_chain_token_to_bridge(b: u32, ) -> Weight; + fn transfer_native_to_bridge(b: u32, ) -> Weight; fn transfer_origin_chain_token_from_bridge() -> Weight; fn transfer_other_chain_token_from_bridge() -> Weight; } @@ -69,18 +69,24 @@ impl WeightInfo for SetheumWeight { .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(2 as Weight)) } - fn transfer_origin_chain_token_to_bridge() -> Weight { + fn transfer_origin_chain_token_to_bridge(b: u32, ) -> Weight { (128_000_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } - fn transfer_other_chain_token_to_bridge() -> Weight { + fn transfer_other_chain_token_to_bridge(b: u32, ) -> Weight { (103_000_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } - fn transfer_native_to_bridge() -> Weight { + fn transfer_native_to_bridge(b: u32, ) -> Weight { (139_000_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) .saturating_add(T::DbWeight::get().reads(4 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) @@ -109,18 +115,24 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(1 as Weight)) .saturating_add(RocksDbWeight::get().writes(2 as Weight)) } - fn transfer_origin_chain_token_to_bridge() -> Weight { + fn transfer_origin_chain_token_to_bridge(b: u32, ) -> Weight { (128_000_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) .saturating_add(RocksDbWeight::get().reads(5 as Weight)) .saturating_add(RocksDbWeight::get().writes(4 as Weight)) } - fn transfer_other_chain_token_to_bridge() -> Weight { + fn transfer_other_chain_token_to_bridge(b: u32, ) -> Weight { (103_000_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) } - fn transfer_native_to_bridge() -> Weight { + fn transfer_native_to_bridge(b: u32, ) -> Weight { (139_000_000 as Weight) + // Standard Error: 0 + .saturating_add((1_000 as Weight).saturating_mul(b as Weight)) .saturating_add(RocksDbWeight::get().reads(4 as Weight)) .saturating_add(RocksDbWeight::get().writes(3 as Weight)) From 970fd9708d705689bf05299533abddadfa91ec2e Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 09:40:57 +0800 Subject: [PATCH 08/22] Update mock.rs --- lib-serml/bridges/chainbridge/src/mock.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib-serml/bridges/chainbridge/src/mock.rs b/lib-serml/bridges/chainbridge/src/mock.rs index d72620155..fd2f4c7b8 100644 --- a/lib-serml/bridges/chainbridge/src/mock.rs +++ b/lib-serml/bridges/chainbridge/src/mock.rs @@ -33,7 +33,7 @@ pub type AccountId = u128; pub const ALICE: AccountId = 1; -mod ecosystem_chainsafe { +mod setheum_chainbridge { pub use super::super::*; } @@ -131,7 +131,7 @@ construct_runtime!( System: frame_system::{Pallet, Call, Storage, Config, Event}, Tokens: orml_tokens::{Pallet, Storage, Event, Config}, ChainBridge: chainbridge::{Pallet, Call, Storage, Event}, - ChainSafeTransfer: ecosystem_chainsafe::{Pallet, Call, Storage, Event}, + ChainSafeTransfer: setheum_chainbridge::{Pallet, Call, Storage, Event}, } ); From a4b6d10dabaa62b0ca12428f3bbdc37380a1e123 Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 10:50:38 +0800 Subject: [PATCH 09/22] Update precompiles and runtimes --- Cargo.lock | 3 + lib-serml/serp/serp-ocw/src/tests.rs | 2 +- lib-serml/serp/serp-treasury/src/lib.rs | 6 +- lib-serml/support/src/lib.rs | 2 +- lib-serml/tokens/nft/src/mock.rs | 2 +- lib-serml/transaction-payment/src/mock.rs | 2 +- primitives/src/tests.rs | 16 +- runtime/common/Cargo.toml | 5 + runtime/common/src/lib.rs | 17 +- runtime/common/src/precompile/dex.rs | 8 +- runtime/common/src/precompile/input.rs | 4 +- runtime/common/src/precompile/mock.rs | 193 ++++++++++++++------- runtime/common/src/precompile/tests.rs | 43 ++--- runtime/newrome/src/benchmarking/tokens.rs | 6 +- runtime/newrome/src/benchmarking/utils.rs | 2 +- runtime/newrome/src/constants.rs | 3 +- runtime/setheum/src/constants.rs | 3 +- 17 files changed, 198 insertions(+), 119 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8a853da1e..f31876e56 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6308,11 +6308,14 @@ dependencies = [ "orml-tokens", "orml-traits", "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-collective", + "pallet-membership", "pallet-proxy", "pallet-scheduler", "pallet-timestamp", "pallet-utility", "parity-scale-codec", + "primitives-proc-macro", "serde", "serde_json", "serp-prices", diff --git a/lib-serml/serp/serp-ocw/src/tests.rs b/lib-serml/serp/serp-ocw/src/tests.rs index 30a9c6888..5a1cb3e95 100644 --- a/lib-serml/serp/serp-ocw/src/tests.rs +++ b/lib-serml/serp/serp-ocw/src/tests.rs @@ -246,7 +246,7 @@ impl SerpTreasury for MockSerpTreasury { } /// Reward SETUSD cashdrop to vault - fn usdj_cashdrop_to_vault() -> DispatchResult { + fn setusd_cashdrop_to_vault() -> DispatchResult { unimplemented!() } diff --git a/lib-serml/serp/serp-treasury/src/lib.rs b/lib-serml/serp/serp-treasury/src/lib.rs index f6d9b23c8..7f9247253 100644 --- a/lib-serml/serp/serp-treasury/src/lib.rs +++ b/lib-serml/serp/serp-treasury/src/lib.rs @@ -215,7 +215,7 @@ pub mod module { if Self::setter_cashdrop_to_vault().is_ok() { count += 1; }; - if Self::usdj_cashdrop_to_vault().is_ok() { + if Self::setusd_cashdrop_to_vault().is_ok() { count += 1; }; @@ -331,9 +331,9 @@ impl SerpTreasury for Pallet { >::deposit_event(Event::CashDropToVault(cashdrop_amount, T::SetterCurrencyId::get())); Ok(()) } - // TODO: Update to 1% per day not 50% per day. and rename `usdj` to `setusd` + // TODO: Update to 1% per day not 50% per day. and rename `setusd` to `setusd` /// SerpUp ratio for SettPay Cashdrops - fn usdj_cashdrop_to_vault() -> DispatchResult { + fn setusd_cashdrop_to_vault() -> DispatchResult { let free_balance = T::Currency::free_balance(T::GetSetUSDCurrencyId::get(), &T::SettPayTreasuryAccountId::get()); // Send 50% of funds to the CashDropVault diff --git a/lib-serml/support/src/lib.rs b/lib-serml/support/src/lib.rs index b9dba5da7..b39c36ac6 100644 --- a/lib-serml/support/src/lib.rs +++ b/lib-serml/support/src/lib.rs @@ -191,7 +191,7 @@ pub trait SerpTreasury { fn setter_cashdrop_to_vault() -> DispatchResult; /// Reward SETUSD cashdrop to vault - fn usdj_cashdrop_to_vault() -> DispatchResult; + fn setusd_cashdrop_to_vault() -> DispatchResult; /// issue serpup surplus(stable currencies) to their destinations according to the serpup_ratio. fn on_serpup(currency_id: Self::CurrencyId, amount: Self::Balance) -> DispatchResult; diff --git a/lib-serml/tokens/nft/src/mock.rs b/lib-serml/tokens/nft/src/mock.rs index b6deaea93..a9648a300 100644 --- a/lib-serml/tokens/nft/src/mock.rs +++ b/lib-serml/tokens/nft/src/mock.rs @@ -208,7 +208,7 @@ impl SerpTreasury for MockSerpTreasury { } /// Reward SETUSD cashdrop to vault - fn usdj_cashdrop_to_vault() -> DispatchResult { + fn setusd_cashdrop_to_vault() -> DispatchResult { unimplemented!() } diff --git a/lib-serml/transaction-payment/src/mock.rs b/lib-serml/transaction-payment/src/mock.rs index 063492ea4..46b929a2d 100644 --- a/lib-serml/transaction-payment/src/mock.rs +++ b/lib-serml/transaction-payment/src/mock.rs @@ -165,7 +165,7 @@ impl SerpTreasury for MockSerpTreasury { } /// Reward SETUSD cashdrop to vault - fn usdj_cashdrop_to_vault() -> DispatchResult { + fn setusd_cashdrop_to_vault() -> DispatchResult { unimplemented!() } diff --git a/primitives/src/tests.rs b/primitives/src/tests.rs index f529600c9..aa153d7b5 100644 --- a/primitives/src/tests.rs +++ b/primitives/src/tests.rs @@ -27,21 +27,21 @@ use std::{ #[test] fn trading_pair_works() { let dnar = CurrencyId::Token(TokenSymbol::DNAR); - let usdj = CurrencyId::Token(TokenSymbol::SETUSD); + let setusd = CurrencyId::Token(TokenSymbol::SETUSD); let erc20 = CurrencyId::Erc20(EvmAddress::from_str("0x0000000000000000000000000000000000000000").unwrap()); - let dnar_usdj_lp = CurrencyId::DexShare(DexShare::Token(TokenSymbol::DNAR), DexShare::Token(TokenSymbol::SETUSD)); + let dnar_setusd_lp = CurrencyId::DexShare(DexShare::Token(TokenSymbol::DNAR), DexShare::Token(TokenSymbol::SETUSD)); let erc20_dnar_lp = CurrencyId::DexShare( DexShare::Token(TokenSymbol::DNAR), DexShare::Erc20(EvmAddress::from_str("0x0000000000000000000000000000000000000000").unwrap()), ); assert_eq!( - TradingPair::from_currency_ids(usdj, dnar).unwrap(), - TradingPair(dnar, usdj) + TradingPair::from_currency_ids(setusd, dnar).unwrap(), + TradingPair(dnar, setusd) ); assert_eq!( - TradingPair::from_currency_ids(dnar, usdj).unwrap(), - TradingPair(dnar, usdj) + TradingPair::from_currency_ids(dnar, setusd).unwrap(), + TradingPair(dnar, setusd) ); assert_eq!( TradingPair::from_currency_ids(erc20, dnar).unwrap(), @@ -50,10 +50,10 @@ fn trading_pair_works() { assert_eq!(TradingPair::from_currency_ids(dnar, dnar), None); assert_eq!( - TradingPair::from_currency_ids(usdj, dnar) + TradingPair::from_currency_ids(setusd, dnar) .unwrap() .dex_share_currency_id(), - dnar_usdj_lp + dnar_setusd_lp ); assert_eq!( TradingPair::from_currency_ids(dnar, erc20) diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml index ba4c15a83..df9a08686 100644 --- a/runtime/common/Cargo.toml +++ b/runtime/common/Cargo.toml @@ -19,6 +19,8 @@ sp-runtime = { default-features = false, git = "https://github.com/paritytech/su frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-scheduler = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } +pallet-collective = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } +pallet-membership = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } # orml dependencies orml-oracle = { path = "../../lib-openrml/oracle", default-features = false } @@ -29,6 +31,7 @@ setheum-evm = { path = "../../lib-serml/evm/evm", default-features = false } setheum-support = { path = "../../lib-serml/support", default-features = false } setheum-transaction-payment = { path = "../../lib-serml/transaction-payment", default-features = false } primitives = { package = "setheum-primitives", path = "../../primitives", default-features = false } +primitives-proc-macro = { path = "../../primitives/proc-macro" } [dev-dependencies] serde_json = "1.0.41" @@ -59,6 +62,8 @@ std = [ "frame-support/std", "frame-system/std", "pallet-scheduler/std", + "pallet-collective/std", + "pallet-membership/std", "orml-oracle/std", "orml-traits/std", "setheum-support/std", diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index 123416088..50f0be023 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -20,19 +20,23 @@ #![cfg_attr(not(feature = "std"), no_std)] +use codec::{Decode, Encode}; use frame_support::{ parameter_types, weights::{ - constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_MILLIS}, + constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_MILLIS, WEIGHT_PER_SECOND}, DispatchClass, Weight, }, }; -use frame_system::limits; +use frame_system::{limits, EnsureOneOf, EnsureRoot}; pub use setheum_support::{ExchangeRate, PrecompileCallerFilter, Price, Rate, Ratio}; use primitives::{ Balance, CurrencyId, PRECOMPILE_ADDRESS_START, PREDEPLOY_ADDRESS_START, SYSTEM_CONTRACT_ADDRESS_PREFIX, }; -use sp_core::H160; +use sp_core::{ + u32_trait::{_1, _2, _3, _4}, + H160, +}; use sp_runtime::{ // TODO: move after https://github.com/paritytech/substrate/pull/9209 offchain::storage_lock::BlockNumberProvider, @@ -50,14 +54,17 @@ pub use precompile::{ pub use primitives::currency::{ TokenInfo, DNAR, DRAM, SETR, SETUSD, SETEUR, SETGBP, SETCHF, SETSAR, RENBTC, + AccountId, }; pub type TimeStampedPrice = orml_oracle::TimestampedValue; // Priority of unsigned transactions parameter_types! { - pub const StakingUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2; - pub const RenvmBridgeUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2; + // Operational is 3/4 of TransactionPriority::max_value(). + // Ensure Inherent -> Operational tx -> Unsigned tx -> Signed normal tx + pub const StakingUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2; // 50% + pub const RenvmBridgeUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 4; // 25% } /// Check if the given `address` is a system contract. diff --git a/runtime/common/src/precompile/dex.rs b/runtime/common/src/precompile/dex.rs index 673894e92..a44c6432f 100644 --- a/runtime/common/src/precompile/dex.rs +++ b/runtime/common/src/precompile/dex.rs @@ -125,7 +125,7 @@ where path, supply_amount ); - let value = Dex::get_swap_target_amount(&path, supply_amount, None) + let value = Dex::get_swap_target_amount(&path, supply_amount) .ok_or_else(|| ExitError::Other("Dex get_swap_target_amount failed".into()))?; // output @@ -148,7 +148,7 @@ where path, target_amount ); - let value = Dex::get_swap_supply_amount(&path, target_amount, None) + let value = Dex::get_swap_supply_amount(&path, target_amount) .ok_or_else(|| ExitError::Other("Dex get_swap_supply_amount failed".into()))?; // output @@ -174,7 +174,7 @@ where ); let value = - Dex::swap_with_exact_supply(&who, &path, supply_amount, min_target_amount, None).map_err(|e| { + Dex::swap_with_exact_supply(&who, &path, supply_amount, min_target_amount).map_err(|e| { let err_msg: &str = e.into(); ExitError::Other(err_msg.into()) })?; @@ -202,7 +202,7 @@ where ); let value = - Dex::swap_with_exact_target(&who, &path, target_amount, max_supply_amount, None).map_err(|e| { + Dex::swap_with_exact_target(&who, &path, target_amount, max_supply_amount).map_err(|e| { let err_msg: &str = e.into(); ExitError::Other(err_msg.into()) })?; diff --git a/runtime/common/src/precompile/input.rs b/runtime/common/src/precompile/input.rs index d85bfc25d..f3c81f6d5 100644 --- a/runtime/common/src/precompile/input.rs +++ b/runtime/common/src/precompile/input.rs @@ -197,7 +197,7 @@ mod tests { use sp_core::H160; use sp_runtime::RuntimeDebug; - use setheum_support::mocks::{MockAddressMapping, MockCurrencyIdMapping}; + use module_support::mocks::{MockAddressMapping, MockCurrencyIdMapping}; use primitives::{AccountId, CurrencyId, TokenSymbol}; #[derive(RuntimeDebug, PartialEq, Eq, TryFromPrimitive)] @@ -274,7 +274,7 @@ mod tests { raw_input[67] = 1; let input = TestInput::new(&raw_input[..]); - assert_ok!(input.currency_id_at(1), CurrencyId::Token(TokenSymbol::SETUSD)); + assert_ok!(input.currency_id_at(1), CurrencyId::Token(TokenSymbol::SETR)); } #[test] diff --git a/runtime/common/src/precompile/mock.rs b/runtime/common/src/precompile/mock.rs index 7e9f3124e..caa237d70 100644 --- a/runtime/common/src/precompile/mock.rs +++ b/runtime/common/src/precompile/mock.rs @@ -29,7 +29,7 @@ use frame_support::{ }; use frame_system::{EnsureRoot, EnsureSignedBy}; use setheum_support::{ - mocks::MockAddressMapping, AddressMapping as AddressMappingT, ExchangeRate, ExchangeRateProvider, + mocks::MockAddressMapping, AddressMapping as AddressMappingT, ExchangeRate, ExchangeRateProvider, SerpTreasury, }; use orml_traits::{parameter_type_with_key, MultiReservableCurrency}; pub use primitives::{ @@ -149,8 +149,8 @@ impl pallet_balances::Config for Test { } // Currencies constants - CurrencyId/TokenSymbol -pub const DNAR: CurrencyId = CurrencyId::Token(TokenSymbol::DNAR); pub const DRAM: CurrencyId = CurrencyId::Token(TokenSymbol::DRAM); +pub const DNAR: CurrencyId = CurrencyId::Token(TokenSymbol::DNAR); pub const SETR: CurrencyId = CurrencyId::Token(TokenSymbol::SETR); pub const SETUSD: CurrencyId = CurrencyId::Token(TokenSymbol::SETUSD); pub const SETEUR: CurrencyId = CurrencyId::Token(TokenSymbol::SETEUR); @@ -163,26 +163,128 @@ pub const RENBTC: CurrencyId = CurrencyId::Token(TokenSymbol::RENBTC); pub const LP_DNAR_SETUSD: CurrencyId = CurrencyId::DexShare(DexShare::Token(TokenSymbol::DNAR), DexShare::Token(TokenSymbol::SETUSD)); -// Currencies constants - FiatCurrencyIds (CurrencyId/TokenSymbol) -pub const CHF: CurrencyId = CurrencyId::Token(TokenSymbol::CHF); -pub const EUR: CurrencyId = CurrencyId::Token(TokenSymbol::EUR); -pub const GBP: CurrencyId = CurrencyId::Token(TokenSymbol::GBP); -pub const SAR: CurrencyId = CurrencyId::Token(TokenSymbol::SAR); -pub const USD: CurrencyId = CurrencyId::Token(TokenSymbol::USD); -pub const KWD: CurrencyId = CurrencyId::Token(TokenSymbol::KWD); -pub const JOD: CurrencyId = CurrencyId::Token(TokenSymbol::JOD); -pub const BHD: CurrencyId = CurrencyId::Token(TokenSymbol::BHD); -pub const KYD: CurrencyId = CurrencyId::Token(TokenSymbol::KYD); -pub const OMR: CurrencyId = CurrencyId::Token(TokenSymbol::OMR); -pub const GIP: CurrencyId = CurrencyId::Token(TokenSymbol::GIP); - parameter_types! { pub const GetNativeCurrencyId: CurrencyId = DNAR; } +pub struct MockSerpTreasury; +impl SerpTreasury for MockSerpTreasury { + type Balance = Balance; + type CurrencyId = CurrencyId; + + /// SerpUp ratio for BuyBack Swaps to burn Dinar + fn get_buyback_serpup( + _amount: Balance, + _currency_id: CurrencyId, + ) -> DispatchResult { + unimplemented!() + } + + /// SerpUp ratio for Setheum Foundation's Charity Fund + fn get_charity_fund_serpup( + _amount: Balance, + _currency_id: CurrencyId + ) -> DispatchResult { + unimplemented!() + } + + /// SerpUp ratio for SettPay Cashdrops + fn get_cashdrop_serpup( + _amount: Balance, + _currency_id: CurrencyId + ) -> DispatchResult { + unimplemented!() + } + + /// Reward SETR cashdrop to vault + fn setter_cashdrop_to_vault() -> DispatchResult { + unimplemented!() + } + + /// Reward SETUSD cashdrop to vault + fn setusd_cashdrop_to_vault() -> DispatchResult { + unimplemented!() + } + + /// issue serpup surplus(stable currencies) to their destinations according to the serpup_ratio. + fn on_serpup( + _currency_id: CurrencyId, + _amount: Balance, + ) -> DispatchResult { + unimplemented!() + } + + /// buy back and burn surplus(stable currencies) with swap by DEX. + fn on_serpdown( + _currency_id: CurrencyId, + _amount: Balance, + ) -> DispatchResult { + unimplemented!() + } + + /// get the minimum supply of a setcurrency - by key + fn get_minimum_supply( + _currency_id: CurrencyId + ) -> Balance { + unimplemented!() + } + + /// issue standard to `who` + fn issue_standard( + _currency_id: CurrencyId, + _who: &AccountId, + _standard: Balance + ) -> DispatchResult { + unimplemented!() + } + + /// burn standard(stable currency) of `who` + fn burn_standard( + _currency_id: CurrencyId, + _who: &AccountId, + _standard: Balance + ) -> DispatchResult { + unimplemented!() + } + + /// issue setter of amount setter to `who` + fn issue_setter( + _who: &AccountId, + _setter: Balance + ) -> DispatchResult { + unimplemented!() + } + + /// burn setter of `who` + fn burn_setter( + _who: &AccountId, + _setter: Balance + ) -> DispatchResult { + unimplemented!() + } + + /// deposit reserve asset (Setter (SETR)) to serp treasury by `who` + fn deposit_setter( + _from: &AccountId, + _amount: Balance + ) -> DispatchResult { + unimplemented!() + } + + /// claim cashdrop of `currency_id` relative to `transfer_amount` for `who` + fn claim_cashdrop( + _currency_id: CurrencyId, + _who: &AccountId, + _transfer_amount: Balance + ) -> DispatchResult { + unimplemented!() + } +} + // TODO: Update! impl setheum_currencies::Config for Test { type Event = Event; + type SerpTreasury = MockSerpTreasury; type MultiCurrency = Tokens; type NativeCurrency = AdaptedBasicCurrency; type GetNativeCurrencyId = GetNativeCurrencyId; @@ -205,6 +307,7 @@ parameter_types! { pub const CreateTokenDeposit: Balance = 100; pub const DataDepositPerByte: Balance = 10; pub const NftPalletId: PalletId = PalletId(*b"set/sNFT"); + pub MaxAttributesBytes: u32 = 2048; } impl setheum_nft::Config for Test { type Event = Event; @@ -213,6 +316,7 @@ impl setheum_nft::Config for Test { type CreateTokenDeposit = CreateTokenDeposit; type DataDepositPerByte = DataDepositPerByte; type PalletId = NftPalletId; + type MaxAttributesBytes = MaxAttributesBytes; type WeightInfo = (); } @@ -233,14 +337,13 @@ impl orml_nft::Config for Test { parameter_types! { pub const TransactionByteFee: Balance = 10; pub const SetterCurrencyId: CurrencyId = CurrencyId::Token(TokenSymbol::SETR); - pub AllNonNativeCurrencyIds: Vec = vec![CurrencyId::Token(TokenSymbol::SETR)]; - pub MaxSlippageSwapWithDEX: Ratio = Ratio::one(); + pub DefaultFeeSwapPathList: Vec> = vec![vec![CurrencyId::Token(TokenSymbol::SETUSD), CurrencyId::Token(TokenSymbol::DNAR)]]; + pub MaxSwapSlippageCompareToOracle: Ratio = Ratio::one(); } impl setheum_transaction_payment::Config for Test { - type AllNonNativeCurrencyIds = AllNonNativeCurrencyIds; type NativeCurrencyId = GetNativeCurrencyId; - type SetterCurrencyId = SetterCurrencyId; + type DefaultFeeSwapPathList = DefaultFeeSwapPathList; type Currency = Balances; type MultiCurrency = Currencies; type OnTransactionPayment = (); @@ -248,7 +351,9 @@ impl setheum_transaction_payment::Config for Test { type WeightToFee = IdentityFee; type FeeMultiplierUpdate = (); type DEX = (); - type MaxSlippageSwapWithDEX = MaxSlippageSwapWithDEX; + type MaxSwapSlippageCompareToOracle = MaxSwapSlippageCompareToOracle; + type TradingPathLimit = TradingPathLimit; + type PriceSource = serp_prices::RealTimePriceProvider; type WeightInfo = (); } pub type ChargeTransactionPayment = setheum_transaction_payment::ChargeTransactionPayment; @@ -419,36 +524,9 @@ impl setheum_evm::Config for Test { type WeightInfo = (); } -pub struct MockLiquidStakingExchangeProvider; -impl ExchangeRateProvider for MockLiquidStakingExchangeProvider { - fn get_exchange_rate() -> ExchangeRate { - ExchangeRate::saturating_from_rational(1, 2) - } -} - parameter_types! { - pub const SetterCurrencyId: CurrencyId = SETR; // Setter currency ticker is SETR. pub const GetSetUSDCurrencyId: CurrencyId = SETUSD; // SetUSD currency ticker is SETUSD. - pub const GetFiatCHFCurrencyId: CurrencyId = CHF; // The CHF Fiat currency denomination. - pub const GetFiatEURCurrencyId: CurrencyId = EUR; // The EUR Fiat currency denomination. - pub const GetFiatGBPCurrencyId: CurrencyId = GBP; // The GBP Fiat currency denomination. - pub const GetFiatSARCurrencyId: CurrencyId = SAR; // The SAR Fiat currency denomination. - pub const GetFiatUSDCurrencyId: CurrencyId = USD; // The USD Fiat currency denomination. pub FiatUsdFixedPrice: Price = Price::saturating_from_rational(1, 1); - - pub const GetSetterPegOneCurrencyId: CurrencyId = GBP; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegTwoCurrencyId: CurrencyId = EUR; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegThreeCurrencyId: CurrencyId = KWD; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegFourCurrencyId: CurrencyId = JOD; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegFiveCurrencyId: CurrencyId = BHD; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegSixCurrencyId: CurrencyId = KYD; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegSevenCurrencyId: CurrencyId = OMR; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegEightCurrencyId: CurrencyId = CHF; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegNineCurrencyId: CurrencyId = GIP; // Fiat pegs of the Setter (SETR). - pub const GetSetterPegTenCurrencyId: CurrencyId = USD; // Fiat pegs of the Setter (SETR). - - pub StableCurrencyIds: Vec = vec![SETR, SETCHF, SETEUR, SETGBP, SETSAR, SETUSD]; - pub FiatCurrencyIds: Vec = vec![CHF, EUR, GBP, QAR, SAR, USD, JOD, BHD, KYD, OMR, GIP]; } ord_parameter_types! { @@ -458,26 +536,9 @@ ord_parameter_types! { impl setheum_prices::Config for Test { type Event = Event; type Source = Oracle; - type SetterCurrencyId = SetterCurrencyId; type GetSetUSDCurrencyId = GetSetUSDCurrencyId; - type GetFiatCHFCurrencyId = GetFiatCHFCurrencyId; - type GetFiatEURCurrencyId = GetFiatEURCurrencyId; - type GetFiatGBPCurrencyId = GetFiatGBPCurrencyId; - type GetFiatSARCurrencyId = GetFiatSARCurrencyId; - type GetFiatUSDCurrencyId = GetFiatUSDCurrencyId; type FiatUsdFixedPrice = FiatUsdFixedPrice; - type GetSetterPegOneCurrencyId = GetSetterPegOneCurrencyId; - type GetSetterPegTwoCurrencyId = GetSetterPegTwoCurrencyId; - type GetSetterPegThreeCurrencyId = GetSetterPegThreeCurrencyId; - type GetSetterPegFourCurrencyId = GetSetterPegFourCurrencyId; - type GetSetterPegFiveCurrencyId = GetSetterPegFiveCurrencyId; - type GetSetterPegSixCurrencyId = GetSetterPegSixCurrencyId; - type GetSetterPegSevenCurrencyId = GetSetterPegSevenCurrencyId; - type GetSetterPegEightCurrencyId = GetSetterPegEightCurrencyId; - type GetSetterPegNineCurrencyId = GetSetterPegNineCurrencyId; - type GetSetterPegTenCurrencyId = GetSetterPegTenCurrencyId; type LockOrigin = EnsureSignedBy; - type LiquidStakingExchangeRateProvider = MockLiquidStakingExchangeProvider; type DEX = DexModule; type Currency = Currencies; type CurrencyIdMapping = EvmCurrencyIdMapping; @@ -508,7 +569,7 @@ pub fn dnar_evm_address() -> EvmAddress { EvmAddress::try_from(DNAR).unwrap() } -pub fn usdj_evm_address() -> EvmAddress { +pub fn setusd_evm_address() -> EvmAddress { EvmAddress::try_from(SETUSD).unwrap() } @@ -516,7 +577,7 @@ pub fn renbtc_evm_address() -> EvmAddress { EvmAddress::try_from(RENBTC).unwrap() } -pub fn lp_dnar_usdj_evm_address() -> EvmAddress { +pub fn lp_dnar_setusd_evm_address() -> EvmAddress { EvmAddress::try_from(LP_DNAR_SETUSD).unwrap() } diff --git a/runtime/common/src/precompile/tests.rs b/runtime/common/src/precompile/tests.rs index 82ff393a8..edd259da3 100644 --- a/runtime/common/src/precompile/tests.rs +++ b/runtime/common/src/precompile/tests.rs @@ -16,12 +16,13 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +#![allow(clippy::erasing_op)] #![cfg(test)] use super::*; use crate::precompile::{ mock::{ - dnar_evm_address, alice, alice_evm_addr, usdj_evm_address, bob, bob_evm_addr, erc20_address_not_exists, - get_task_id, lp_dnar_usdj_evm_address, new_test_ext, renbtc_evm_address, run_to_block, Balances, DexModule, + dnar_evm_address, alice, alice_evm_addr, setusd_evm_address, bob, bob_evm_addr, erc20_address_not_exists, + get_task_id, lp_dnar_setusd_evm_address, new_test_ext, renbtc_evm_address, run_to_block, Balances, DexModule, DexPrecompile, Event as TestEvent, MultiCurrencyPrecompile, Oracle, OraclePrecompile, Origin, Price, ScheduleCallPrecompile, System, Test, ALICE, SETUSD, SETR, INITIAL_BALANCE, RENBTC, }, @@ -145,7 +146,7 @@ fn multicurrency_precompile_should_work() { assert_eq!(used_gas, 0); // DexShare - context.caller = lp_dnar_usdj_evm_address(); + context.caller = lp_dnar_setusd_evm_address(); let (reason, output, used_gas) = MultiCurrencyPrecompile::execute(&input, None, &context).unwrap(); assert_eq!(reason, ExitSucceed::Returned); let mut expected_output = [0u8; 32]; @@ -168,7 +169,7 @@ fn multicurrency_precompile_should_work() { assert_eq!(used_gas, 0); // DexShare - context.caller = lp_dnar_usdj_evm_address(); + context.caller = lp_dnar_setusd_evm_address(); let (reason, output, used_gas) = MultiCurrencyPrecompile::execute(&input, None, &context).unwrap(); assert_eq!(reason, ExitSucceed::Returned); let mut expected_output = [0u8; 32]; @@ -192,7 +193,7 @@ fn multicurrency_precompile_should_work() { assert_eq!(used_gas, 0); // DexShare - context.caller = lp_dnar_usdj_evm_address(); + context.caller = lp_dnar_setusd_evm_address(); let (reason, output, used_gas) = MultiCurrencyPrecompile::execute(&input, None, &context).unwrap(); assert_eq!(reason, ExitSucceed::Returned); let mut expected_output = [0u8; 32]; @@ -216,7 +217,7 @@ fn multicurrency_precompile_should_work() { assert_eq!(used_gas, 0); // DexShare - context.caller = lp_dnar_usdj_evm_address(); + context.caller = lp_dnar_setusd_evm_address(); let (reason, output, used_gas) = MultiCurrencyPrecompile::execute(&input, None, &context).unwrap(); assert_eq!(reason, ExitSucceed::Returned); let expected_output = [0u8; 32]; @@ -241,7 +242,7 @@ fn multicurrency_precompile_should_work() { assert_eq!(used_gas, 0); // DexShare - context.caller = lp_dnar_usdj_evm_address(); + context.caller = lp_dnar_setusd_evm_address(); let (reason, output, used_gas) = MultiCurrencyPrecompile::execute(&input, None, &context).unwrap(); assert_eq!(reason, ExitSucceed::Returned); let expected_output = [0u8; 32]; @@ -272,7 +273,7 @@ fn multicurrency_precompile_should_work() { assert_eq!(Balances::free_balance(bob()), to_balance + 1); // DexShare - context.caller = lp_dnar_usdj_evm_address(); + context.caller = lp_dnar_setusd_evm_address(); assert_noop!( MultiCurrencyPrecompile::execute(&input, None, &context), ExitError::Other("BalanceTooLow".into()) @@ -296,7 +297,7 @@ fn oracle_precompile_should_work() { // action input[1 * 32..4 + 1 * 32].copy_from_slice(&Into::::into(oracle::Action::GetPrice).to_be_bytes()); // RENBTC - U256::from_big_endian(&renbtc_evm_address().as_bytes()).to_big_endian(&mut input[4 + 1 * 32..4 + 2 * 32]); + U256::from_big_endian(renbtc_evm_address().as_bytes()).to_big_endian(&mut input[4 + 1 * 32..4 + 2 * 32]); // no price yet let (reason, output, used_gas) = OraclePrecompile::execute(&input, None, &context).unwrap(); @@ -618,9 +619,9 @@ fn dex_precompile_get_liquidity_should_work() { // action input[1 * 32..4 + 1 * 32].copy_from_slice(&Into::::into(dex::Action::GetLiquidityPool).to_be_bytes()); // RENBTC - U256::from_big_endian(&renbtc_evm_address().as_bytes()).to_big_endian(&mut input[4 + 1 * 32..4 + 2 * 32]); + U256::from_big_endian(renbtc_evm_address().as_bytes()).to_big_endian(&mut input[4 + 1 * 32..4 + 2 * 32]); // SETUSD - U256::from_big_endian(&usdj_evm_address().as_bytes()).to_big_endian(&mut input[4 + 2 * 32..4 + 3 * 32]); + U256::from_big_endian(setusd_evm_address().as_bytes()).to_big_endian(&mut input[4 + 2 * 32..4 + 3 * 32]); let mut expected_output = [0u8; 64]; U256::from(1_000).to_big_endian(&mut expected_output[..32]); @@ -663,9 +664,9 @@ fn dex_precompile_get_liquidity_token_address_should_work() { input[1 * 32..4 + 1 * 32] .copy_from_slice(&Into::::into(dex::Action::GetLiquidityTokenAddress).to_be_bytes()); // RENBTC - U256::from_big_endian(&renbtc_evm_address().as_bytes()).to_big_endian(&mut input[4 + 1 * 32..4 + 2 * 32]); + U256::from_big_endian(renbtc_evm_address().as_bytes()).to_big_endian(&mut input[4 + 1 * 32..4 + 2 * 32]); // SETUSD - U256::from_big_endian(&usdj_evm_address().as_bytes()).to_big_endian(&mut input[4 + 2 * 32..4 + 3 * 32]); + U256::from_big_endian(setusd_evm_address().as_bytes()).to_big_endian(&mut input[4 + 2 * 32..4 + 3 * 32]); let mut expected_output = [0u8; 32]; let address = H160::from_str("0x0000000000000000000000010000000100000004").unwrap(); @@ -722,9 +723,9 @@ fn dex_precompile_get_swap_target_amount_should_work() { // path_len U256::from(2).to_big_endian(&mut input[4 + 3 * 32..4 + 4 * 32]); // RENBTC - U256::from_big_endian(&renbtc_evm_address().as_bytes()).to_big_endian(&mut input[4 + 4 * 32..4 + 5 * 32]); + U256::from_big_endian(renbtc_evm_address().as_bytes()).to_big_endian(&mut input[4 + 4 * 32..4 + 5 * 32]); // SETUSD - U256::from_big_endian(&usdj_evm_address().as_bytes()).to_big_endian(&mut input[4 + 5 * 32..4 + 6 * 32]); + U256::from_big_endian(setusd_evm_address().as_bytes()).to_big_endian(&mut input[4 + 5 * 32..4 + 6 * 32]); let mut expected_output = [0u8; 32]; U256::from(989).to_big_endian(&mut expected_output[..32]); @@ -771,9 +772,9 @@ fn dex_precompile_get_swap_supply_amount_should_work() { // path_len U256::from(2).to_big_endian(&mut input[4 + 3 * 32..4 + 4 * 32]); // RENBTC - U256::from_big_endian(&renbtc_evm_address().as_bytes()).to_big_endian(&mut input[4 + 4 * 32..4 + 5 * 32]); + U256::from_big_endian(renbtc_evm_address().as_bytes()).to_big_endian(&mut input[4 + 4 * 32..4 + 5 * 32]); // SETUSD - U256::from_big_endian(&usdj_evm_address().as_bytes()).to_big_endian(&mut input[4 + 5 * 32..4 + 6 * 32]); + U256::from_big_endian(setusd_evm_address().as_bytes()).to_big_endian(&mut input[4 + 5 * 32..4 + 6 * 32]); let mut expected_output = [0u8; 32]; U256::from(1).to_big_endian(&mut expected_output[..32]); @@ -824,9 +825,9 @@ fn dex_precompile_swap_with_exact_supply_should_work() { // path_len U256::from(2).to_big_endian(&mut input[4 + 5 * 32..4 + 6 * 32]); // RENBTC - U256::from_big_endian(&renbtc_evm_address().as_bytes()).to_big_endian(&mut input[4 + 6 * 32..4 + 7 * 32]); + U256::from_big_endian(renbtc_evm_address().as_bytes()).to_big_endian(&mut input[4 + 6 * 32..4 + 7 * 32]); // SETUSD - U256::from_big_endian(&usdj_evm_address().as_bytes()).to_big_endian(&mut input[4 + 7 * 32..4 + 8 * 32]); + U256::from_big_endian(setusd_evm_address().as_bytes()).to_big_endian(&mut input[4 + 7 * 32..4 + 8 * 32]); let mut expected_output = [0u8; 32]; U256::from(989).to_big_endian(&mut expected_output[..32]); @@ -877,9 +878,9 @@ fn dex_precompile_swap_with_exact_target_should_work() { // path_len U256::from(2).to_big_endian(&mut input[4 + 5 * 32..4 + 6 * 32]); // RENBTC - U256::from_big_endian(&renbtc_evm_address().as_bytes()).to_big_endian(&mut input[4 + 6 * 32..4 + 7 * 32]); + U256::from_big_endian(renbtc_evm_address().as_bytes()).to_big_endian(&mut input[4 + 6 * 32..4 + 7 * 32]); // SETUSD - U256::from_big_endian(&usdj_evm_address().as_bytes()).to_big_endian(&mut input[4 + 7 * 32..4 + 8 * 32]); + U256::from_big_endian(setusd_evm_address().as_bytes()).to_big_endian(&mut input[4 + 7 * 32..4 + 8 * 32]); let mut expected_output = [0u8; 32]; U256::from(1).to_big_endian(&mut expected_output[..32]); diff --git a/runtime/newrome/src/benchmarking/tokens.rs b/runtime/newrome/src/benchmarking/tokens.rs index e8d8a50b4..8ddcae650 100644 --- a/runtime/newrome/src/benchmarking/tokens.rs +++ b/runtime/newrome/src/benchmarking/tokens.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use super::utils::{lookup_of_account, set_usdj_balance}; +use super::utils::{lookup_of_account, set_setusd_balance}; use crate::{dollar, AccountId, Balance, Runtime, Tokens, SETUSD}; use sp_std::prelude::*; @@ -40,7 +40,7 @@ runtime_benchmarks! { let amount: Balance = d * dollar(SETUSD); let from = account("from", 0, SEED); - set_usdj_balance(&from, amount); + set_setusd_balance(&from, amount); let to: AccountId = account("to", 0, SEED); let to_lookup = lookup_of_account(to.clone()); @@ -53,7 +53,7 @@ runtime_benchmarks! { let amount: Balance = d * dollar(SETUSD); let from = account("from", 0, SEED); - set_usdj_balance(&from, amount); + set_setusd_balance(&from, amount); let to: AccountId = account("to", 0, SEED); let to_lookup = lookup_of_account(to); diff --git a/runtime/newrome/src/benchmarking/utils.rs b/runtime/newrome/src/benchmarking/utils.rs index beb6933e9..dac5952e9 100644 --- a/runtime/newrome/src/benchmarking/utils.rs +++ b/runtime/newrome/src/benchmarking/utils.rs @@ -33,7 +33,7 @@ pub fn set_balance(currency_id: CurrencyId, who: &AccountId, balance: Balance) { ); } -pub fn set_usdj_balance(who: &AccountId, balance: Balance) { +pub fn set_setusd_balance(who: &AccountId, balance: Balance) { set_balance(CurrencyId::Token(TokenSymbol::SETUSD), who, balance) } diff --git a/runtime/newrome/src/constants.rs b/runtime/newrome/src/constants.rs index 7ab7945a8..a07f5a7b9 100644 --- a/runtime/newrome/src/constants.rs +++ b/runtime/newrome/src/constants.rs @@ -22,7 +22,8 @@ pub mod time { use primitives::{BlockNumber, Moment}; - pub const SECS_PER_BLOCK: Moment = 4; + // 3 seconds average blocktime + pub const SECS_PER_BLOCK: Moment = 3; pub const MILLISECS_PER_BLOCK: Moment = SECS_PER_BLOCK * 1000; // These time units are defined in number of blocks. diff --git a/runtime/setheum/src/constants.rs b/runtime/setheum/src/constants.rs index fbfbe73ab..f1301c97a 100644 --- a/runtime/setheum/src/constants.rs +++ b/runtime/setheum/src/constants.rs @@ -22,7 +22,8 @@ pub mod time { use primitives::{BlockNumber, Moment}; - pub const SECS_PER_BLOCK: Moment = 4; + // 3 seconds average blocktime + pub const SECS_PER_BLOCK: Moment = 3; pub const MILLISECS_PER_BLOCK: Moment = SECS_PER_BLOCK * 1000; // These time units are defined in number of blocks. From f77a069a17e2c940e23e650bbf7be80aa4c4185b Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 10:52:26 +0800 Subject: [PATCH 10/22] Fix SerpTreasury mocks --- lib-serml/settmint/settmint-engine/src/mock.rs | 2 +- lib-serml/settmint/settmint-gateway/src/mock.rs | 2 +- lib-serml/settmint/settmint-manager/src/mock.rs | 2 +- lib-serml/tokens/currencies/src/mock.rs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib-serml/settmint/settmint-engine/src/mock.rs b/lib-serml/settmint/settmint-engine/src/mock.rs index 9aa125963..321179f85 100644 --- a/lib-serml/settmint/settmint-engine/src/mock.rs +++ b/lib-serml/settmint/settmint-engine/src/mock.rs @@ -282,7 +282,7 @@ impl serp_treasury::Config for Runtime { type SettPayTreasuryAccountId = SettPayTreasuryAccountId; type CashDropVaultAccountId = CashDropVaultAccountId; type CharityFundAccountId = CharityFundAccountId; - type DefaultFeeSwapPathList = DefaultFeeSwapPathList; + type DefaultSwapPathList = DefaultFeeSwapPathList; type Dex = SetheumDEX; type MaxSwapSlippageCompareToOracle = MaxSwapSlippageCompareToOracle; type TradingPathLimit = TradingPathLimit; diff --git a/lib-serml/settmint/settmint-gateway/src/mock.rs b/lib-serml/settmint/settmint-gateway/src/mock.rs index 600463b60..541dff49d 100644 --- a/lib-serml/settmint/settmint-gateway/src/mock.rs +++ b/lib-serml/settmint/settmint-gateway/src/mock.rs @@ -257,7 +257,7 @@ impl serp_treasury::Config for Runtime { type SettPayTreasuryAccountId = SettPayTreasuryAccountId; type CashDropVaultAccountId = CashDropVaultAccountId; type CharityFundAccountId = CharityFundAccountId; - type DefaultFeeSwapPathList = DefaultFeeSwapPathList; + type DefaultSwapPathList = DefaultFeeSwapPathList; type Dex = SetheumDEX; type MaxSwapSlippageCompareToOracle = MaxSwapSlippageCompareToOracle; type TradingPathLimit = TradingPathLimit; diff --git a/lib-serml/settmint/settmint-manager/src/mock.rs b/lib-serml/settmint/settmint-manager/src/mock.rs index 75075edc9..123a9a392 100644 --- a/lib-serml/settmint/settmint-manager/src/mock.rs +++ b/lib-serml/settmint/settmint-manager/src/mock.rs @@ -267,7 +267,7 @@ impl serp_treasury::Config for Runtime { type SettPayTreasuryAccountId = SettPayTreasuryAccountId; type CashDropVaultAccountId = CashDropVaultAccountId; type CharityFundAccountId = CharityFundAccountId; - type DefaultFeeSwapPathList = DefaultFeeSwapPathList; + type DefaultSwapPathList = DefaultFeeSwapPathList; type Dex = SetheumDEX; type MaxSwapSlippageCompareToOracle = MaxSwapSlippageCompareToOracle; type TradingPathLimit = TradingPathLimit; diff --git a/lib-serml/tokens/currencies/src/mock.rs b/lib-serml/tokens/currencies/src/mock.rs index 87a831c31..115aff30d 100644 --- a/lib-serml/tokens/currencies/src/mock.rs +++ b/lib-serml/tokens/currencies/src/mock.rs @@ -348,7 +348,7 @@ impl serp_treasury::Config for Runtime { type SettPayTreasuryAccountId = SettPayTreasuryAccountId; type CashDropVaultAccountId = CashDropVaultAccountId; type CharityFundAccountId = CharityFundAccountId; - type DefaultFeeSwapPathList = DefaultFeeSwapPathList; + type DefaultSwapPathList = DefaultFeeSwapPathList; type Dex = SetheumDEX; type MaxSwapSlippageCompareToOracle = MaxSwapSlippageCompareToOracle; type TradingPathLimit = TradingPathLimit; From a3837b18d526b3584785a9db57cb059edea92fa3 Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 11:03:56 +0800 Subject: [PATCH 11/22] Rename SettMint to SetMint #516 --- Cargo.lock | 24 +++++++++---------- Cargo.toml | 2 +- README.md | 8 +++---- .../setmint-engine}/Cargo.toml | 6 ++--- .../setmint-engine}/src/lib.rs | 4 ++-- .../setmint-engine}/src/mock.rs | 10 ++++---- .../src/standard_exchange_rate_convertor.rs | 0 .../setmint-engine}/src/tests.rs | 2 +- .../setmint-gateway}/Cargo.toml | 10 ++++---- .../setmint-gateway}/src/lib.rs | 10 ++++---- .../setmint-gateway}/src/mock.rs | 16 ++++++------- .../setmint-gateway}/src/tests.rs | 0 .../setmint-gateway}/src/weights.rs | 10 ++++---- .../setmint-manager}/Cargo.toml | 2 +- .../setmint-manager}/src/lib.rs | 4 ++-- .../setmint-manager}/src/mock.rs | 6 ++--- .../setmint-manager}/src/tests.rs | 2 +- primitives/src/lib.rs | 2 +- runtime/newrome/Cargo.toml | 20 ++++++++-------- runtime/newrome/src/benchmarking/mod.rs | 2 +- ...settmint_manager.rs => setmint_manager.rs} | 2 +- runtime/newrome/src/lib.rs | 18 +++++++------- runtime/newrome/src/weights/mod.rs | 4 ++-- ...settmint_manager.rs => setmint_manager.rs} | 6 ++--- runtime/setheum/Cargo.toml | 20 ++++++++-------- runtime/setheum/src/lib.rs | 18 +++++++------- runtime/setheum/src/weights/mod.rs | 4 ++-- ...settmint_manager.rs => setmint_manager.rs} | 8 +++---- 28 files changed, 110 insertions(+), 110 deletions(-) rename lib-serml/{settmint/settmint-engine => setmint/setmint-engine}/Cargo.toml (93%) rename lib-serml/{settmint/settmint-engine => setmint/setmint-engine}/src/lib.rs (96%) rename lib-serml/{settmint/settmint-engine => setmint/setmint-engine}/src/mock.rs (97%) rename lib-serml/{settmint/settmint-engine => setmint/setmint-engine}/src/standard_exchange_rate_convertor.rs (100%) rename lib-serml/{settmint/settmint-engine => setmint/setmint-engine}/src/tests.rs (98%) rename lib-serml/{settmint/settmint-gateway => setmint/setmint-gateway}/Cargo.toml (86%) rename lib-serml/{settmint/settmint-gateway => setmint/setmint-gateway}/src/lib.rs (95%) rename lib-serml/{settmint/settmint-gateway => setmint/setmint-gateway}/src/mock.rs (96%) rename lib-serml/{settmint/settmint-gateway => setmint/setmint-gateway}/src/tests.rs (100%) rename lib-serml/{settmint/settmint-gateway => setmint/setmint-gateway}/src/weights.rs (90%) rename lib-serml/{settmint/settmint-manager => setmint/setmint-manager}/Cargo.toml (98%) rename lib-serml/{settmint/settmint-manager => setmint/setmint-manager}/src/lib.rs (99%) rename lib-serml/{settmint/settmint-manager => setmint/setmint-manager}/src/mock.rs (98%) rename lib-serml/{settmint/settmint-manager => setmint/setmint-manager}/src/tests.rs (99%) rename runtime/newrome/src/benchmarking/{settmint_manager.rs => setmint_manager.rs} (99%) rename runtime/newrome/src/weights/{settmint_manager.rs => setmint_manager.rs} (93%) rename runtime/setheum/src/weights/{settmint_manager.rs => setmint_manager.rs} (91%) diff --git a/Cargo.lock b/Cargo.lock index f31876e56..1711e7ff0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4413,9 +4413,9 @@ dependencies = [ "setheum-renvm-bridge", "setheum-support", "setheum-transaction-payment", - "settmint-engine", - "settmint-gateway", - "settmint-manager", + "setmint-engine", + "setmint-gateway", + "setmint-manager", "smallvec 1.6.1", "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", @@ -8134,9 +8134,9 @@ dependencies = [ "setheum-renvm-bridge", "setheum-support", "setheum-transaction-payment", - "settmint-engine", - "settmint-gateway", - "settmint-manager", + "setmint-engine", + "setmint-gateway", + "setmint-manager", "smallvec 1.6.1", "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", @@ -8256,7 +8256,7 @@ dependencies = [ ] [[package]] -name = "settmint-engine" +name = "setmint-engine" version = "0.9.0" dependencies = [ "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", @@ -8272,7 +8272,7 @@ dependencies = [ "setheum-dex", "setheum-primitives", "setheum-support", - "settmint-manager", + "setmint-manager", "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", @@ -8281,7 +8281,7 @@ dependencies = [ ] [[package]] -name = "settmint-gateway" +name = "setmint-gateway" version = "0.9.0" dependencies = [ "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", @@ -8296,8 +8296,8 @@ dependencies = [ "setheum-dex", "setheum-primitives", "setheum-support", - "settmint-engine", - "settmint-manager", + "setmint-engine", + "setmint-manager", "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", @@ -8305,7 +8305,7 @@ dependencies = [ ] [[package]] -name = "settmint-manager" +name = "setmint-manager" version = "0.9.0" dependencies = [ "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", diff --git a/Cargo.toml b/Cargo.toml index e6b5f21fd..5c88f5ea1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ members = [ "lib-serml/example", "lib-serml/serp/serp-prices", "lib-serml/serp/serp-treasury", - "lib-serml/settmint/*", + "lib-serml/setmint/*", "lib-serml/support", "lib-serml/tokens/*", "lib-serml/transaction-payment", diff --git a/README.md b/README.md index 940adde76..88b6af929 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Setheum's Blockchain Network node Implementation in Rust, Substrate FRAME and Se # Introduction -Setheum is founded and initiated and fascilitated by Muhammad-Jibril B.A. who founded Setheum Labs, Setheum Foundation to steward and support the development and advancement of the Network, its ecosystem and its community to foster the development and adoption of decentralised finance by building and supporting cross-chain open finance infrastructure such as the SERP (Setheum Elastic Reserve Protocol) stablecoin system, the SettMint stablecoin minting system and Setheum's built-in payment system SettPay that lets traders and transactors claim cashback (what we call CashDrop) on their transactions to speak of a few. +Setheum is founded and initiated and fascilitated by Muhammad-Jibril B.A. who founded Setheum Labs, Setheum Foundation to steward and support the development and advancement of the Network, its ecosystem and its community to foster the development and adoption of decentralised finance by building and supporting cross-chain open finance infrastructure such as the SERP (Setheum Elastic Reserve Protocol) stablecoin system, the SetMint stablecoin minting system and Setheum's built-in payment system SettPay that lets traders and transactors claim cashback (what we call CashDrop) on their transactions to speak of a few. Setheum also deploys Advanced Incentivization mechanisms and economic models modeled under the Jurisdiction of Islamic Finance. Setheum deploys a Multi-Cameral DECENTRALISED GOVERNANCE SYSTEM. @@ -48,7 +48,7 @@ DRAM("Setheum Dirham", 12) = 1, // Staking Reward and Governance Token - System SETSAR("SetRiyal", 12) = 7, ``` -1. The Setter - The Setter is a basket currency pegged to the Top 10 Strongest and most valuable currencies. It serves as the medium of Exchange and the Defacto stablecoin of the Setheum Ecosystem. All other Setheum system stablecoins orbit around the Setter (SETR) and the SettMint for minting Setheum Currencies (system stablecoins) accepts only the Setter as the Minting Reserve Asset. Only with the Setter (SETR) can a user participate in the DNAR Auctions to stabilize the price of the Setter, while the Setter is Auctioned to stabilize the price of all the other SettCurrencies (system stablecoins). It's the star that brightens many planets - 10 to be exact +1. The Setter - The Setter is a basket currency pegged to the Top 10 Strongest and most valuable currencies. It serves as the medium of Exchange and the Defacto stablecoin of the Setheum Ecosystem. All other Setheum system stablecoins orbit around the Setter (SETR) and the SetMint for minting Setheum Currencies (system stablecoins) accepts only the Setter as the Minting Reserve Asset. Only with the Setter (SETR) can a user participate in the DNAR Auctions to stabilize the price of the Setter, while the Setter is Auctioned to stabilize the price of all the other SettCurrencies (system stablecoins). It's the star that brightens many planets - 10 to be exact 2. [The SERP](./lib-serp) - The SERP (Setheum Elastic Reserve Protocol) is algorithmically responsible for stabilizing the prices of the Setheum Stable Currencies. No human interferrance is needed for this, it's all algorithmically handled by the SERP. The SERP is the backbone of Setheum, it is based on my TES (Token Elasticity of Supply) algorithm based on PES (Price Elasticity of Supply) such that the demand curve or price of a currency determines the supply serping point, meaning the supply curve of a SetCurrency will be adjusted according to the demand curve of that specific SetCurrency. The result will be burning or minting an amount equivalent to the serping point produced by the SERP-TES, the burning amount will be bought back by the SERP automatically through the built-in-DEX and the bought amount will be burnt to meet the satisfaction of the demand curve to prop the price back up to its peg, the opposite is done to lower the price of an under-supplied currency that is on demand and above its peg on the demand curve, for this the mint amount is divided into receipients including the SettPayTreasury where CashDrops are deposited for users to claim, the System Treasury under Governance, the Charity Fund stewarded by the Setheum Foundation, and the WelfareTreasury, more on the Welfare Treasury below. @@ -57,8 +57,8 @@ In The SERP and Setheum lingua, I coined these terms: * serpup: to increase the supply of a Setheum stablecurrency at its serping point. * serpdown: to decrease the supply of a Setheum stablecurrency at its serping point. -3. [The SettMint](./lib-serml/settmint) - The Settmint is partly inspired by the Maker Protocol (MakerDAO), except that SettMint is on a very different principle of Setheum that ought not to be violated. -SettMint is not a CDP but quite similar, as users can hold, authorize & transfer positions, users can reserve the Setter (SETR) to mint any SetCurrency of their choice without the need for over-collateralization, debt, interest rates, liquidation, or even stability fees. The stability of the Currencies is handles by the SERP, and the the Setter used as the reserve currency is also a SetCurrency (Setheum System Stablecoin) therefore eliminating position volatility and the risk of liquidation as all risk parameters have been eliminated with the Setter and Setheum's strong principle on the matters of the SettMint and Setheum's Monetary Policy. +3. [The SetMint](./lib-serml/setmint) - The Settmint is partly inspired by the Maker Protocol (MakerDAO), except that SetMint is on a very different principle of Setheum that ought not to be violated. +SetMint is not a CDP but quite similar, as users can hold, authorize & transfer positions, users can reserve the Setter (SETR) to mint any SetCurrency of their choice without the need for over-collateralization, debt, interest rates, liquidation, or even stability fees. The stability of the Currencies is handles by the SERP, and the the Setter used as the reserve currency is also a SetCurrency (Setheum System Stablecoin) therefore eliminating position volatility and the risk of liquidation as all risk parameters have been eliminated with the Setter and Setheum's strong principle on the matters of the SetMint and Setheum's Monetary Policy. This is one of the reasons I see Setheum as one of the most Sophisticated Advanced Economic Systems yet so simple, easy to use and understand, and even easier to get started. 4. The SettPay - The SettPay is responsible for the CashDrops that are dispatched by the SERP to the claimants (transactors that claim cashdrops). It is under the governance of the "Financial Council". They decide how much percent claimants get based on how much they spent, these params are custom and governable for every Setheum System currency including the DNAR. For example, DNAR spenders get 2.58% cashdrop per claimed transaction if their spent amount is >= 10000 dollars, else if their spent amount is < 10000 dollars && >= 100 then they get 4% cashdrop, else if their spent amount is < 100 then they get 5% cashdrop. The Welfare Council can update these parameters by governance proposals and voting without the need for forking or even a runtime upgrade. diff --git a/lib-serml/settmint/settmint-engine/Cargo.toml b/lib-serml/setmint/setmint-engine/Cargo.toml similarity index 93% rename from lib-serml/settmint/settmint-engine/Cargo.toml rename to lib-serml/setmint/setmint-engine/Cargo.toml index 280cbfd9a..ccb4dd2a3 100644 --- a/lib-serml/settmint/settmint-engine/Cargo.toml +++ b/lib-serml/setmint/setmint-engine/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "settmint-engine" +name = "setmint-engine" version = "0.9.0" authors = ["Setheum Labs"] edition = "2018" @@ -24,7 +24,7 @@ orml-utilities = { path = "../../../lib-openrml/utilities", default-features = f # local dependencies support = { package = "setheum-support", path = "../../support", default-features = false } -settmint = { package = "settmint-manager", path = "../settmint-manager", default-features = false } +setmint = { package = "setmint-manager", path = "../setmint-manager", default-features = false } primitives = { package = "setheum-primitives", path = "../../../primitives", default-features = false } [dev-dependencies] @@ -48,7 +48,7 @@ std = [ "sp-runtime/std", "sp-std/std", "support/std", - "settmint/std", + "setmint/std", "primitives/std", "orml-utilities/std", ] diff --git a/lib-serml/settmint/settmint-engine/src/lib.rs b/lib-serml/setmint/setmint-engine/src/lib.rs similarity index 96% rename from lib-serml/settmint/settmint-engine/src/lib.rs rename to lib-serml/setmint/setmint-engine/src/lib.rs index bcac3bdad..90769ca2d 100644 --- a/lib-serml/settmint/settmint-engine/src/lib.rs +++ b/lib-serml/setmint/setmint-engine/src/lib.rs @@ -48,14 +48,14 @@ mod tests; pub use standard_exchange_rate_convertor::StandardExchangeRateConvertor; pub use module::*; -pub type SettmintOf = settmint::Pallet; +pub type SettmintOf = setmint::Pallet; #[frame_support::pallet] pub mod module { use super::*; #[pallet::config] - pub trait Config: frame_system::Config + settmint::Config + SendTransactionTypes> { + pub trait Config: frame_system::Config + setmint::Config + SendTransactionTypes> { type Event: From> + IsType<::Event>; /// The list of valid standard currency types diff --git a/lib-serml/settmint/settmint-engine/src/mock.rs b/lib-serml/setmint/setmint-engine/src/mock.rs similarity index 97% rename from lib-serml/settmint/settmint-engine/src/mock.rs rename to lib-serml/setmint/setmint-engine/src/mock.rs index 321179f85..f9723735d 100644 --- a/lib-serml/settmint/settmint-engine/src/mock.rs +++ b/lib-serml/setmint/setmint-engine/src/mock.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! Mocks for the settmint engine module. +//! Mocks for the setmint engine module. #![cfg(test)] @@ -55,7 +55,7 @@ pub const SETCHF: CurrencyId = CurrencyId::Token(TokenSymbol::SETCHF); pub const SETSAR: CurrencyId = CurrencyId::Token(TokenSymbol::SETSAR); -mod settmint_engine { +mod setmint_engine { pub use super::super::*; } @@ -141,7 +141,7 @@ parameter_types! { pub const SettmintManagerPalletId: PalletId = PalletId(*b"set/mint"); } -impl settmint::Config for Runtime { +impl setmint::Config for Runtime { type Event = Event; type Convert = StandardExchangeRateConvertor; type Currency = Currencies; @@ -328,11 +328,11 @@ construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Storage, Config, Event}, - SettmintEngineModule: settmint_engine::{Pallet, Storage, Call, Event}, + SettmintEngineModule: setmint_engine::{Pallet, Storage, Call, Event}, SerpTreasuryModule: serp_treasury::{Pallet, Storage, Event}, Currencies: orml_currencies::{Pallet, Call, Event}, Tokens: orml_tokens::{Pallet, Storage, Event, Config}, - SettmintManagerModule: settmint::{Pallet, Storage, Call, Event}, + SettmintManagerModule: setmint::{Pallet, Storage, Call, Event}, PalletBalances: pallet_balances::{Pallet, Call, Storage, Event}, SetheumDEX: setheum_dex::{Pallet, Storage, Call, Event, Config}, } diff --git a/lib-serml/settmint/settmint-engine/src/standard_exchange_rate_convertor.rs b/lib-serml/setmint/setmint-engine/src/standard_exchange_rate_convertor.rs similarity index 100% rename from lib-serml/settmint/settmint-engine/src/standard_exchange_rate_convertor.rs rename to lib-serml/setmint/setmint-engine/src/standard_exchange_rate_convertor.rs diff --git a/lib-serml/settmint/settmint-engine/src/tests.rs b/lib-serml/setmint/setmint-engine/src/tests.rs similarity index 98% rename from lib-serml/settmint/settmint-engine/src/tests.rs rename to lib-serml/setmint/setmint-engine/src/tests.rs index 57047d30e..e820219a4 100644 --- a/lib-serml/settmint/settmint-engine/src/tests.rs +++ b/lib-serml/setmint/setmint-engine/src/tests.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! Unit tests for the settmint engine module. +//! Unit tests for the setmint engine module. #![cfg(test)] diff --git a/lib-serml/settmint/settmint-gateway/Cargo.toml b/lib-serml/setmint/setmint-gateway/Cargo.toml similarity index 86% rename from lib-serml/settmint/settmint-gateway/Cargo.toml rename to lib-serml/setmint/setmint-gateway/Cargo.toml index eb7f57b95..892bc1153 100644 --- a/lib-serml/settmint/settmint-gateway/Cargo.toml +++ b/lib-serml/setmint/setmint-gateway/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "settmint-gateway" +name = "setmint-gateway" version = "0.9.0" authors = ["Setheum Labs"] edition = "2018" @@ -19,8 +19,8 @@ sp-std = { default-features = false, git = "https://github.com/paritytech/substr orml-tokens = { path = "../../../lib-openrml/tokens", default-features = false } # local dependencies -settmint-engine = { package = "settmint-engine", path = "../settmint-engine", default-features = false } -settmint-manager= { package = "settmint-manager", path = "../settmint-manager", default-features = false } +setmint-engine = { package = "setmint-engine", path = "../setmint-engine", default-features = false } +setmint-manager= { package = "setmint-manager", path = "../setmint-manager", default-features = false } support = { package = "setheum-support", path = "../../support", default-features = false } primitives = { package = "setheum-primitives", path = "../../../primitives", default-features = false } @@ -43,8 +43,8 @@ std = [ "frame-system/std", "sp-std/std", "orml-tokens/std", - "settmint-manager/std", - "settmint-engine/std", + "setmint-manager/std", + "setmint-engine/std", "support/std", "primitives/std", ] diff --git a/lib-serml/settmint/settmint-gateway/src/lib.rs b/lib-serml/setmint/setmint-gateway/src/lib.rs similarity index 95% rename from lib-serml/settmint/settmint-gateway/src/lib.rs rename to lib-serml/setmint/setmint-gateway/src/lib.rs index edccc61d9..9375442b5 100644 --- a/lib-serml/settmint/settmint-gateway/src/lib.rs +++ b/lib-serml/setmint/setmint-gateway/src/lib.rs @@ -46,10 +46,10 @@ pub use weights::WeightInfo; pub mod module { use super::*; - pub const RESERVE_ID: ReserveIdentifier = ReserveIdentifier::SettMint; + pub const RESERVE_ID: ReserveIdentifier = ReserveIdentifier::SetMint; #[pallet::config] - pub trait Config: frame_system::Config + settmint_engine::Config { + pub trait Config: frame_system::Config + setmint_engine::Config { type Event: From> + IsType<::Event>; /// Currency for authorization reserved. @@ -131,7 +131,7 @@ pub mod module { standard_adjustment: Amount, ) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; - >::adjust_position(&who, currency_id, reserve_adjustment, standard_adjustment)?; + >::adjust_position(&who, currency_id, reserve_adjustment, standard_adjustment)?; Ok(().into()) } @@ -151,7 +151,7 @@ pub mod module { let to = ensure_signed(origin)?; let from = T::Lookup::lookup(from)?; Self::check_authorization(&from, &to, currency_id)?; - >::transfer_position(&from, &to, currency_id)?; + >::transfer_position(&from, &to, currency_id)?; Ok(().into()) } @@ -205,7 +205,7 @@ pub mod module { } /// Cancel all authorization of caller - #[pallet::weight(::WeightInfo::unauthorize_all(::StandardCurrencies::get().len() as u32))] + #[pallet::weight(::WeightInfo::unauthorize_all(::StandardCurrencies::get().len() as u32))] #[transactional] pub fn unauthorize_all(origin: OriginFor) -> DispatchResultWithPostInfo { let from = ensure_signed(origin)?; diff --git a/lib-serml/settmint/settmint-gateway/src/mock.rs b/lib-serml/setmint/setmint-gateway/src/mock.rs similarity index 96% rename from lib-serml/settmint/settmint-gateway/src/mock.rs rename to lib-serml/setmint/setmint-gateway/src/mock.rs index 541dff49d..347fca055 100644 --- a/lib-serml/settmint/settmint-gateway/src/mock.rs +++ b/lib-serml/setmint/setmint-gateway/src/mock.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! Mocks for the settmint_gateway module. +//! Mocks for the setmint_gateway module. #![cfg(test)] @@ -32,7 +32,7 @@ use sp_runtime::{ }; use support::{ExchangeRate, Price, PriceProvider, Ratio}; -mod settmint_gateway { +mod setmint_gateway { pub use super::super::*; } @@ -285,7 +285,7 @@ parameter_types! { pub const MinimumStandardValue: Balance = 2; } -impl settmint_engine::Config for Runtime { +impl setmint_engine::Config for Runtime { type Event = Event; type StandardCurrencies = StandardCurrencyIds; type DefaultStandardExchangeRate = DefaultStandardExchangeRate; @@ -297,9 +297,9 @@ parameter_types! { pub const SettmintManagerPalletId: PalletId = PalletId(*b"set/mint"); } -impl settmint_manager::Config for Runtime { +impl setmint_manager::Config for Runtime { type Event = Event; - type Convert = settmint_engine::StandardExchangeRateConvertor; + type Convert = setmint_engine::StandardExchangeRateConvertor; type Currency = Tokens; type StandardCurrencyIds = StandardCurrencyIds; type GetReserveCurrencyId = GetReserveCurrencyId; @@ -328,13 +328,13 @@ construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Storage, Config, Event}, - SettmintGateway: settmint_gateway::{Pallet, Storage, Call, Event}, + SettmintGateway: setmint_gateway::{Pallet, Storage, Call, Event}, Tokens: orml_tokens::{Pallet, Storage, Event, Config}, PalletBalances: pallet_balances::{Pallet, Call, Storage, Event}, Currencies: orml_currencies::{Pallet, Call, Event}, - SettmintManagerModule: settmint_manager::{Pallet, Storage, Call, Event}, + SettmintManagerModule: setmint_manager::{Pallet, Storage, Call, Event}, SerpTreasuryModule: serp_treasury::{Pallet, Storage, Event}, - SettmintEngineModule: settmint_engine::{Pallet, Storage, Call, Event}, + SettmintEngineModule: setmint_engine::{Pallet, Storage, Call, Event}, SetheumDEX: setheum_dex::{Pallet, Storage, Call, Event, Config}, } ); diff --git a/lib-serml/settmint/settmint-gateway/src/tests.rs b/lib-serml/setmint/setmint-gateway/src/tests.rs similarity index 100% rename from lib-serml/settmint/settmint-gateway/src/tests.rs rename to lib-serml/setmint/setmint-gateway/src/tests.rs diff --git a/lib-serml/settmint/settmint-gateway/src/weights.rs b/lib-serml/setmint/setmint-gateway/src/weights.rs similarity index 90% rename from lib-serml/settmint/settmint-gateway/src/weights.rs rename to lib-serml/setmint/setmint-gateway/src/weights.rs index c764c3c93..4fe5bb7f0 100644 --- a/lib-serml/settmint/settmint-gateway/src/weights.rs +++ b/lib-serml/setmint/setmint-gateway/src/weights.rs @@ -17,7 +17,7 @@ // along with this program. If not, see . -//! Autogenerated weights for settmint_gateway +//! Autogenerated weights for setmint_gateway //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 //! DATE: 2021-02-26, STEPS: [50, ], REPEAT: 20, LOW RANGE: [], HIGH RANGE: [] @@ -28,12 +28,12 @@ // --chain=dev // --steps=50 // --repeat=20 -// --pallet=settmint_gateway +// --pallet=setmint_gateway // --extrinsic=* // --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --output=./lib-serml/settmint-gateway/src/weights.rs +// --output=./lib-serml/setmint-gateway/src/weights.rs // --template=./templates/setheum-weight-template.hbs @@ -45,7 +45,7 @@ use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; use sp_std::marker::PhantomData; -/// Weight functions needed for settmint_gateway. +/// Weight functions needed for setmint_gateway. pub trait WeightInfo { fn authorize() -> Weight; fn unauthorize() -> Weight; @@ -54,7 +54,7 @@ pub trait WeightInfo { fn transfer_position_from() -> Weight; } -/// Weights for settmint_gateway using the Setheum node and recommended hardware. +/// Weights for setmint_gateway using the Setheum node and recommended hardware. pub struct SetheumWeight(PhantomData); impl WeightInfo for SetheumWeight { fn authorize() -> Weight { diff --git a/lib-serml/settmint/settmint-manager/Cargo.toml b/lib-serml/setmint/setmint-manager/Cargo.toml similarity index 98% rename from lib-serml/settmint/settmint-manager/Cargo.toml rename to lib-serml/setmint/setmint-manager/Cargo.toml index b9f2b8c44..d7fd28f62 100644 --- a/lib-serml/settmint/settmint-manager/Cargo.toml +++ b/lib-serml/setmint/setmint-manager/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "settmint-manager" +name = "setmint-manager" version = "0.9.0" authors = ["Setheum Labs"] edition = "2018" diff --git a/lib-serml/settmint/settmint-manager/src/lib.rs b/lib-serml/setmint/setmint-manager/src/lib.rs similarity index 99% rename from lib-serml/settmint/settmint-manager/src/lib.rs rename to lib-serml/setmint/setmint-manager/src/lib.rs index 04ff03448..faa6a3cf8 100644 --- a/lib-serml/settmint/settmint-manager/src/lib.rs +++ b/lib-serml/setmint/setmint-manager/src/lib.rs @@ -41,7 +41,7 @@ mod tests; pub use module::*; -/// A settmint standard position. +/// A setmint standard position. #[derive(Encode, Decode, Eq, PartialEq, Copy, Clone, RuntimeDebug, Default, MaxEncodedLen)] pub struct Position { /// The amount of reserve. @@ -63,7 +63,7 @@ pub mod module { type Convert: Convert<(CurrencyId, Balance), Balance>; /// Currency type for deposit/withdraw reserve assets - /// to/from settmint-manager module + /// to/from setmint-manager module type Currency: MultiCurrencyExtended< Self::AccountId, CurrencyId = CurrencyId, diff --git a/lib-serml/settmint/settmint-manager/src/mock.rs b/lib-serml/setmint/setmint-manager/src/mock.rs similarity index 98% rename from lib-serml/settmint/settmint-manager/src/mock.rs rename to lib-serml/setmint/setmint-manager/src/mock.rs index 123a9a392..fba221408 100644 --- a/lib-serml/settmint/settmint-manager/src/mock.rs +++ b/lib-serml/setmint/setmint-manager/src/mock.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! Mocks for the settmint-manager module. +//! Mocks for the setmint-manager module. #![cfg(test)] @@ -54,7 +54,7 @@ pub const SETCHF: CurrencyId = CurrencyId::Token(TokenSymbol::SETCHF); pub const SETSAR: CurrencyId = CurrencyId::Token(TokenSymbol::SETSAR); -mod settmint_manager { +mod setmint_manager { pub use super::super::*; } @@ -319,7 +319,7 @@ construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Storage, Config, Event}, - SettmintManagerModule: settmint_manager::{Pallet, Storage, Call, Event}, + SettmintManagerModule: setmint_manager::{Pallet, Storage, Call, Event}, Tokens: orml_tokens::{Pallet, Storage, Event, Config}, PalletBalances: pallet_balances::{Pallet, Call, Storage, Event}, Currencies: orml_currencies::{Pallet, Call, Event}, diff --git a/lib-serml/settmint/settmint-manager/src/tests.rs b/lib-serml/setmint/setmint-manager/src/tests.rs similarity index 99% rename from lib-serml/settmint/settmint-manager/src/tests.rs rename to lib-serml/setmint/setmint-manager/src/tests.rs index beb579e7d..b23ebfdcc 100644 --- a/lib-serml/settmint/settmint-manager/src/tests.rs +++ b/lib-serml/setmint/setmint-manager/src/tests.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! Unit tests for the settmint-manager module. +//! Unit tests for the setmint-manager module. #![cfg(test)] diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs index 6def7d58f..cd9c6717d 100644 --- a/primitives/src/lib.rs +++ b/primitives/src/lib.rs @@ -165,7 +165,7 @@ impl Decode for TradingPair { pub enum ReserveIdentifier { EvmStorageDeposit, EvmDeveloperDeposit, - SettMint, + SetMint, Nft, TransactionPayment, diff --git a/runtime/newrome/Cargo.toml b/runtime/newrome/Cargo.toml index 4e4b4089d..634a1c3c5 100644 --- a/runtime/newrome/Cargo.toml +++ b/runtime/newrome/Cargo.toml @@ -88,10 +88,10 @@ setheum-evm-rpc-runtime-api = { path = "../../lib-serml/evm/evm/rpc/runtime_api" # - serp serp-prices = { path = "../../lib-serml/serp/serp-prices", default-features = false } serp-treasury = { path = "../../lib-serml/serp/serp-treasury", default-features = false } -# - settmint -settmint-engine = { path = "../../lib-serml/settmint/settmint-engine", default-features = false } -settmint-gateway = { path = "../../lib-serml/settmint/settmint-gateway", default-features = false } -settmint-manager = { path = "../../lib-serml/settmint/settmint-manager", default-features = false } +# - setmint +setmint-engine = { path = "../../lib-serml/setmint/setmint-engine", default-features = false } +setmint-gateway = { path = "../../lib-serml/setmint/setmint-gateway", default-features = false } +setmint-manager = { path = "../../lib-serml/setmint/setmint-manager", default-features = false } # - support setheum-support = { path = "../../lib-serml/support", default-features = false } # - tokens @@ -174,9 +174,9 @@ std = [ "setheum-evm-manager/std", "serp-prices/std", "serp-treasury/std", - "settmint-engine/std", - "settmint-gateway/std", - "settmint-manager/std", + "setmint-engine/std", + "setmint-gateway/std", + "setmint-manager/std", "setheum-support/std", "setheum-currencies/std", "setheum-nft/std", @@ -254,9 +254,9 @@ try-runtime = [ "setheum-evm-manager/try-runtime", "serp-prices/try-runtime", "serp-treasury/try-runtime", - "settmint-engine/try-runtime", - "settmint-gateway/try-runtime", - "settmint-manager/try-runtime", + "setmint-engine/try-runtime", + "setmint-gateway/try-runtime", + "setmint-manager/try-runtime", "setheum-currencies/try-runtime", "setheum-nft/try-runtime", "setheum-transaction-payment/try-runtime", diff --git a/runtime/newrome/src/benchmarking/mod.rs b/runtime/newrome/src/benchmarking/mod.rs index b9496427e..7afd59960 100644 --- a/runtime/newrome/src/benchmarking/mod.rs +++ b/runtime/newrome/src/benchmarking/mod.rs @@ -20,7 +20,7 @@ // module benchmarking (SERML) pub mod dex; -pub mod settmint_gateway; +pub mod setmint_gateway; pub mod prices; pub mod transaction_payment; diff --git a/runtime/newrome/src/benchmarking/settmint_manager.rs b/runtime/newrome/src/benchmarking/setmint_manager.rs similarity index 99% rename from runtime/newrome/src/benchmarking/settmint_manager.rs rename to runtime/newrome/src/benchmarking/setmint_manager.rs index 1b1d55667..593b90b21 100644 --- a/runtime/newrome/src/benchmarking/settmint_manager.rs +++ b/runtime/newrome/src/benchmarking/setmint_manager.rs @@ -36,7 +36,7 @@ use sp_std::prelude::*; const SEED: u32 = 0; runtime_benchmarks! { - { Runtime, settmint_gateway } + { Runtime, setmint_gateway } _ {} diff --git a/runtime/newrome/src/lib.rs b/runtime/newrome/src/lib.rs index d5bcaa199..8ebed3114 100644 --- a/runtime/newrome/src/lib.rs +++ b/runtime/newrome/src/lib.rs @@ -958,9 +958,9 @@ parameter_types! { ]; pub const GetReserveCurrencyId: CurrencyId = SETR; } -impl settmint_manager::Config for Runtime { +impl setmint_manager::Config for Runtime { type Event = Event; - type Convert = settmint_engine::StandardExchangeRateConvertor; + type Convert = setmint_engine::StandardExchangeRateConvertor; type Currency = Currencies; type StandardCurrencyIds = StandardCurrencyIds; type GetReserveCurrencyId = GetReserveCurrencyId; @@ -1033,7 +1033,7 @@ parameter_types! { pub MinimumStandardValue: Balance = dollar(SETR); } -impl settmint_engine::Config for Runtime { +impl setmint_engine::Config for Runtime { type Event = Event; type StandardCurrencyIds = StandardCurrencyIds; type DefaultStandardExchangeRate = DefaultStandardExchangeRate; @@ -1045,11 +1045,11 @@ parameter_types! { pub DepositPerAuthorization: Balance = deposit(1, 64); } -impl settmint_gateway::Config for Runtime { +impl setmint_gateway::Config for Runtime { type Event = Event; type Currency = Balances; type DepositPerAuthorization = DepositPerAuthorization; - type WeightInfo = weights::settmint_gateway::WeightInfo; + type WeightInfo = weights::setmint_gateway::WeightInfo; } parameter_types! { @@ -1547,9 +1547,9 @@ construct_runtime!( Dex: setheum_dex::{Pallet, Storage, Call, Event, Config} = 40, // Settmint - SettmintEngine: settmint_engine::{Pallet, Storage, Call, Event, Config, ValidateUnsigned} = 41, - SettmintGateway: settmint_gateway::{Pallet, Storage, Call, Event} = 42, - SettmintManager: settmint_manager::{Pallet, Storage, Call, Event} = 43, + SettmintEngine: setmint_engine::{Pallet, Storage, Call, Event, Config, ValidateUnsigned} = 41, + SettmintGateway: setmint_gateway::{Pallet, Storage, Call, Event} = 42, + SettmintManager: setmint_manager::{Pallet, Storage, Call, Event} = 43, // Smart contracts // Setheum EVM (SEVM) @@ -1899,7 +1899,7 @@ impl_runtime_apis! { orml_add_benchmark!(params, batches, setheum_evm, benchmarking::evm); orml_add_benchmark!(params, batches, orml_oracle, benchmarking::oracle); orml_add_benchmark!(params, batches, prices, benchmarking::prices); - orml_add_benchmark!(params, batches, settmint_gateway, benchmarking::settmint_gateway); + orml_add_benchmark!(params, batches, setmint_gateway, benchmarking::setmint_gateway); orml_add_benchmark!(params, batches, orml_tokens, benchmarking::tokens); orml_add_benchmark!(params, batches, transaction_payment, benchmarking::transaction_payment); orml_add_benchmark!(params, batches, orml_vesting, benchmarking::vesting); diff --git a/runtime/newrome/src/weights/mod.rs b/runtime/newrome/src/weights/mod.rs index 52eef4c19..e19eab31e 100644 --- a/runtime/newrome/src/weights/mod.rs +++ b/runtime/newrome/src/weights/mod.rs @@ -19,11 +19,11 @@ //! A list of the different weight modules for our runtime. #![allow(clippy::unnecessary_cast)] -pub mod settmint_engine; +pub mod setmint_engine; pub mod serp_treasury; pub mod setheum_currencies; pub mod dex; -pub mod settmint_gateway; +pub mod setmint_gateway; pub mod setheum_nft; pub mod serp_prices; pub mod setheum_transaction_payment; diff --git a/runtime/newrome/src/weights/settmint_manager.rs b/runtime/newrome/src/weights/setmint_manager.rs similarity index 93% rename from runtime/newrome/src/weights/settmint_manager.rs rename to runtime/newrome/src/weights/setmint_manager.rs index c309d52f7..b04cadf57 100644 --- a/runtime/newrome/src/weights/settmint_manager.rs +++ b/runtime/newrome/src/weights/setmint_manager.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! Autogenerated weights for settmint_gateway +//! Autogenerated weights for setmint_gateway //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 //! DATE: 2021-03-01, STEPS: [50, ], REPEAT: 20, LOW RANGE: [], HIGH RANGE: [] @@ -41,9 +41,9 @@ use frame_support::{traits::Get, weights::Weight}; use sp_std::marker::PhantomData; -/// Weight functions for settmint_gateway. +/// Weight functions for setmint_gateway. pub struct WeightInfo(_); -impl settmint_gateway::WeightInfo for WeightInfo { +impl setmint_gateway::WeightInfo for WeightInfo { fn authorize() -> Weight { (25_888_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight)) } diff --git a/runtime/setheum/Cargo.toml b/runtime/setheum/Cargo.toml index ff375e652..d54707acc 100644 --- a/runtime/setheum/Cargo.toml +++ b/runtime/setheum/Cargo.toml @@ -85,10 +85,10 @@ setheum-evm-rpc-runtime-api = { path = "../../lib-serml/evm/evm/rpc/runtime_api" # - serp serp-prices = { path = "../../lib-serml/serp/serp-prices", default-features = false } serp-treasury = { path = "../../lib-serml/serp/serp-treasury", default-features = false } -# - settmint -settmint-engine = { path = "../../lib-serml/settmint/settmint-engine", default-features = false } -settmint-gateway = { path = "../../lib-serml/settmint/settmint-gateway", default-features = false } -settmint-manager = { path = "../../lib-serml/settmint/settmint-manager", default-features = false } +# - setmint +setmint-engine = { path = "../../lib-serml/setmint/setmint-engine", default-features = false } +setmint-gateway = { path = "../../lib-serml/setmint/setmint-gateway", default-features = false } +setmint-manager = { path = "../../lib-serml/setmint/setmint-manager", default-features = false } # - support setheum-support = { path = "../../lib-serml/support", default-features = false } # - tokens @@ -171,9 +171,9 @@ std = [ "setheum-evm-manager/std", "serp-prices/std", "serp-treasury/std", - "settmint-engine/std", - "settmint-gateway/std", - "settmint-manager/std", + "setmint-engine/std", + "setmint-gateway/std", + "setmint-manager/std", "setheum-support/std", "setheum-currencies/std", "setheum-nft/std", @@ -252,9 +252,9 @@ try-runtime = [ "setheum-evm-manager/try-runtime", "serp-prices/try-runtime", "serp-treasury/try-runtime", - "settmint-engine/try-runtime", - "settmint-gateway/try-runtime", - "settmint-manager/try-runtime", + "setmint-engine/try-runtime", + "setmint-gateway/try-runtime", + "setmint-manager/try-runtime", "setheum-currencies/try-runtime", "setheum-nft/try-runtime", "setheum-transaction-payment/try-runtime", diff --git a/runtime/setheum/src/lib.rs b/runtime/setheum/src/lib.rs index 812ffaf9e..179568262 100644 --- a/runtime/setheum/src/lib.rs +++ b/runtime/setheum/src/lib.rs @@ -974,9 +974,9 @@ parameter_types! { ]; pub const GetReserveCurrencyId: CurrencyId = SETR; } -impl settmint_manager::Config for Runtime { +impl setmint_manager::Config for Runtime { type Event = Event; - type Convert = settmint_engine::StandardExchangeRateConvertor; + type Convert = setmint_engine::StandardExchangeRateConvertor; type Currency = Currencies; type StandardCurrencyIds = StandardCurrencyIds; type GetReserveCurrencyId = GetReserveCurrencyId; @@ -1049,7 +1049,7 @@ parameter_types! { pub MinimumStandardValue: Balance = dollar(SETR); } -impl settmint_engine::Config for Runtime { +impl setmint_engine::Config for Runtime { type Event = Event; type StandardCurrencyIds = StandardCurrencyIds; type DefaultStandardExchangeRate = DefaultStandardExchangeRate; @@ -1061,11 +1061,11 @@ parameter_types! { pub DepositPerAuthorization: Balance = deposit(1, 64); } -impl settmint_gateway::Config for Runtime { +impl setmint_gateway::Config for Runtime { type Event = Event; type Currency = Balances; type DepositPerAuthorization = DepositPerAuthorization; - type WeightInfo = weights::settmint_gateway::WeightInfo; + type WeightInfo = weights::setmint_gateway::WeightInfo; } parameter_types! { @@ -1501,9 +1501,9 @@ construct_runtime!( Dex: setheum_dex::{Pallet, Storage, Call, Event, Config} = 40, // Settmint - SettmintEngine: settmint_engine::{Pallet, Storage, Call, Event, Config, ValidateUnsigned} = 41, - SettmintGateway: settmint_gateway::{Pallet, Storage, Call, Event} = 42, - SettmintManager: settmint_manager::{Pallet, Storage, Call, Event} = 43, + SettmintEngine: setmint_engine::{Pallet, Storage, Call, Event, Config, ValidateUnsigned} = 41, + SettmintGateway: setmint_gateway::{Pallet, Storage, Call, Event} = 42, + SettmintManager: setmint_manager::{Pallet, Storage, Call, Event} = 43, // Smart contracts // Setheum EVM (SEVM) @@ -1883,7 +1883,7 @@ impl_runtime_apis! { orml_add_benchmark!(params, batches, setheum_evm, benchmarking::evm); orml_add_benchmark!(params, batches, orml_oracle, benchmarking::oracle); orml_add_benchmark!(params, batches, prices, benchmarking::prices); - orml_add_benchmark!(params, batches, settmint_gateway, benchmarking::settmint_gateway); + orml_add_benchmark!(params, batches, setmint_gateway, benchmarking::setmint_gateway); orml_add_benchmark!(params, batches, orml_tokens, benchmarking::tokens); orml_add_benchmark!(params, batches, transaction_payment, benchmarking::transaction_payment); orml_add_benchmark!(params, batches, orml_vesting, benchmarking::vesting); diff --git a/runtime/setheum/src/weights/mod.rs b/runtime/setheum/src/weights/mod.rs index 52eef4c19..e19eab31e 100644 --- a/runtime/setheum/src/weights/mod.rs +++ b/runtime/setheum/src/weights/mod.rs @@ -19,11 +19,11 @@ //! A list of the different weight modules for our runtime. #![allow(clippy::unnecessary_cast)] -pub mod settmint_engine; +pub mod setmint_engine; pub mod serp_treasury; pub mod setheum_currencies; pub mod dex; -pub mod settmint_gateway; +pub mod setmint_gateway; pub mod setheum_nft; pub mod serp_prices; pub mod setheum_transaction_payment; diff --git a/runtime/setheum/src/weights/settmint_manager.rs b/runtime/setheum/src/weights/setmint_manager.rs similarity index 91% rename from runtime/setheum/src/weights/settmint_manager.rs rename to runtime/setheum/src/weights/setmint_manager.rs index dfaa9af61..e1b3fade9 100644 --- a/runtime/setheum/src/weights/settmint_manager.rs +++ b/runtime/setheum/src/weights/setmint_manager.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! Autogenerated weights for settmint_gateway +//! Autogenerated weights for setmint_gateway //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 3.0.0 //! DATE: 2021-02-26, STEPS: [50, ], REPEAT: 20, LOW RANGE: [], HIGH RANGE: [] @@ -28,7 +28,7 @@ // --chain=dev // --steps=50 // --repeat=20 -// --pallet=settmint_gateway +// --pallet=setmint_gateway // --extrinsic=* // --execution=wasm // --wasm-execution=compiled @@ -41,9 +41,9 @@ use frame_support::{traits::Get, weights::Weight}; use sp_std::marker::PhantomData; -/// Weight functions for settmint_gateway. +/// Weight functions for setmint_gateway. pub struct WeightInfo(_); -impl settmint_gateway::WeightInfo for WeightInfo { +impl setmint_gateway::WeightInfo for WeightInfo { fn authorize() -> Weight { (14_000_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight)) } From a04a7730fcd2a5814482b721fc08076018ce792f Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 11:31:37 +0800 Subject: [PATCH 12/22] Update .gitmodules --- .gitmodules | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitmodules b/.gitmodules index 2a4608737..a2615a5d9 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,6 @@ [submodule "lib-openrml"] path = lib-openrml - url = https://github.com/open-web3-stack/open-runtime-module-library.git + url = https://github.com/Setheum-Foundation/open-runtime-module-library.git [submodule "predeploy-contracts"] path = predeploy-contracts url = https://github.com/Setheum-Labs/predeploy-contracts.git From 3d133d498f1388066ee6ff2b6754ef9f1838ad13 Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 11:33:08 +0800 Subject: [PATCH 13/22] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 88b6af929..d9be8129c 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,7 @@ Install required tools and install git hooks: ```bash ./scripts/init.sh submodule build-full +git submodule update --init --recursive ``` From f893393b5e0570b7ad3c041faa759644a776a970 Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 11:38:07 +0800 Subject: [PATCH 14/22] Update Submodules --- lib-openrml | 2 +- predeploy-contracts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib-openrml b/lib-openrml index 650ef607d..5babe0b71 160000 --- a/lib-openrml +++ b/lib-openrml @@ -1 +1 @@ -Subproject commit 650ef607d023e4537d3f2932baa5e50bc3a349cb +Subproject commit 5babe0b71cf60538ca23d41231f9558816c52ae9 diff --git a/predeploy-contracts b/predeploy-contracts index c8288fd9a..8e9aadbd9 160000 --- a/predeploy-contracts +++ b/predeploy-contracts @@ -1 +1 @@ -Subproject commit c8288fd9a4fec1527b6d41bddfd7a1eecdd67f0b +Subproject commit 8e9aadbd9394edd22028a3b0c530d9c28f901e47 From dd95a37d58c79cd72723ebb5a3617dd48bb55200 Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 11:49:20 +0800 Subject: [PATCH 15/22] rm lib-openrml --- .gitmodules | 3 --- lib-openrml | 1 - 2 files changed, 4 deletions(-) delete mode 160000 lib-openrml diff --git a/.gitmodules b/.gitmodules index a2615a5d9..b5476352a 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,3 @@ -[submodule "lib-openrml"] - path = lib-openrml - url = https://github.com/Setheum-Foundation/open-runtime-module-library.git [submodule "predeploy-contracts"] path = predeploy-contracts url = https://github.com/Setheum-Labs/predeploy-contracts.git diff --git a/lib-openrml b/lib-openrml deleted file mode 160000 index 5babe0b71..000000000 --- a/lib-openrml +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 5babe0b71cf60538ca23d41231f9558816c52ae9 From 7624a2f0eaabafe70fd8ca69fe61d9fe710b40c0 Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 11:52:47 +0800 Subject: [PATCH 16/22] Add lib-open from SetheumFoundation's setheum ORML Support --- .gitmodules | 3 ++ Cargo.toml | 30 ++++++++++---------- README.md | 4 +-- lib-open | 1 + lib-serml/bridges/chainbridge/Cargo.toml | 4 +-- lib-serml/bridges/renvm-bridge/Cargo.toml | 6 ++-- lib-serml/dex/dex/Cargo.toml | 4 +-- lib-serml/evm/evm-accounts/Cargo.toml | 6 ++-- lib-serml/evm/evm-manager/Cargo.toml | 8 +++--- lib-serml/evm/evm/Cargo.toml | 6 ++-- lib-serml/serp/serp-ocw/Cargo.toml | 6 ++-- lib-serml/serp/serp-prices/Cargo.toml | 4 +-- lib-serml/serp/serp-treasury/Cargo.toml | 8 +++--- lib-serml/setmint/setmint-engine/Cargo.toml | 8 +++--- lib-serml/setmint/setmint-gateway/Cargo.toml | 6 ++-- lib-serml/setmint/setmint-manager/Cargo.toml | 6 ++-- lib-serml/tokens/currencies/Cargo.toml | 8 +++--- lib-serml/tokens/nft/Cargo.toml | 6 ++-- lib-serml/transaction-payment/Cargo.toml | 4 +-- node/cli/Cargo.toml | 2 +- node/service/Cargo.toml | 2 +- rpc/Cargo.toml | 2 +- runtime/common/Cargo.toml | 8 +++--- runtime/newrome/Cargo.toml | 18 ++++++------ runtime/setheum/Cargo.toml | 18 ++++++------ 25 files changed, 91 insertions(+), 87 deletions(-) create mode 160000 lib-open diff --git a/.gitmodules b/.gitmodules index b5476352a..f6a248075 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,6 @@ [submodule "predeploy-contracts"] path = predeploy-contracts url = https://github.com/Setheum-Labs/predeploy-contracts.git +[submodule "lib-open"] + path = lib-open + url = https://github.com/Setheum-Foundation/open-runtime-module-library.git diff --git a/Cargo.toml b/Cargo.toml index 5c88f5ea1..14aaea2e8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,21 +25,21 @@ members = [ "runtime/newrome", "runtime/setheum", - "lib-openrml/authority", - "lib-openrml/bencher", - "lib-openrml/benchmarking", - "lib-openrml/currencies", - "lib-openrml/nft", - "lib-openrml/oracle", - "lib-openrml/oracle/rpc", - "lib-openrml/oracle/rpc/runtime-api", - "lib-openrml/rewards", - "lib-openrml/tokens", - "lib-openrml/traits", - "lib-openrml/utilities", - "lib-openrml/vesting", - "lib-openrml/weight-gen", - "lib-openrml/weight-meter", + "lib-open/authority", + "lib-open/bencher", + "lib-open/benchmarking", + "lib-open/currencies", + "lib-open/nft", + "lib-open/oracle", + "lib-open/oracle/rpc", + "lib-open/oracle/rpc/runtime-api", + "lib-open/rewards", + "lib-open/tokens", + "lib-open/traits", + "lib-open/utilities", + "lib-open/vesting", + "lib-open/weight-gen", + "lib-open/weight-meter", ] resolver = "2" diff --git a/README.md b/README.md index d9be8129c..f55c44c0a 100644 --- a/README.md +++ b/README.md @@ -219,8 +219,8 @@ cargo update ### Update ORML ```bash -cd lib-openrml && git checkout master && git pull -git add lib-openrml +cd lib-open && git checkout master && git pull +git add lib-open cargo-update check-all ``` diff --git a/lib-open b/lib-open new file mode 160000 index 000000000..71ca06da9 --- /dev/null +++ b/lib-open @@ -0,0 +1 @@ +Subproject commit 71ca06da91b9ec3f170d16dd1ee38e8f1d0552c6 diff --git a/lib-serml/bridges/chainbridge/Cargo.toml b/lib-serml/bridges/chainbridge/Cargo.toml index b4e1cfd2d..d372dec80 100644 --- a/lib-serml/bridges/chainbridge/Cargo.toml +++ b/lib-serml/bridges/chainbridge/Cargo.toml @@ -15,7 +15,7 @@ sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot- sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } # orml dependencies -orml-traits = { path = "../../../lib-openrml/traits", default-features = false } +orml-traits = { path = "../../../lib-open/traits", default-features = false } # special dependencies chainbridge = { git = "https://github.com/Slixon-Technologies/chainbridge-substrate", default-features = false } @@ -25,7 +25,7 @@ support = { package = "setheum-support", path = "../../support", default-feature primitives = { package = "setheum-primitives", path = "../../../primitives", default-features = false } [dev-dependencies] -orml-tokens = { path = "../../../lib-openrml/tokens" } +orml-tokens = { path = "../../../lib-open/tokens" } [features] default = ["std"] diff --git a/lib-serml/bridges/renvm-bridge/Cargo.toml b/lib-serml/bridges/renvm-bridge/Cargo.toml index a096b484d..1c9baddd9 100644 --- a/lib-serml/bridges/renvm-bridge/Cargo.toml +++ b/lib-serml/bridges/renvm-bridge/Cargo.toml @@ -18,7 +18,7 @@ sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot- sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } # orml dependencies -orml-traits = { path = "../../../lib-openrml/traits", default-features = false } +orml-traits = { path = "../../../lib-open/traits", default-features = false } # local dependencies support = { package = "setheum-support", path = "../../support", default-features = false } @@ -26,8 +26,8 @@ primitives = { package = "setheum-primitives", path = "../../../primitives", def [dev-dependencies] hex-literal = "0.3.1" -orml-currencies = { path = "../../../lib-openrml/currencies" } -orml-tokens = { path = "../../../lib-openrml/tokens" } +orml-currencies = { path = "../../../lib-open/currencies" } +orml-tokens = { path = "../../../lib-open/tokens" } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } [features] diff --git a/lib-serml/dex/dex/Cargo.toml b/lib-serml/dex/dex/Cargo.toml index 101287773..ba7e41166 100644 --- a/lib-serml/dex/dex/Cargo.toml +++ b/lib-serml/dex/dex/Cargo.toml @@ -19,14 +19,14 @@ frame-system = { git = "https://github.com/paritytech/substrate", branch = "polk sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } # orml dependencies -orml-traits = { path = "../../../lib-openrml/traits", default-features = false } +orml-traits = { path = "../../../lib-open/traits", default-features = false } # local dependencies support = { package = "setheum-support", path = "../../support", default-features = false } primitives = { package = "setheum-primitives", path = "../../../primitives", default-features = false } [dev-dependencies] -orml-tokens = { path = "../../../lib-openrml/tokens" } +orml-tokens = { path = "../../../lib-open/tokens" } sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } diff --git a/lib-serml/evm/evm-accounts/Cargo.toml b/lib-serml/evm/evm-accounts/Cargo.toml index 39539264d..7ea54776e 100644 --- a/lib-serml/evm/evm-accounts/Cargo.toml +++ b/lib-serml/evm/evm-accounts/Cargo.toml @@ -16,15 +16,15 @@ sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0 sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } -orml-traits = { path = "../../../lib-openrml/traits", default-features = false } +orml-traits = { path = "../../../lib-open/traits", default-features = false } primitives = { package = "setheum-primitives", path = "../../../primitives", default-features = false } setheum-support = { package = "setheum-support", path = "../../support", default-features = false } [dev-dependencies] pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -orml-currencies = { path = "../../../lib-openrml/currencies" } -orml-tokens = { path = "../../../lib-openrml/tokens" } +orml-currencies = { path = "../../../lib-open/currencies" } +orml-tokens = { path = "../../../lib-open/tokens" } [features] default = ["std"] diff --git a/lib-serml/evm/evm-manager/Cargo.toml b/lib-serml/evm/evm-manager/Cargo.toml index dbdcaf64f..f56ac1661 100644 --- a/lib-serml/evm/evm-manager/Cargo.toml +++ b/lib-serml/evm/evm-manager/Cargo.toml @@ -21,10 +21,10 @@ setheum-support = { package = "setheum-support", path = "../../support", default [dev-dependencies] pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -orml-currencies = { path = "../../../lib-openrml/currencies" } -orml-tokens = { path = "../../../lib-openrml/tokens" } -orml-traits = { path = "../../../lib-openrml/traits" } -orml-utilities = { path = "../../../lib-openrml/utilities" } +orml-currencies = { path = "../../../lib-open/currencies" } +orml-tokens = { path = "../../../lib-open/tokens" } +orml-traits = { path = "../../../lib-open/traits" } +orml-utilities = { path = "../../../lib-open/utilities" } setheum-evm = { path = "../evm" } setheum-evm-bridge = { path = "../evm-bridge" } diff --git a/lib-serml/evm/evm/Cargo.toml b/lib-serml/evm/evm/Cargo.toml index 1868fd52c..69687d640 100644 --- a/lib-serml/evm/evm/Cargo.toml +++ b/lib-serml/evm/evm/Cargo.toml @@ -30,7 +30,7 @@ sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot- sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } -orml-traits = { path = "../../../lib-openrml/traits", default-features = false } +orml-traits = { path = "../../../lib-open/traits", default-features = false } support = { package = "setheum-support", path = "../../support", default-features = false } primitives = { package = "setheum-primitives", path = "../../../primitives", default-features = false } @@ -38,8 +38,8 @@ primitives = { package = "setheum-primitives", path = "../../../primitives", def [dev-dependencies] env_logger = "0.7" pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -orml-currencies = { path = "../../../lib-openrml/currencies" } -orml-tokens = { path = "../../../lib-openrml/tokens" } +orml-currencies = { path = "../../../lib-open/currencies" } +orml-tokens = { path = "../../../lib-open/tokens" } [features] default = ["std"] diff --git a/lib-serml/serp/serp-ocw/Cargo.toml b/lib-serml/serp/serp-ocw/Cargo.toml index 710620524..4888011e7 100644 --- a/lib-serml/serp/serp-ocw/Cargo.toml +++ b/lib-serml/serp/serp-ocw/Cargo.toml @@ -23,8 +23,8 @@ sp-keystore = { git = 'https://github.com/paritytech/substrate.git', branch = "p sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } # orml dependencies -orml-traits = { path = "../../../lib-openrml/traits", default-features = false } -orml-tokens = { path = "../../../lib-openrml/tokens", default-features = false } +orml-traits = { path = "../../../lib-open/traits", default-features = false } +orml-tokens = { path = "../../../lib-open/tokens", default-features = false } # local dependencies primitives = { package = "setheum-primitives", path = "../../../primitives", default-features = false } @@ -34,7 +34,7 @@ support = { package = "setheum-support", path = "../../support", default-feature sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -orml-currencies = { path = "../../../lib-openrml/currencies" } +orml-currencies = { path = "../../../lib-open/currencies" } serp-treasury = { package = "serp-treasury", path = "../../serp/serp-treasury" } setheum-dex = { path = "../..//dex/dex" } frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } diff --git a/lib-serml/serp/serp-prices/Cargo.toml b/lib-serml/serp/serp-prices/Cargo.toml index d4398bcfc..8d3678ad2 100644 --- a/lib-serml/serp/serp-prices/Cargo.toml +++ b/lib-serml/serp/serp-prices/Cargo.toml @@ -19,7 +19,7 @@ sp-core = { default-features = false, git = "https://github.com/paritytech/subst sp-arithmetic = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } # orml dependencies -orml-traits = { package = "orml-traits", path = "../../../lib-openrml/traits", default-features = false } +orml-traits = { package = "orml-traits", path = "../../../lib-open/traits", default-features = false } # local dependencies support = { package = "setheum-support", path = "../../support", default-features = false } @@ -28,7 +28,7 @@ primitives = { package = "setheum-primitives", path = "../../../primitives", def [dev-dependencies] sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -orml-tokens = { path = "../../../lib-openrml/tokens" } +orml-tokens = { path = "../../../lib-open/tokens" } [features] default = ["std"] diff --git a/lib-serml/serp/serp-treasury/Cargo.toml b/lib-serml/serp/serp-treasury/Cargo.toml index 33680b98b..0a69fa0ad 100644 --- a/lib-serml/serp/serp-treasury/Cargo.toml +++ b/lib-serml/serp/serp-treasury/Cargo.toml @@ -16,8 +16,8 @@ sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot- sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } # orml dependencies -orml-traits = { path = "../../../lib-openrml/traits", default-features = false } -orml-tokens = { path = "../../../lib-openrml/tokens", default-features = false } +orml-traits = { path = "../../../lib-open/traits", default-features = false } +orml-tokens = { path = "../../../lib-open/tokens", default-features = false } # local dependencies prices = { package = "serp-prices", path = "../../serp/serp-prices", default-features = false } @@ -28,9 +28,9 @@ primitives = { package = "setheum-primitives", path = "../../../primitives", def sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -orml-currencies = { path = "../../../lib-openrml/currencies" } +orml-currencies = { path = "../../../lib-open/currencies" } setheum-dex = { path = "../../dex/dex" } -orml-tokens = { path = "../../../lib-openrml/tokens" } +orml-tokens = { path = "../../../lib-open/tokens" } [features] default = ["std"] diff --git a/lib-serml/setmint/setmint-engine/Cargo.toml b/lib-serml/setmint/setmint-engine/Cargo.toml index ccb4dd2a3..3af18361d 100644 --- a/lib-serml/setmint/setmint-engine/Cargo.toml +++ b/lib-serml/setmint/setmint-engine/Cargo.toml @@ -18,9 +18,9 @@ sp-runtime = { default-features = false, git = "https://github.com/paritytech/su sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } # orml dependencies -orml-tokens = { path = "../../../lib-openrml/tokens", default-features = false } -orml-traits = { path = "../../../lib-openrml/traits", default-features = false } -orml-utilities = { path = "../../../lib-openrml/utilities", default-features = false } +orml-tokens = { path = "../../../lib-open/tokens", default-features = false } +orml-traits = { path = "../../../lib-open/traits", default-features = false } +orml-utilities = { path = "../../../lib-open/utilities", default-features = false } # local dependencies support = { package = "setheum-support", path = "../../support", default-features = false } @@ -30,7 +30,7 @@ primitives = { package = "setheum-primitives", path = "../../../primitives", def [dev-dependencies] sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -orml-currencies = { path = "../../../lib-openrml/currencies" } +orml-currencies = { path = "../../../lib-open/currencies" } setheum-dex = { path = "../../dex/dex" } serp-treasury = { package = "serp-treasury", path = "../../serp/serp-treasury" } diff --git a/lib-serml/setmint/setmint-gateway/Cargo.toml b/lib-serml/setmint/setmint-gateway/Cargo.toml index 892bc1153..852b9785a 100644 --- a/lib-serml/setmint/setmint-gateway/Cargo.toml +++ b/lib-serml/setmint/setmint-gateway/Cargo.toml @@ -16,7 +16,7 @@ frame-system = { default-features = false, git = "https://github.com/paritytech/ sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } # orml dependencies -orml-tokens = { path = "../../../lib-openrml/tokens", default-features = false } +orml-tokens = { path = "../../../lib-open/tokens", default-features = false } # local dependencies setmint-engine = { package = "setmint-engine", path = "../setmint-engine", default-features = false } @@ -28,8 +28,8 @@ primitives = { package = "setheum-primitives", path = "../../../primitives", def sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -orml-currencies = { path = "../../../lib-openrml/currencies" } -orml-traits = { path = "../../../lib-openrml/traits" } +orml-currencies = { path = "../../../lib-open/currencies" } +orml-traits = { path = "../../../lib-open/traits" } setheum-dex = { path = "../../dex/dex" } serp-treasury = { package = "serp-treasury", path = "../../serp/serp-treasury" } diff --git a/lib-serml/setmint/setmint-manager/Cargo.toml b/lib-serml/setmint/setmint-manager/Cargo.toml index d7fd28f62..98ae7ec0a 100644 --- a/lib-serml/setmint/setmint-manager/Cargo.toml +++ b/lib-serml/setmint/setmint-manager/Cargo.toml @@ -17,8 +17,8 @@ sp-runtime = { default-features = false, git = "https://github.com/paritytech/su max-encoded-len = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } # orml dependencies -orml-traits = { path = "../../../lib-openrml/traits", default-features = false } -orml-tokens = { path = "../../../lib-openrml/tokens", default-features = false } +orml-traits = { path = "../../../lib-open/traits", default-features = false } +orml-tokens = { path = "../../../lib-open/tokens", default-features = false } # local dependencies primitives = { package = "setheum-primitives", path = "../../../primitives", default-features = false } @@ -28,7 +28,7 @@ support = { package = "setheum-support", path = "../../support", default-feature sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -orml-currencies = { path = "../../../lib-openrml/currencies" } +orml-currencies = { path = "../../../lib-open/currencies" } serp-treasury = { package = "serp-treasury", path = "../../serp/serp-treasury" } setheum-dex = { path = "../..//dex/dex" } frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } diff --git a/lib-serml/tokens/currencies/Cargo.toml b/lib-serml/tokens/currencies/Cargo.toml index eb5b5a83e..a7f74cc4d 100644 --- a/lib-serml/tokens/currencies/Cargo.toml +++ b/lib-serml/tokens/currencies/Cargo.toml @@ -16,8 +16,8 @@ frame-support = { git = "https://github.com/paritytech/substrate", branch = "pol frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } # orml dependencies -orml-traits = { path = "../../../lib-openrml/traits", default-features = false } -orml-utilities = { path = "../../../lib-openrml/utilities", default-features = false } +orml-traits = { path = "../../../lib-open/traits", default-features = false } +orml-utilities = { path = "../../../lib-open/utilities", default-features = false } # local dependencies serp-treasury = { package = "serp-treasury", path = "../../serp/serp-treasury", default-features = false } @@ -28,8 +28,8 @@ support = { package = "setheum-support", path = "../../support", default-feature sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -tokens = { package = "orml-tokens", path = "../../../lib-openrml/tokens" } -orml-currencies = { path = "../../../lib-openrml/currencies" } +tokens = { package = "orml-tokens", path = "../../../lib-open/tokens" } +orml-currencies = { path = "../../../lib-open/currencies" } setheum-evm = { path = "../../evm/evm" } setheum-evm-bridge = { path = "../../evm/evm-bridge" } diff --git a/lib-serml/tokens/nft/Cargo.toml b/lib-serml/tokens/nft/Cargo.toml index 833450de6..c0134646a 100644 --- a/lib-serml/tokens/nft/Cargo.toml +++ b/lib-serml/tokens/nft/Cargo.toml @@ -20,8 +20,8 @@ sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkad sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } # orml dependencies -orml-nft = { path = "../../../lib-openrml/nft", default-features = false } -orml-traits = { path = "../../../lib-openrml/traits", default-features = false } +orml-nft = { path = "../../../lib-open/nft", default-features = false } +orml-traits = { path = "../../../lib-open/traits", default-features = false } # local dependencies primitives = { package = "setheum-primitives", path = "../../../primitives", default-features = false } @@ -31,7 +31,7 @@ sp-core = { default-features = false, git = "https://github.com/paritytech/subst sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-utility = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -orml-tokens = { path = "../../../lib-openrml/tokens" } +orml-tokens = { path = "../../../lib-open/tokens" } support = { package = "setheum-support", path = "../../support" } setheum-currencies = { path = "../../tokens/currencies", default-features = false } diff --git a/lib-serml/transaction-payment/Cargo.toml b/lib-serml/transaction-payment/Cargo.toml index fa853df18..b82910d7a 100644 --- a/lib-serml/transaction-payment/Cargo.toml +++ b/lib-serml/transaction-payment/Cargo.toml @@ -19,7 +19,7 @@ pallet-transaction-payment = { git = "https://github.com/paritytech/substrate", pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } # orml dependencies -orml-traits = { path = "../../lib-openrml/traits", default-features = false } +orml-traits = { path = "../../lib-open/traits", default-features = false } # local dependencies primitives = { package = "setheum-primitives", path = "../../primitives", default-features = false } @@ -28,7 +28,7 @@ support = { package = "setheum-support", path = "../support", default-features = [dev-dependencies] sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } -orml-tokens = { path = "../../lib-openrml/tokens" } +orml-tokens = { path = "../../lib-open/tokens" } setheum-currencies = { path = "../../lib-serml/tokens/currencies" } setheum-dex = { path = "../dex/dex" } smallvec = "1.4.1" diff --git a/node/cli/Cargo.toml b/node/cli/Cargo.toml index 694e91b02..6d3eb65e4 100644 --- a/node/cli/Cargo.toml +++ b/node/cli/Cargo.toml @@ -25,7 +25,7 @@ inspect = { package = "setheum-inspect", path = "../../inspect" } service = { package = "setheum-service", path = "../service", default-features = false, optional = true } [build-dependencies] -orml-build-script-utils = { path = "../../lib-openrml/build-script-utils"} +orml-build-script-utils = { path = "../../lib-open/build-script-utils"} [features] default = [ "wasmtime", "cli" ] diff --git a/node/service/Cargo.toml b/node/service/Cargo.toml index de892e818..23fcacae9 100644 --- a/node/service/Cargo.toml +++ b/node/service/Cargo.toml @@ -57,7 +57,7 @@ sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v sp-keystore = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } # orml dependencies -orml-oracle-rpc = { path = "../../lib-openrml/oracle/rpc" } +orml-oracle-rpc = { path = "../../lib-open/oracle/rpc" } # local dependencies setheum-renvm-bridge = { path = "../../lib-serml/bridges/renvm-bridge" } diff --git a/rpc/Cargo.toml b/rpc/Cargo.toml index 5572d54e8..75434f90a 100644 --- a/rpc/Cargo.toml +++ b/rpc/Cargo.toml @@ -30,7 +30,7 @@ substrate-frame-rpc-system = { git = "https://github.com/paritytech/substrate", pallet-transaction-payment-rpc = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } # orml dependencies -orml-oracle-rpc = { path = "../lib-openrml/oracle/rpc" } +orml-oracle-rpc = { path = "../lib-open/oracle/rpc" } # local dependencies evm-rpc = { path = "../lib-serml/evm/evm/rpc" } diff --git a/runtime/common/Cargo.toml b/runtime/common/Cargo.toml index df9a08686..fa900e0a9 100644 --- a/runtime/common/Cargo.toml +++ b/runtime/common/Cargo.toml @@ -23,8 +23,8 @@ pallet-collective = { git = "https://github.com/paritytech/substrate", branch = pallet-membership = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8", default-features = false } # orml dependencies -orml-oracle = { path = "../../lib-openrml/oracle", default-features = false } -orml-traits = { path = "../../lib-openrml/traits", default-features = false } +orml-oracle = { path = "../../lib-open/oracle", default-features = false } +orml-traits = { path = "../../lib-open/traits", default-features = false } # local dependencies setheum-evm = { path = "../../lib-serml/evm/evm", default-features = false } @@ -43,8 +43,8 @@ pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "p pallet-proxy = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } pallet-utility = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } setheum-service = { path = "../../node/service" } -orml-tokens = { path = "../../lib-openrml/tokens" } -orml-nft = { path = "../../lib-openrml/nft" } +orml-tokens = { path = "../../lib-open/tokens" } +orml-nft = { path = "../../lib-open/nft" } setheum-currencies = { path = "../../lib-serml/tokens/currencies" } setheum-nft = { path = "../../lib-serml/tokens/nft" } setheum-dex = { path = "../../lib-serml/dex/dex" } diff --git a/runtime/newrome/Cargo.toml b/runtime/newrome/Cargo.toml index 634a1c3c5..364106615 100644 --- a/runtime/newrome/Cargo.toml +++ b/runtime/newrome/Cargo.toml @@ -60,15 +60,15 @@ sp-transaction-pool = { default-features = false, git = "https://github.com/pari sp-version = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } # orml dependencies -orml-authority = { path = "../../lib-openrml/authority", default-features = false } -orml-benchmarking = { path = "../../lib-openrml/benchmarking", default-features = false, optional = true } -orml-oracle = { path = "../../lib-openrml/oracle", default-features = false } -orml-oracle-rpc-runtime-api = { path = "../../lib-openrml/oracle/rpc/runtime-api", default-features = false } -orml-tokens = { path = "../../lib-openrml/tokens", default-features = false } -orml-traits = { path = "../../lib-openrml/traits", default-features = false } -orml-vesting = { path = "../../lib-openrml/vesting", default-features = false } -orml-rewards = { path = "../../lib-openrml/rewards", default-features = false } -orml-nft= { path = "../../lib-openrml/nft", default-features = false } +orml-authority = { path = "../../lib-open/authority", default-features = false } +orml-benchmarking = { path = "../../lib-open/benchmarking", default-features = false, optional = true } +orml-oracle = { path = "../../lib-open/oracle", default-features = false } +orml-oracle-rpc-runtime-api = { path = "../../lib-open/oracle/rpc/runtime-api", default-features = false } +orml-tokens = { path = "../../lib-open/tokens", default-features = false } +orml-traits = { path = "../../lib-open/traits", default-features = false } +orml-vesting = { path = "../../lib-open/vesting", default-features = false } +orml-rewards = { path = "../../lib-open/rewards", default-features = false } +orml-nft= { path = "../../lib-open/nft", default-features = false } # local dependencies # - airdrop diff --git a/runtime/setheum/Cargo.toml b/runtime/setheum/Cargo.toml index d54707acc..82951dfb1 100644 --- a/runtime/setheum/Cargo.toml +++ b/runtime/setheum/Cargo.toml @@ -57,15 +57,15 @@ sp-transaction-pool = { default-features = false, git = "https://github.com/pari sp-version = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.8" } # orml dependencies -orml-authority = { path = "../../lib-openrml/authority", default-features = false } -orml-benchmarking = { path = "../../lib-openrml/benchmarking", default-features = false, optional = true } -orml-oracle = { path = "../../lib-openrml/oracle", default-features = false } -orml-oracle-rpc-runtime-api = { path = "../../lib-openrml/oracle/rpc/runtime-api", default-features = false } -orml-tokens = { path = "../../lib-openrml/tokens", default-features = false } -orml-traits = { path = "../../lib-openrml/traits", default-features = false } -orml-vesting = { path = "../../lib-openrml/vesting", default-features = false } -orml-rewards = { path = "../../lib-openrml/rewards", default-features = false } -orml-nft= { path = "../../lib-openrml/nft", default-features = false } +orml-authority = { path = "../../lib-open/authority", default-features = false } +orml-benchmarking = { path = "../../lib-open/benchmarking", default-features = false, optional = true } +orml-oracle = { path = "../../lib-open/oracle", default-features = false } +orml-oracle-rpc-runtime-api = { path = "../../lib-open/oracle/rpc/runtime-api", default-features = false } +orml-tokens = { path = "../../lib-open/tokens", default-features = false } +orml-traits = { path = "../../lib-open/traits", default-features = false } +orml-vesting = { path = "../../lib-open/vesting", default-features = false } +orml-rewards = { path = "../../lib-open/rewards", default-features = false } +orml-nft= { path = "../../lib-open/nft", default-features = false } # local dependencies # - airdrop From 675cbea957353d14a5efde500c6c6dfd73bca756 Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 12:13:31 +0800 Subject: [PATCH 17/22] Update lib.rs --- runtime/common/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/runtime/common/src/lib.rs b/runtime/common/src/lib.rs index 50f0be023..003c0e856 100644 --- a/runtime/common/src/lib.rs +++ b/runtime/common/src/lib.rs @@ -51,9 +51,11 @@ pub use precompile::{ AllPrecompiles, DexPrecompile, MultiCurrencyPrecompile, NFTPrecompile, OraclePrecompile, ScheduleCallPrecompile, StateRentPrecompile, }; -pub use primitives::currency::{ +pub use primitives::{ + currency::{ TokenInfo, DNAR, DRAM, SETR, SETUSD, SETEUR, SETGBP, SETCHF, SETSAR, RENBTC, + }, AccountId, }; From a457dd596f5f017f53a80e17061aeb223a658de3 Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 12:18:34 +0800 Subject: [PATCH 18/22] Update tests.rs --- lib-serml/example/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib-serml/example/src/tests.rs b/lib-serml/example/src/tests.rs index 711ddd9d9..d1f28d417 100644 --- a/lib-serml/example/src/tests.rs +++ b/lib-serml/example/src/tests.rs @@ -29,7 +29,7 @@ fn set_dummy_work() { assert_eq!(Example::dummy(), None); assert_ok!(Example::set_dummy(Origin::root(), 20)); assert_eq!(Example::dummy(), Some(20)); - System::assert_last_event(Event::example(crate::Event::Dummy(20))); + System::assert_last_event(Event::Example(crate::Event::Dummy(20))); }); } From aebf82206c506964fdc349d4adb1e6c7bde98b54 Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 13:06:31 +0800 Subject: [PATCH 19/22] Add Substrate patches --- Cargo.toml | 136 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 136 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 14aaea2e8..bda30185a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -112,3 +112,139 @@ wasmi = { opt-level = 3 } x25519-dalek = { opt-level = 3 } yamux = { opt-level = 3 } zeroize = { opt-level = 3 } + +[patch."https://github.com/paritytech/substrate"] +frame-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +frame-benchmarking-cli = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +frame-election-provider-support = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +frame-executive = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +frame-support = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +frame-support-procedural = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +frame-support-procedural-tools = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +frame-support-procedural-tools-derive = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +frame-system = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +frame-system-rpc-runtime-api = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +frame-try-runtime = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +max-encoded-len = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +max-encoded-len-derive = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-aura = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-authorship = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-babe = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-balances = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-bounties = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-collective = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-democracy = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-election-provider-multi-phase = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-elections-phragmen = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-grandpa = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-identity = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-im-online = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-indices = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-membership = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-mmr = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-mmr-primitives = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-mmr-rpc = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-multisig = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-nicks = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-offences = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-proxy = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-recovery = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-scheduler = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-session = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-society = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-staking = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-staking-reward-curve = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-sudo = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-timestamp = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-tips = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-transaction-payment = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-transaction-payment-rpc = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-treasury = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-utility = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-vesting = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +remote-externalities = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-basic-authorship = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-block-builder = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-chain-spec = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-cli = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-client-api = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-client-db = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-consensus = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-consensus-aura = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-consensus-babe = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-consensus-babe-rpc = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-consensus-epochs = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-consensus-manual-seal = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-consensus-slots = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-executor = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-executor-common = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-executor-wasmtime = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-finality-grandpa = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-finality-grandpa-rpc = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-finality-grandpa-warp-sync = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-informant = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-keystore = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-network = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-network-gossip = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-offchain = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-rpc = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-rpc-api = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-rpc-server = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-service = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-sync-state-rpc = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-telemetry = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-tracing = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-transaction-graph = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-transaction-pool = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-api = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-application-crypto = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-arithmetic = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-block-builder = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-blockchain = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-consensus = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-consensus-aura = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-consensus-babe = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-consensus-slots = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-consensus-vrf = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-core = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-debug-derive = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-externalities = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-finality-grandpa = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-inherents = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-io = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-keystore = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-maybe-compressed-blob = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-npos-elections = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-offchain = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-rpc = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-runtime = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-runtime-interface = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-runtime-interface-proc-macro = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-serializer = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-session = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-staking = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-state-machine = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-std = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-storage = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-timestamp = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-tracing = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-transaction-pool = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-trie = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-utils = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-version = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-wasm-interface = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +substrate-build-script-utils = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +substrate-frame-rpc-system = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +substrate-prometheus-endpoint = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +try-runtime-cli = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +frame-system-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-gilt = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-offences-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-session-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +pallet-staking-reward-fn = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sc-consensus-uncles = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } +sp-authorship = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } From 1b271df6fecc88c5ec85965fb4cac8062e43ff5a Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 13:22:50 +0800 Subject: [PATCH 20/22] remove unused patches --- Cargo.toml | 24 ------------------------ 1 file changed, 24 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index bda30185a..b6bf5e300 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -116,7 +116,6 @@ zeroize = { opt-level = 3 } [patch."https://github.com/paritytech/substrate"] frame-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } frame-benchmarking-cli = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -frame-election-provider-support = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } frame-executive = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } frame-support = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } frame-support-procedural = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } @@ -127,33 +126,21 @@ frame-system-rpc-runtime-api = { git = "https://github.com/paritytech//substrate frame-try-runtime = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } max-encoded-len = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } max-encoded-len-derive = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-aura = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-authorship = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-babe = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-balances = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-bounties = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-collective = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-democracy = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-election-provider-multi-phase = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-elections-phragmen = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-grandpa = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-identity = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-im-online = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-indices = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-membership = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-mmr = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-mmr-primitives = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-mmr-rpc = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-multisig = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-nicks = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-offences = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-proxy = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-recovery = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-scheduler = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-session = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-society = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-staking = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-staking-reward-curve = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-sudo = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-timestamp = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } @@ -163,9 +150,7 @@ pallet-transaction-payment-rpc = { git = "https://github.com/paritytech//substra pallet-transaction-payment-rpc-runtime-api = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-treasury = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } pallet-utility = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-vesting = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } remote-externalities = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -sc-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sc-basic-authorship = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sc-block-builder = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sc-chain-spec = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } @@ -184,7 +169,6 @@ sc-executor-common = { git = "https://github.com/paritytech//substrate", rev = " sc-executor-wasmtime = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sc-finality-grandpa = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sc-finality-grandpa-rpc = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -sc-finality-grandpa-warp-sync = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sc-informant = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sc-keystore = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sc-network = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } @@ -194,7 +178,6 @@ sc-rpc = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cff sc-rpc-api = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sc-rpc-server = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sc-service = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -sc-sync-state-rpc = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sc-telemetry = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sc-tracing = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sc-transaction-graph = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } @@ -202,7 +185,6 @@ sc-transaction-pool = { git = "https://github.com/paritytech//substrate", rev = sp-api = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sp-application-crypto = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sp-arithmetic = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -sp-authority-discovery = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sp-block-builder = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sp-blockchain = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sp-consensus = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } @@ -237,14 +219,8 @@ sp-trie = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cf sp-utils = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sp-version = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sp-wasm-interface = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -substrate-build-script-utils = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } substrate-frame-rpc-system = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } substrate-prometheus-endpoint = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } try-runtime-cli = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -frame-system-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-gilt = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-offences-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-session-benchmarking = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } -pallet-staking-reward-fn = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sc-consensus-uncles = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } sp-authorship = { git = "https://github.com/paritytech//substrate", rev = "74101dc21cfffb4c2d014fcc28edc166d5ca1b16" } From a2cd52b6b2c6421379896e7a25e9f0b1ce3d78ae Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Wed, 1 Sep 2021 14:19:46 +0800 Subject: [PATCH 21/22] Update dex.rs --- runtime/common/src/precompile/dex.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/runtime/common/src/precompile/dex.rs b/runtime/common/src/precompile/dex.rs index a44c6432f..4ddda410c 100644 --- a/runtime/common/src/precompile/dex.rs +++ b/runtime/common/src/precompile/dex.rs @@ -234,7 +234,6 @@ where max_amount_a, max_amount_b, min_share_increment, - false, ) .map_err(|e| { let err_msg: &str = e.into(); @@ -264,7 +263,6 @@ where remove_share, min_withdrawn_a, min_withdrawn_b, - false, ) .map_err(|e| { let err_msg: &str = e.into(); From 9909747cfe9dc9470f9387021ad740d2fe954460 Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Date: Thu, 2 Sep 2021 16:53:09 +0800 Subject: [PATCH 22/22] Update Cargo.lock --- Cargo.lock | 2773 +++++++++++++++++----------------------------------- 1 file changed, 899 insertions(+), 1874 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1711e7ff0..9a052f69f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -810,15 +810,15 @@ name = "chainbridge" version = "0.0.2" source = "git+https://github.com/Slixon-Technologies/chainbridge-substrate#c536e17c5d4c0f661059a5e13c1ae41d03b21f0d" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", + "frame-support", + "frame-system", + "pallet-balances", "parity-scale-codec", "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -1649,7 +1649,7 @@ name = "evm-rpc" version = "0.9.0" dependencies = [ "ethereum-types", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", "jsonrpc-core", "jsonrpc-derive", "pallet-transaction-payment-rpc-runtime-api", @@ -1659,13 +1659,13 @@ dependencies = [ "serde_json", "setheum-evm", "setheum-evm-rpc-runtime-api", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-blockchain", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", "sp-rpc", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", + "sp-storage", ] [[package]] @@ -1806,7 +1806,7 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "fork-tree" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "parity-scale-codec", ] @@ -1824,49 +1824,30 @@ dependencies = [ [[package]] name = "frame-benchmarking" version = "3.1.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "linregress", - "log", - "parity-scale-codec", - "paste", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", -] - -[[package]] -name = "frame-benchmarking" -version = "3.1.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "linregress", "log", "parity-scale-codec", "paste", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-io", + "sp-runtime", + "sp-runtime-interface", + "sp-std", + "sp-storage", ] [[package]] name = "frame-benchmarking-cli" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "Inflector", "chrono", - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", "handlebars", "parity-scale-codec", "sc-cli", @@ -1874,198 +1855,74 @@ dependencies = [ "sc-executor", "sc-service", "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-externalities", + "sp-keystore", + "sp-runtime", + "sp-state-machine", "structopt", ] [[package]] name = "frame-executive" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] - -[[package]] -name = "frame-metadata" -version = "13.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "parity-scale-codec", - "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", -] - -[[package]] -name = "frame-metadata" -version = "13.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ + "frame-support", + "frame-system", "parity-scale-codec", - "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", + "sp-tracing", ] [[package]] name = "frame-metadata" version = "13.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "parity-scale-codec", - "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", -] - -[[package]] -name = "frame-support" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "bitflags", - "frame-metadata 13.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "frame-support-procedural 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "impl-trait-for-tuples 0.2.1", - "log", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "once_cell", - "parity-scale-codec", - "paste", - "serde", - "smallvec 1.6.1", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-staking 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", -] - -[[package]] -name = "frame-support" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "bitflags", - "frame-metadata 13.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-support-procedural 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "impl-trait-for-tuples 0.2.1", - "log", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "once_cell", "parity-scale-codec", - "paste", "serde", - "smallvec 1.6.1", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-staking 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-std", ] [[package]] name = "frame-support" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "bitflags", - "frame-metadata 13.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "frame-support-procedural 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "frame-metadata", + "frame-support-procedural", "impl-trait-for-tuples 0.2.1", "log", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "max-encoded-len", "once_cell", "parity-scale-codec", "paste", "serde", "smallvec 1.6.1", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-staking 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", -] - -[[package]] -name = "frame-support-procedural" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "Inflector", - "frame-support-procedural-tools 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "frame-support-procedural" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "Inflector", - "frame-support-procedural-tools 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "proc-macro2", - "quote", - "syn", + "sp-arithmetic", + "sp-core", + "sp-inherents", + "sp-io", + "sp-runtime", + "sp-staking", + "sp-state-machine", + "sp-std", + "sp-tracing", ] [[package]] name = "frame-support-procedural" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "Inflector", - "frame-support-procedural-tools 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "frame-support-procedural-tools" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "frame-support-procedural-tools-derive 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "proc-macro-crate 1.0.0", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "frame-support-procedural-tools" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "frame-support-procedural-tools-derive 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "proc-macro-crate 1.0.0", + "frame-support-procedural-tools", "proc-macro2", "quote", "syn", @@ -2074,9 +1931,9 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support-procedural-tools-derive 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "frame-support-procedural-tools-derive", "proc-macro-crate 1.0.0", "proc-macro2", "quote", @@ -2086,27 +1943,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools-derive" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "frame-support-procedural-tools-derive" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "frame-support-procedural-tools-derive" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "proc-macro2", "quote", @@ -2116,73 +1953,39 @@ dependencies = [ [[package]] name = "frame-system" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "impl-trait-for-tuples 0.2.1", - "log", - "parity-scale-codec", - "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", -] - -[[package]] -name = "frame-system" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "impl-trait-for-tuples 0.2.1", - "log", - "parity-scale-codec", - "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] - -[[package]] -name = "frame-system" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "frame-support", "impl-trait-for-tuples 0.2.1", "log", "parity-scale-codec", "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", + "sp-version", ] [[package]] name = "frame-system-rpc-runtime-api" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "parity-scale-codec", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", ] [[package]] name = "frame-try-runtime" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", "parity-scale-codec", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-runtime", + "sp-std", ] [[package]] @@ -3987,42 +3790,10 @@ dependencies = [ [[package]] name = "max-encoded-len" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "impl-trait-for-tuples 0.2.1", - "max-encoded-len-derive 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "parity-scale-codec", - "primitive-types", -] - -[[package]] -name = "max-encoded-len" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.7#9c572625f6557dfdb19f47474369a0327d51dfbc" -dependencies = [ - "impl-trait-for-tuples 0.2.1", - "parity-scale-codec", - "primitive-types", -] - -[[package]] -name = "max-encoded-len" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "impl-trait-for-tuples 0.2.1", - "max-encoded-len-derive 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "parity-scale-codec", - "primitive-types", -] - -[[package]] -name = "max-encoded-len" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "impl-trait-for-tuples 0.2.1", - "max-encoded-len-derive 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "max-encoded-len-derive", "parity-scale-codec", "primitive-types", ] @@ -4030,29 +3801,7 @@ dependencies = [ [[package]] name = "max-encoded-len-derive" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "proc-macro-crate 1.0.0", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "max-encoded-len-derive" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "proc-macro-crate 1.0.0", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "max-encoded-len-derive" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "proc-macro-crate 1.0.0", "proc-macro2", @@ -4355,10 +4104,10 @@ name = "newrome-runtime" version = "0.9.0" dependencies = [ "evm", - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", "frame-executive", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "frame-system-rpc-runtime-api", "frame-try-runtime", "hex-literal 0.3.3", @@ -4374,7 +4123,7 @@ dependencies = [ "orml-vesting", "pallet-authorship", "pallet-babe", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "pallet-bounties", "pallet-collective", "pallet-grandpa", @@ -4417,20 +4166,20 @@ dependencies = [ "setmint-gateway", "setmint-manager", "smallvec 1.6.1", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-application-crypto", "sp-block-builder", "sp-consensus-babe", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-inherents", + "sp-io", "sp-offchain", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", "sp-session", - "sp-staking 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-staking", + "sp-std", "sp-transaction-pool", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-version", "substrate-wasm-builder 4.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.7)", ] @@ -4603,15 +4352,15 @@ checksum = "28988d872ab76095a6e6ac88d99b54fd267702734fd7ffe610ca27f533ddb95a" name = "orml-authority" version = "0.4.1-dev" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "pallet-scheduler", "parity-scale-codec", "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -4621,7 +4370,7 @@ dependencies = [ "ansi_term 0.12.1", "build-helper", "cargo_metadata 0.13.1", - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", "linregress", "parity-scale-codec", "paste", @@ -4631,12 +4380,12 @@ dependencies = [ "sc-executor-common", "serde", "serde_json", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-maybe-compressed-blob 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-maybe-compressed-blob", + "sp-runtime-interface", + "sp-state-machine", + "sp-std", "tempfile", "toml", "walkdir", @@ -4647,19 +4396,19 @@ dependencies = [ name = "orml-benchmarking" version = "0.4.1-dev" dependencies = [ - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", + "frame-support", + "frame-system", "hex-literal 0.2.1", "parity-scale-codec", "paste", "serde", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-io", + "sp-runtime", + "sp-runtime-interface", + "sp-std", + "sp-storage", ] [[package]] @@ -4673,50 +4422,50 @@ dependencies = [ name = "orml-currencies" version = "0.4.1-dev" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "orml-tokens", "orml-traits", "orml-utilities", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "parity-scale-codec", "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "orml-nft" version = "0.4.1-dev" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", + "max-encoded-len", "parity-scale-codec", "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "orml-oracle" version = "0.4.1-dev" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "orml-traits", "orml-utilities", "parity-scale-codec", "serde", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-application-crypto", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -4728,9 +4477,9 @@ dependencies = [ "jsonrpc-derive", "orml-oracle-rpc-runtime-api", "parity-scale-codec", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-blockchain", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", ] [[package]] @@ -4738,57 +4487,57 @@ name = "orml-oracle-rpc-runtime-api" version = "0.4.1-dev" dependencies = [ "parity-scale-codec", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-std", ] [[package]] name = "orml-rewards" version = "0.4.1-dev" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", + "max-encoded-len", "orml-traits", "parity-scale-codec", "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "orml-tokens" version = "0.4.1-dev" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", + "max-encoded-len", "orml-traits", "pallet-elections-phragmen", "pallet-treasury", "parity-scale-codec", "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "orml-traits" version = "0.4.1-dev" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", "impl-trait-for-tuples 0.2.1", "num-traits", "orml-utilities", "parity-scale-codec", "serde", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-io", + "sp-runtime", + "sp-std", "xcm", ] @@ -4796,45 +4545,45 @@ dependencies = [ name = "orml-utilities" version = "0.4.1-dev" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "parity-scale-codec", "serde", "serde_json", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "orml-vesting" version = "0.4.1-dev" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", + "max-encoded-len", + "pallet-balances", "parity-scale-codec", "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "orml-weight-meter" version = "0.4.1-dev" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "orml-bencher", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "parity-scale-codec", "serde", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-io", + "sp-runtime", + "sp-std", "spin 0.7.1", "weight-meter-procedural", ] @@ -4857,209 +4606,194 @@ dependencies = [ [[package]] name = "pallet-authorship" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "impl-trait-for-tuples 0.2.1", "parity-scale-codec", "sp-authorship", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-babe" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", + "frame-support", + "frame-system", "log", "pallet-authorship", "pallet-session", "pallet-timestamp", "parity-scale-codec", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-application-crypto", "sp-consensus-babe", "sp-consensus-vrf", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-io", + "sp-runtime", "sp-session", - "sp-staking 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] - -[[package]] -name = "pallet-balances" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "log", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "parity-scale-codec", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", + "sp-staking", + "sp-std", ] [[package]] name = "pallet-balances" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", + "frame-support", + "frame-system", "log", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "max-encoded-len", "parity-scale-codec", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-bounties" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "pallet-treasury", "parity-scale-codec", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-collective" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", + "frame-support", + "frame-system", "log", "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-elections-phragmen" version = "4.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "frame-support", + "frame-system", "log", "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-core", + "sp-io", "sp-npos-elections", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-grandpa" version = "3.1.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", + "frame-support", + "frame-system", "log", "pallet-authorship", "pallet-session", "parity-scale-codec", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-application-crypto", + "sp-core", "sp-finality-grandpa", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-io", + "sp-runtime", "sp-session", - "sp-staking 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-staking", + "sp-std", ] [[package]] name = "pallet-indices" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", "sp-keyring", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-membership" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", + "frame-support", + "frame-system", "log", "parity-scale-codec", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-multisig" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-offences" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "log", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "parity-scale-codec", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-staking 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", + "sp-staking", + "sp-std", ] [[package]] name = "pallet-proxy" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", + "max-encoded-len", "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -5067,67 +4801,67 @@ name = "pallet-randomness-collective-flip" version = "3.0.0" source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "parity-scale-codec", "safe-mix", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-recovery" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "enumflags2", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "parity-scale-codec", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-scheduler" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", + "frame-support", + "frame-system", "log", "parity-scale-codec", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-session" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "impl-trait-for-tuples 0.2.1", "log", "pallet-timestamp", "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", "sp-session", - "sp-staking 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-staking", + "sp-std", + "sp-trie", ] [[package]] name = "pallet-staking-reward-curve" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "proc-macro-crate 1.0.0", "proc-macro2", @@ -5138,119 +4872,119 @@ dependencies = [ [[package]] name = "pallet-sudo" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "parity-scale-codec", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-timestamp" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", + "frame-support", + "frame-system", "impl-trait-for-tuples 0.2.1", "log", "parity-scale-codec", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-inherents", + "sp-io", + "sp-runtime", + "sp-std", "sp-timestamp", ] [[package]] name = "pallet-tips" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "pallet-treasury", "parity-scale-codec", "serde", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-transaction-payment" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "parity-scale-codec", "serde", "smallvec 1.6.1", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-transaction-payment-rpc" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "jsonrpc-core", "jsonrpc-core-client", "jsonrpc-derive", "pallet-transaction-payment-rpc-runtime-api", "parity-scale-codec", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-blockchain", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", "sp-rpc", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", ] [[package]] name = "pallet-transaction-payment-rpc-runtime-api" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "pallet-transaction-payment", "parity-scale-codec", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-runtime", ] [[package]] name = "pallet-treasury" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "impl-trait-for-tuples 0.2.1", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "parity-scale-codec", "serde", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", + "sp-std", ] [[package]] name = "pallet-utility" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -6187,7 +5921,7 @@ dependencies = [ [[package]] name = "remote-externalities" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "env_logger 0.8.4", "hex", @@ -6197,9 +5931,9 @@ dependencies = [ "parity-scale-codec", "serde", "serde_json", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", ] [[package]] @@ -6298,16 +6032,16 @@ dependencies = [ name = "runtime-common" version = "0.9.0" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "hex-literal 0.3.3", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "max-encoded-len", "num_enum", "orml-nft", "orml-oracle", "orml-tokens", "orml-traits", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "pallet-collective", "pallet-membership", "pallet-proxy", @@ -6328,10 +6062,10 @@ dependencies = [ "setheum-support", "setheum-transaction-payment", "sha3 0.9.1", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", "static_assertions", ] @@ -6478,19 +6212,19 @@ dependencies = [ [[package]] name = "sc-allocator" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "log", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-wasm-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-std", + "sp-wasm-interface", "thiserror", ] [[package]] name = "sc-basic-authorship" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "futures 0.3.16", "futures-timer 3.0.2", @@ -6500,12 +6234,12 @@ dependencies = [ "sc-client-api", "sc-proposer-metrics", "sc-telemetry", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-blockchain", "sp-consensus", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-inherents", + "sp-runtime", "sp-transaction-pool", "substrate-prometheus-endpoint", ] @@ -6513,23 +6247,23 @@ dependencies = [ [[package]] name = "sc-block-builder" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "parity-scale-codec", "sc-client-api", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-block-builder", "sp-blockchain", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-inherents", + "sp-runtime", + "sp-state-machine", ] [[package]] name = "sc-chain-spec" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "impl-trait-for-tuples 0.2.1", "parity-scale-codec", @@ -6542,14 +6276,14 @@ dependencies = [ "serde", "serde_json", "sp-consensus-babe", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-runtime", ] [[package]] name = "sc-chain-spec-derive" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "proc-macro-crate 1.0.0", "proc-macro2", @@ -6560,7 +6294,7 @@ dependencies = [ [[package]] name = "sc-cli" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "chrono", "fdlimit", @@ -6582,13 +6316,13 @@ dependencies = [ "serde", "serde_json", "sp-blockchain", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", "sp-keyring", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-panic-handler 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-keystore", + "sp-panic-handler", + "sp-runtime", "sp-utils", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-version", "structopt", "thiserror", "tiny-bip39", @@ -6598,7 +6332,7 @@ dependencies = [ [[package]] name = "sc-client-api" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "derive_more", "fnv", @@ -6610,29 +6344,29 @@ dependencies = [ "parity-scale-codec", "parking_lot 0.11.1", "sc-executor", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-blockchain", "sp-consensus", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", "sp-database", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-externalities", + "sp-inherents", + "sp-keystore", + "sp-runtime", + "sp-state-machine", + "sp-std", + "sp-storage", "sp-transaction-pool", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-trie", "sp-utils", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-version", "substrate-prometheus-endpoint", ] [[package]] name = "sc-client-db" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "blake2-rfc", "hash-db", @@ -6648,34 +6382,34 @@ dependencies = [ "sc-client-api", "sc-executor", "sc-state-db", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-arithmetic", "sp-blockchain", "sp-consensus", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", "sp-database", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", + "sp-state-machine", + "sp-trie", "substrate-prometheus-endpoint", ] [[package]] name = "sc-consensus" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "parking_lot 0.11.1", "sc-client-api", "sp-blockchain", "sp-consensus", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", ] [[package]] name = "sc-consensus-aura" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "derive_more", @@ -6687,26 +6421,26 @@ dependencies = [ "sc-client-api", "sc-consensus-slots", "sc-telemetry", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-application-crypto", "sp-block-builder", "sp-blockchain", "sp-consensus", "sp-consensus-aura", "sp-consensus-slots", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-inherents", + "sp-io", + "sp-keystore", + "sp-runtime", + "sp-version", "substrate-prometheus-endpoint", ] [[package]] name = "sc-consensus-babe" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "derive_more", @@ -6731,28 +6465,28 @@ dependencies = [ "sc-telemetry", "schnorrkel", "serde", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-application-crypto", "sp-block-builder", "sp-blockchain", "sp-consensus", "sp-consensus-babe", "sp-consensus-slots", "sp-consensus-vrf", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-inherents", + "sp-io", + "sp-keystore", + "sp-runtime", "sp-utils", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-version", "substrate-prometheus-endpoint", ] [[package]] name = "sc-consensus-babe-rpc" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "derive_more", "futures 0.3.16", @@ -6763,33 +6497,33 @@ dependencies = [ "sc-consensus-epochs", "sc-rpc-api", "serde", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-application-crypto", "sp-blockchain", "sp-consensus", "sp-consensus-babe", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-keystore", + "sp-runtime", ] [[package]] name = "sc-consensus-epochs" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "fork-tree", "parity-scale-codec", "sc-client-api", "sc-consensus", "sp-blockchain", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", ] [[package]] name = "sc-consensus-manual-seal" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "assert_matches", "async-trait", @@ -6806,16 +6540,16 @@ dependencies = [ "sc-consensus-epochs", "sc-transaction-pool", "serde", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-blockchain", "sp-consensus", "sp-consensus-babe", "sp-consensus-slots", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-inherents", "sp-keyring", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-keystore", + "sp-runtime", "sp-timestamp", "sp-transaction-pool", "substrate-prometheus-endpoint", @@ -6824,7 +6558,7 @@ dependencies = [ [[package]] name = "sc-consensus-slots" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "futures 0.3.16", @@ -6834,36 +6568,36 @@ dependencies = [ "parity-scale-codec", "sc-client-api", "sc-telemetry", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-application-crypto", + "sp-arithmetic", "sp-blockchain", "sp-consensus", "sp-consensus-slots", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-inherents", + "sp-runtime", + "sp-state-machine", "sp-timestamp", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-trie", "thiserror", ] [[package]] name = "sc-consensus-uncles" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "sc-client-api", "sp-authorship", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", "thiserror", ] [[package]] name = "sc-executor" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "derive_more", "lazy_static", @@ -6875,33 +6609,33 @@ dependencies = [ "sc-executor-common", "sc-executor-wasmi", "sc-executor-wasmtime", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-panic-handler 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-core", + "sp-externalities", + "sp-io", + "sp-panic-handler", + "sp-runtime-interface", "sp-serializer", "sp-tasks", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-wasm-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-trie", + "sp-version", + "sp-wasm-interface", "wasmi", ] [[package]] name = "sc-executor-common" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "derive_more", "parity-scale-codec", "pwasm-utils", "sc-allocator", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-maybe-compressed-blob 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-maybe-compressed-blob", "sp-serializer", - "sp-wasm-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-wasm-interface", "thiserror", "wasmi", ] @@ -6909,22 +6643,22 @@ dependencies = [ [[package]] name = "sc-executor-wasmi" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "log", "parity-scale-codec", "sc-allocator", "sc-executor-common", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-wasm-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-runtime-interface", + "sp-wasm-interface", "wasmi", ] [[package]] name = "sc-executor-wasmtime" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "cfg-if 1.0.0", "libc", @@ -6934,16 +6668,16 @@ dependencies = [ "sc-allocator", "sc-executor-common", "scoped-tls", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-wasm-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-runtime-interface", + "sp-wasm-interface", "wasmtime", ] [[package]] name = "sc-finality-grandpa" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "derive_more", @@ -6966,16 +6700,16 @@ dependencies = [ "sc-network-gossip", "sc-telemetry", "serde_json", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-application-crypto", + "sp-arithmetic", "sp-blockchain", "sp-consensus", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", "sp-finality-grandpa", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-inherents", + "sp-keystore", + "sp-runtime", "sp-utils", "substrate-prometheus-endpoint", "wasm-timer", @@ -6984,7 +6718,7 @@ dependencies = [ [[package]] name = "sc-finality-grandpa-rpc" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "derive_more", "finality-grandpa", @@ -7001,14 +6735,14 @@ dependencies = [ "serde", "serde_json", "sp-blockchain", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-runtime", ] [[package]] name = "sc-informant" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "ansi_term 0.12.1", "futures 0.3.16", @@ -7018,7 +6752,7 @@ dependencies = [ "sc-client-api", "sc-network", "sp-blockchain", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", "sp-transaction-pool", "wasm-timer", ] @@ -7026,7 +6760,7 @@ dependencies = [ [[package]] name = "sc-keystore" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "derive_more", @@ -7037,16 +6771,16 @@ dependencies = [ "parking_lot 0.11.1", "rand 0.7.3", "serde_json", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-application-crypto", + "sp-core", + "sp-keystore", "subtle 2.4.1", ] [[package]] name = "sc-light" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "hash-db", "lazy_static", @@ -7054,18 +6788,18 @@ dependencies = [ "parking_lot 0.11.1", "sc-client-api", "sc-executor", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-blockchain", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-externalities", + "sp-runtime", + "sp-state-machine", ] [[package]] name = "sc-network" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-std", "async-trait", @@ -7101,11 +6835,11 @@ dependencies = [ "serde", "serde_json", "smallvec 1.6.1", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-arithmetic", "sp-blockchain", "sp-consensus", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-runtime", "sp-utils", "substrate-prometheus-endpoint", "thiserror", @@ -7118,7 +6852,7 @@ dependencies = [ [[package]] name = "sc-network-gossip" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "futures 0.3.16", "futures-timer 3.0.2", @@ -7126,7 +6860,7 @@ dependencies = [ "log", "lru", "sc-network", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", "substrate-prometheus-endpoint", "tracing", "wasm-timer", @@ -7135,7 +6869,7 @@ dependencies = [ [[package]] name = "sc-offchain" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "bytes 0.5.6", "fnv", @@ -7152,10 +6886,10 @@ dependencies = [ "sc-client-api", "sc-keystore", "sc-network", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-core", "sp-offchain", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", "sp-utils", "threadpool", ] @@ -7163,7 +6897,7 @@ dependencies = [ [[package]] name = "sc-peerset" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "futures 0.3.16", "libp2p", @@ -7176,7 +6910,7 @@ dependencies = [ [[package]] name = "sc-proposer-metrics" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "log", "substrate-prometheus-endpoint", @@ -7185,7 +6919,7 @@ dependencies = [ [[package]] name = "sc-rpc" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "futures 0.3.16", "hash-db", @@ -7202,25 +6936,25 @@ dependencies = [ "sc-rpc-api", "sc-tracing", "serde_json", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-blockchain", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-keystore", "sp-offchain", "sp-rpc", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", "sp-session", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-state-machine", + "sp-tracing", "sp-transaction-pool", "sp-utils", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-version", ] [[package]] name = "sc-rpc-api" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "derive_more", "futures 0.3.16", @@ -7234,18 +6968,18 @@ dependencies = [ "sc-chain-spec", "serde", "serde_json", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", "sp-rpc", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", + "sp-tracing", "sp-transaction-pool", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-version", ] [[package]] name = "sc-rpc-server" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "futures 0.1.31", "jsonrpc-core", @@ -7256,14 +6990,14 @@ dependencies = [ "log", "serde", "serde_json", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", "substrate-prometheus-endpoint", ] [[package]] name = "sc-service" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "directories", @@ -7298,26 +7032,26 @@ dependencies = [ "sc-transaction-pool", "serde", "serde_json", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-application-crypto", "sp-block-builder", "sp-blockchain", "sp-consensus", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-externalities", + "sp-inherents", + "sp-io", + "sp-keystore", + "sp-runtime", "sp-session", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-state-machine", + "sp-storage", + "sp-tracing", "sp-transaction-pool", "sp-transaction-storage-proof", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-trie", "sp-utils", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-version", "substrate-prometheus-endpoint", "tempfile", "thiserror", @@ -7329,7 +7063,7 @@ dependencies = [ [[package]] name = "sc-state-db" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "log", "parity-scale-codec", @@ -7337,14 +7071,14 @@ dependencies = [ "parity-util-mem-derive", "parking_lot 0.11.1", "sc-client-api", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", "thiserror", ] [[package]] name = "sc-telemetry" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "chrono", "futures 0.3.16", @@ -7364,7 +7098,7 @@ dependencies = [ [[package]] name = "sc-tracing" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "ansi_term 0.12.1", "atty", @@ -7381,14 +7115,14 @@ dependencies = [ "sc-tracing-proc-macro", "serde", "serde_json", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-block-builder", "sp-blockchain", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", "sp-rpc", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", + "sp-storage", + "sp-tracing", "thiserror", "tracing", "tracing-log", @@ -7401,7 +7135,7 @@ dependencies = [ [[package]] name = "sc-tracing-proc-macro" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "proc-macro-crate 1.0.0", "proc-macro2", @@ -7412,7 +7146,7 @@ dependencies = [ [[package]] name = "sc-transaction-graph" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "derive_more", "futures 0.3.16", @@ -7423,8 +7157,8 @@ dependencies = [ "retain_mut", "serde", "sp-blockchain", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-runtime", "sp-transaction-pool", "sp-utils", "thiserror", @@ -7434,7 +7168,7 @@ dependencies = [ [[package]] name = "sc-transaction-pool" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "futures 0.3.16", "intervalier", @@ -7444,11 +7178,11 @@ dependencies = [ "parking_lot 0.11.1", "sc-client-api", "sc-transaction-graph", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-blockchain", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-runtime", + "sp-tracing", "sp-transaction-pool", "sp-utils", "substrate-prometheus-endpoint", @@ -7504,7 +7238,6 @@ dependencies = [ "merlin", "rand 0.7.3", "rand_core 0.5.1", - "serde", "sha2 0.8.2", "subtle 2.4.1", "zeroize", @@ -7685,19 +7418,19 @@ dependencies = [ name = "serp-prices" version = "0.9.0" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "orml-tokens", "orml-traits", "parity-scale-codec", "serde", "setheum-primitives", "setheum-support", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-arithmetic", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", "substrate-fixed", ] @@ -7705,22 +7438,22 @@ dependencies = [ name = "serp-treasury" version = "0.9.0" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "orml-currencies", "orml-tokens", "orml-traits", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "parity-scale-codec", "serde", "serp-prices", "setheum-dex", "setheum-primitives", "setheum-support", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7737,14 +7470,14 @@ dependencies = [ name = "setheum-airdrop" version = "0.9.0" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "parity-scale-codec", "serde", "setheum-primitives", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", ] [[package]] @@ -7752,18 +7485,18 @@ name = "setheum-chainbridge" version = "1.0.0" dependencies = [ "chainbridge", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "orml-tokens", "orml-traits", "parity-scale-codec", "serde", "setheum-primitives", "setheum-support", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7780,8 +7513,8 @@ dependencies = [ "sc-tracing", "setheum-inspect", "setheum-service", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-runtime", "structopt", "try-runtime-cli", ] @@ -7790,13 +7523,13 @@ dependencies = [ name = "setheum-currencies" version = "0.9.0" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "orml-currencies", "orml-tokens", "orml-traits", "orml-utilities", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "pallet-timestamp", "parity-scale-codec", "serde", @@ -7806,31 +7539,31 @@ dependencies = [ "setheum-evm-bridge", "setheum-primitives", "setheum-support", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "setheum-dex" version = "0.8.0" dependencies = [ - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", + "frame-support", + "frame-system", + "max-encoded-len", "orml-tokens", "orml-traits", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "parity-scale-codec", "serde", "setheum-primitives", "setheum-support", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7841,14 +7574,14 @@ dependencies = [ "evm", "evm-gasometer", "evm-runtime", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "impl-trait-for-tuples 0.1.3", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "max-encoded-len", "orml-currencies", "orml-tokens", "orml-traits", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "pallet-timestamp", "parity-scale-codec", "primitive-types", @@ -7858,10 +7591,10 @@ dependencies = [ "setheum-primitives", "setheum-support", "sha3 0.9.1", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", "tiny-keccak", ] @@ -7869,21 +7602,21 @@ dependencies = [ name = "setheum-evm-accounts" version = "1.2.2" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "libsecp256k1", "orml-currencies", "orml-tokens", "orml-traits", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "parity-scale-codec", "serde", "setheum-primitives", "setheum-support", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7891,11 +7624,11 @@ name = "setheum-evm-bridge" version = "1.2.2" dependencies = [ "ethereum-types", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "impl-trait-for-tuples 0.2.1", "num_enum", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "pallet-timestamp", "parity-scale-codec", "primitive-types", @@ -7904,23 +7637,23 @@ dependencies = [ "setheum-evm", "setheum-primitives", "setheum-support", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "setheum-evm-manager" version = "1.2.2" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "orml-currencies", "orml-tokens", "orml-traits", "orml-utilities", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "pallet-timestamp", "parity-scale-codec", "serde", @@ -7928,10 +7661,10 @@ dependencies = [ "setheum-evm-bridge", "setheum-primitives", "setheum-support", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -7940,23 +7673,23 @@ version = "1.2.2" dependencies = [ "ethereum-types", "setheum-primitives", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] name = "setheum-example" version = "0.9.0" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "parity-scale-codec", "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", ] [[package]] @@ -7970,8 +7703,8 @@ dependencies = [ "sc-client-api", "sc-service", "sp-blockchain", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-runtime", "structopt", ] @@ -7980,14 +7713,14 @@ name = "setheum-nft" version = "0.9.0" dependencies = [ "enumflags2", - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", + "frame-support", + "frame-system", + "max-encoded-len", "orml-nft", "orml-tokens", "orml-traits", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "pallet-proxy", "pallet-utility", "parity-scale-codec", @@ -7995,10 +7728,10 @@ dependencies = [ "setheum-currencies", "setheum-primitives", "setheum-support", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -8008,38 +7741,38 @@ dependencies = [ "bstringify", "chainbridge", "evm", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "max-encoded-len", "num-traits", "num_enum", "parity-scale-codec", "primitives-proc-macro", "serde", "serde_json", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] name = "setheum-renvm-bridge" version = "1.0.0" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "hex-literal 0.3.3", "orml-currencies", "orml-tokens", "orml-traits", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "parity-scale-codec", "serde", "setheum-primitives", "setheum-support", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -8061,13 +7794,13 @@ dependencies = [ "sc-keystore", "sc-rpc", "setheum-primitives", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-block-builder", "sp-blockchain", "sp-consensus", "sp-consensus-babe", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-keystore", + "sp-runtime", "sp-transaction-pool", "substrate-frame-rpc-system", ] @@ -8076,14 +7809,14 @@ dependencies = [ name = "setheum-runtime" version = "0.9.0" dependencies = [ - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", "frame-executive", - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "frame-system-rpc-runtime-api", "frame-try-runtime", "hex-literal 0.3.3", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.7)", + "max-encoded-len", "orml-authority", "orml-benchmarking", "orml-nft", @@ -8095,7 +7828,7 @@ dependencies = [ "orml-vesting", "pallet-authorship", "pallet-babe", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "pallet-bounties", "pallet-collective", "pallet-grandpa", @@ -8138,20 +7871,20 @@ dependencies = [ "setmint-gateway", "setmint-manager", "smallvec 1.6.1", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-application-crypto", "sp-block-builder", "sp-consensus-babe", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-inherents", + "sp-io", "sp-offchain", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", "sp-session", - "sp-staking 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-staking", + "sp-std", "sp-transaction-pool", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-version", "substrate-wasm-builder 4.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -8160,7 +7893,7 @@ name = "setheum-service" version = "0.9.0" dependencies = [ "async-trait", - "frame-benchmarking 3.1.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-benchmarking", "frame-system-rpc-runtime-api", "futures 0.3.16", "hex-literal 0.3.3", @@ -8196,24 +7929,24 @@ dependencies = [ "setheum-renvm-bridge", "setheum-rpc", "setheum-runtime", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-block-builder", "sp-blockchain", "sp-consensus", "sp-consensus-aura", "sp-consensus-babe", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", "sp-finality-grandpa", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-inherents", + "sp-keystore", "sp-offchain", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", "sp-session", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-std", + "sp-storage", "sp-timestamp", "sp-transaction-pool", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-trie", "substrate-prometheus-endpoint", ] @@ -8221,25 +7954,25 @@ dependencies = [ name = "setheum-support" version = "0.9.0" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", "impl-trait-for-tuples 0.1.3", "parity-scale-codec", "setheum-primitives", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "setheum-transaction-payment" version = "0.8.0" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "orml-tokens", "orml-traits", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", "parity-scale-codec", @@ -8249,23 +7982,23 @@ dependencies = [ "setheum-primitives", "setheum-support", "smallvec 1.6.1", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "setmint-engine" version = "0.9.0" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "orml-currencies", "orml-tokens", "orml-traits", "orml-utilities", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "parity-scale-codec", "serde", "serp-treasury", @@ -8273,23 +8006,23 @@ dependencies = [ "setheum-primitives", "setheum-support", "setmint-manager", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-application-crypto", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "setmint-gateway" version = "0.9.0" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", "orml-currencies", "orml-tokens", "orml-traits", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "parity-scale-codec", "serde", "serp-treasury", @@ -8298,33 +8031,33 @@ dependencies = [ "setheum-support", "setmint-engine", "setmint-manager", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] name = "setmint-manager" version = "0.9.0" dependencies = [ - "frame-support 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "frame-system 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "frame-support", + "frame-system", + "max-encoded-len", "orml-currencies", "orml-tokens", "orml-traits", - "pallet-balances 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "pallet-balances", "parity-scale-codec", "serde", "serp-treasury", "setheum-dex", "setheum-primitives", "setheum-support", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-io", + "sp-runtime", + "sp-std", ] [[package]] @@ -8557,53 +8290,24 @@ dependencies = [ [[package]] name = "sp-api" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "hash-db", - "log", - "parity-scale-codec", - "sp-api-proc-macro 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "thiserror", -] - -[[package]] -name = "sp-api" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "hash-db", "log", "parity-scale-codec", - "sp-api-proc-macro 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api-proc-macro", + "sp-core", + "sp-runtime", + "sp-state-machine", + "sp-std", + "sp-version", "thiserror", ] [[package]] name = "sp-api-proc-macro" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "blake2-rfc", - "proc-macro-crate 1.0.0", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "sp-api-proc-macro" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "blake2-rfc", "proc-macro-crate 1.0.0", @@ -8615,130 +8319,76 @@ dependencies = [ [[package]] name = "sp-application-crypto" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "parity-scale-codec", - "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", -] - -[[package]] -name = "sp-application-crypto" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "parity-scale-codec", - "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] - -[[package]] -name = "sp-application-crypto" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "parity-scale-codec", - "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", -] - -[[package]] -name = "sp-arithmetic" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "integer-sqrt", - "num-traits", - "parity-scale-codec", - "serde", - "sp-debug-derive 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "static_assertions", -] - -[[package]] -name = "sp-arithmetic" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "integer-sqrt", - "num-traits", + "max-encoded-len", "parity-scale-codec", "serde", - "sp-debug-derive 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "static_assertions", + "sp-core", + "sp-io", + "sp-std", ] [[package]] name = "sp-arithmetic" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "integer-sqrt", "num-traits", "parity-scale-codec", "serde", - "sp-debug-derive 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-debug-derive", + "sp-std", "static_assertions", ] [[package]] name = "sp-authorship" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "parity-scale-codec", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-inherents", + "sp-runtime", + "sp-std", ] [[package]] name = "sp-block-builder" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "parity-scale-codec", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-inherents", + "sp-runtime", + "sp-std", ] [[package]] name = "sp-blockchain" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "futures 0.3.16", "log", "lru", "parity-scale-codec", "parking_lot 0.11.1", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-consensus", "sp-database", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", + "sp-state-machine", "thiserror", ] [[package]] name = "sp-consensus" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "futures 0.3.16", @@ -8748,15 +8398,15 @@ dependencies = [ "parity-scale-codec", "parking_lot 0.11.1", "serde", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-core", + "sp-inherents", + "sp-runtime", + "sp-state-machine", + "sp-std", + "sp-trie", "sp-utils", - "sp-version 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-version", "substrate-prometheus-endpoint", "thiserror", "wasm-timer", @@ -8765,158 +8415,68 @@ dependencies = [ [[package]] name = "sp-consensus-aura" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "parity-scale-codec", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-application-crypto", "sp-consensus", "sp-consensus-slots", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-inherents", + "sp-runtime", + "sp-std", "sp-timestamp", ] [[package]] name = "sp-consensus-babe" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "merlin", "parity-scale-codec", "serde", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-application-crypto", "sp-consensus", "sp-consensus-slots", "sp-consensus-vrf", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-inherents", + "sp-keystore", + "sp-runtime", + "sp-std", "sp-timestamp", ] [[package]] name = "sp-consensus-slots" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "parity-scale-codec", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-arithmetic", + "sp-runtime", ] [[package]] name = "sp-consensus-vrf" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "parity-scale-codec", - "schnorrkel", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] - -[[package]] -name = "sp-core" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "base58", - "blake2-rfc", - "byteorder", - "dyn-clonable", - "ed25519-dalek", - "futures 0.3.16", - "hash-db", - "hash256-std-hasher", - "hex", - "impl-serde", - "lazy_static", - "libsecp256k1", - "log", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "merlin", - "num-traits", - "parity-scale-codec", - "parity-util-mem", - "parking_lot 0.11.1", - "primitive-types", - "rand 0.7.3", - "regex", - "schnorrkel", - "secrecy", - "serde", - "sha2 0.9.5", - "sp-debug-derive 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "substrate-bip39", - "thiserror", - "tiny-bip39", - "tiny-keccak", - "twox-hash", - "wasmi", - "zeroize", -] - -[[package]] -name = "sp-core" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "base58", - "blake2-rfc", - "byteorder", - "dyn-clonable", - "ed25519-dalek", - "futures 0.3.16", - "hash-db", - "hash256-std-hasher", - "hex", - "impl-serde", - "lazy_static", - "libsecp256k1", - "log", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "merlin", - "num-traits", "parity-scale-codec", - "parity-util-mem", - "parking_lot 0.11.1", - "primitive-types", - "rand 0.7.3", - "regex", "schnorrkel", - "secrecy", - "serde", - "sha2 0.9.5", - "sp-debug-derive 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "substrate-bip39", - "thiserror", - "tiny-bip39", - "tiny-keccak", - "twox-hash", - "wasmi", - "zeroize", + "sp-core", + "sp-runtime", + "sp-std", ] [[package]] name = "sp-core" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "base58", "blake2-rfc", @@ -8931,7 +8491,7 @@ dependencies = [ "lazy_static", "libsecp256k1", "log", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "max-encoded-len", "merlin", "num-traits", "parity-scale-codec", @@ -8944,11 +8504,11 @@ dependencies = [ "secrecy", "serde", "sha2 0.9.5", - "sp-debug-derive 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-debug-derive", + "sp-externalities", + "sp-runtime-interface", + "sp-std", + "sp-storage", "substrate-bip39", "thiserror", "tiny-bip39", @@ -8961,7 +8521,7 @@ dependencies = [ [[package]] name = "sp-database" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "kvdb", "parking_lot 0.11.1", @@ -8970,179 +8530,59 @@ dependencies = [ [[package]] name = "sp-debug-derive" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "proc-macro2", "quote", "syn", ] -[[package]] -name = "sp-debug-derive" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "sp-debug-derive" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "sp-externalities" -version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "environmental", - "parity-scale-codec", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", -] - -[[package]] -name = "sp-externalities" -version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "environmental", - "parity-scale-codec", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] - [[package]] name = "sp-externalities" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "environmental", "parity-scale-codec", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-std", + "sp-storage", ] [[package]] name = "sp-finality-grandpa" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "finality-grandpa", "log", "parity-scale-codec", "serde", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] - -[[package]] -name = "sp-inherents" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "async-trait", - "impl-trait-for-tuples 0.2.1", - "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "thiserror", -] - -[[package]] -name = "sp-inherents" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "async-trait", - "impl-trait-for-tuples 0.2.1", - "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "thiserror", + "sp-api", + "sp-application-crypto", + "sp-core", + "sp-keystore", + "sp-runtime", + "sp-std", ] [[package]] name = "sp-inherents" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "impl-trait-for-tuples 0.2.1", "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-core", + "sp-runtime", + "sp-std", "thiserror", ] [[package]] name = "sp-io" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "futures 0.3.16", - "hash-db", - "libsecp256k1", - "log", - "parity-scale-codec", - "parking_lot 0.11.1", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-maybe-compressed-blob 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-wasm-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "tracing", - "tracing-core", -] - -[[package]] -name = "sp-io" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "futures 0.3.16", - "hash-db", - "libsecp256k1", - "log", - "parity-scale-codec", - "parking_lot 0.11.1", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-maybe-compressed-blob 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-wasm-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "tracing", - "tracing-core", -] - -[[package]] -name = "sp-io" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "futures 0.3.16", "hash-db", @@ -9150,16 +8590,16 @@ dependencies = [ "log", "parity-scale-codec", "parking_lot 0.11.1", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-maybe-compressed-blob 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-wasm-interface 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-core", + "sp-externalities", + "sp-keystore", + "sp-maybe-compressed-blob", + "sp-runtime-interface", + "sp-state-machine", + "sp-std", + "sp-tracing", + "sp-trie", + "sp-wasm-interface", "tracing", "tracing-core", ] @@ -9167,18 +8607,18 @@ dependencies = [ [[package]] name = "sp-keyring" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "lazy_static", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-runtime", "strum", ] [[package]] name = "sp-keystore" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "derive_more", @@ -9187,74 +8627,15 @@ dependencies = [ "parity-scale-codec", "parking_lot 0.11.1", "schnorrkel", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", + "serde", + "sp-core", + "sp-externalities", ] [[package]] -name = "sp-keystore" -version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "async-trait", - "derive_more", - "futures 0.3.16", - "merlin", - "parity-scale-codec", - "parking_lot 0.11.1", - "schnorrkel", - "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] - -[[package]] -name = "sp-keystore" -version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "async-trait", - "derive_more", - "futures 0.3.16", - "merlin", - "parity-scale-codec", - "parking_lot 0.11.1", - "schnorrkel", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", -] - -[[package]] -name = "sp-maybe-compressed-blob" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "ruzstd", - "zstd", -] - -[[package]] -name = "sp-maybe-compressed-blob" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.7#9c572625f6557dfdb19f47474369a0327d51dfbc" -dependencies = [ - "ruzstd", - "zstd", -] - -[[package]] -name = "sp-maybe-compressed-blob" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "ruzstd", - "zstd", -] - -[[package]] -name = "sp-maybe-compressed-blob" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +name = "sp-maybe-compressed-blob" +version = "3.0.0" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "ruzstd", "zstd", @@ -9263,20 +8644,20 @@ dependencies = [ [[package]] name = "sp-npos-elections" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "parity-scale-codec", "serde", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-arithmetic", + "sp-core", "sp-npos-elections-compact", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-std", ] [[package]] name = "sp-npos-elections-compact" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "proc-macro-crate 1.0.0", "proc-macro2", @@ -9287,33 +8668,17 @@ dependencies = [ [[package]] name = "sp-offchain" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] - -[[package]] -name = "sp-panic-handler" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "backtrace", -] - -[[package]] -name = "sp-panic-handler" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "backtrace", + "sp-api", + "sp-core", + "sp-runtime", ] [[package]] name = "sp-panic-handler" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "backtrace", ] @@ -9321,159 +8686,57 @@ dependencies = [ [[package]] name = "sp-rpc" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "rustc-hash", "serde", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", "tracing-core", ] [[package]] name = "sp-runtime" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "either", - "hash256-std-hasher", - "impl-trait-for-tuples 0.2.1", - "log", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "parity-scale-codec", - "parity-util-mem", - "paste", - "rand 0.7.3", - "serde", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", -] - -[[package]] -name = "sp-runtime" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "either", "hash256-std-hasher", "impl-trait-for-tuples 0.2.1", "log", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "max-encoded-len", "parity-scale-codec", "parity-util-mem", "paste", "rand 0.7.3", "serde", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] - -[[package]] -name = "sp-runtime" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "either", - "hash256-std-hasher", - "impl-trait-for-tuples 0.2.1", - "log", - "max-encoded-len 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "parity-scale-codec", - "parity-util-mem", - "paste", - "rand 0.7.3", - "serde", - "sp-application-crypto 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-arithmetic 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", -] - -[[package]] -name = "sp-runtime-interface" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "impl-trait-for-tuples 0.2.1", - "parity-scale-codec", - "primitive-types", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-runtime-interface-proc-macro 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-wasm-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "static_assertions", -] - -[[package]] -name = "sp-runtime-interface" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "impl-trait-for-tuples 0.2.1", - "parity-scale-codec", - "primitive-types", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime-interface-proc-macro 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-wasm-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "static_assertions", + "sp-application-crypto", + "sp-arithmetic", + "sp-core", + "sp-io", + "sp-std", ] [[package]] name = "sp-runtime-interface" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "impl-trait-for-tuples 0.2.1", "parity-scale-codec", "primitive-types", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-runtime-interface-proc-macro 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-storage 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-tracing 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-wasm-interface 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-externalities", + "sp-runtime-interface-proc-macro", + "sp-std", + "sp-storage", + "sp-tracing", + "sp-wasm-interface", "static_assertions", ] [[package]] name = "sp-runtime-interface-proc-macro" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "Inflector", - "proc-macro-crate 1.0.0", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "sp-runtime-interface-proc-macro" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "Inflector", - "proc-macro-crate 1.0.0", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "sp-runtime-interface-proc-macro" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "Inflector", "proc-macro-crate 1.0.0", @@ -9485,7 +8748,7 @@ dependencies = [ [[package]] name = "sp-serializer" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "serde", "serde_json", @@ -9494,96 +8757,30 @@ dependencies = [ [[package]] name = "sp-session" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "parity-scale-codec", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-staking 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-core", + "sp-runtime", + "sp-staking", + "sp-std", ] [[package]] name = "sp-staking" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "parity-scale-codec", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", -] - -[[package]] -name = "sp-staking" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "parity-scale-codec", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] - -[[package]] -name = "sp-staking" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "parity-scale-codec", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", -] - -[[package]] -name = "sp-state-machine" -version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "hash-db", - "log", - "num-traits", - "parity-scale-codec", - "parking_lot 0.11.1", - "rand 0.7.3", - "smallvec 1.6.1", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-panic-handler 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "thiserror", - "tracing", - "trie-db", - "trie-root", -] - -[[package]] -name = "sp-state-machine" -version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ - "hash-db", - "log", - "num-traits", "parity-scale-codec", - "parking_lot 0.11.1", - "rand 0.7.3", - "smallvec 1.6.1", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-panic-handler 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "thiserror", - "tracing", - "trie-db", - "trie-root", + "sp-runtime", + "sp-std", ] [[package]] name = "sp-state-machine" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "hash-db", "log", @@ -9592,11 +8789,11 @@ dependencies = [ "parking_lot 0.11.1", "rand 0.7.3", "smallvec 1.6.1", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-panic-handler 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-core", + "sp-externalities", + "sp-panic-handler", + "sp-std", + "sp-trie", "thiserror", "tracing", "trie-db", @@ -9606,83 +8803,47 @@ dependencies = [ [[package]] name = "sp-std" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" - -[[package]] -name = "sp-std" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" - -[[package]] -name = "sp-std" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" - -[[package]] -name = "sp-storage" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "impl-serde", - "parity-scale-codec", - "ref-cast", - "serde", - "sp-debug-derive 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", -] - -[[package]] -name = "sp-storage" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "impl-serde", - "parity-scale-codec", - "ref-cast", - "serde", - "sp-debug-derive 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" [[package]] name = "sp-storage" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "impl-serde", "parity-scale-codec", "ref-cast", "serde", - "sp-debug-derive 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-debug-derive", + "sp-std", ] [[package]] name = "sp-tasks" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "log", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime-interface 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-externalities", + "sp-io", + "sp-runtime-interface", + "sp-std", ] [[package]] name = "sp-timestamp" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "futures-timer 3.0.2", "log", "parity-scale-codec", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", + "sp-inherents", + "sp-runtime", + "sp-std", "thiserror", "wasm-timer", ] @@ -9690,43 +8851,7 @@ dependencies = [ [[package]] name = "sp-tracing" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "erased-serde", - "log", - "parity-scale-codec", - "parking_lot 0.10.2", - "serde", - "serde_json", - "slog", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "tracing", - "tracing-core", - "tracing-subscriber", -] - -[[package]] -name = "sp-tracing" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "erased-serde", - "log", - "parity-scale-codec", - "parking_lot 0.10.2", - "serde", - "serde_json", - "slog", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "tracing", - "tracing-core", - "tracing-subscriber", -] - -[[package]] -name = "sp-tracing" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "erased-serde", "log", @@ -9735,7 +8860,7 @@ dependencies = [ "serde", "serde_json", "slog", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-std", "tracing", "tracing-core", "tracing-subscriber", @@ -9744,72 +8869,44 @@ dependencies = [ [[package]] name = "sp-transaction-pool" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "derive_more", "futures 0.3.16", "log", "parity-scale-codec", "serde", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-blockchain", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-runtime", "thiserror", ] [[package]] name = "sp-transaction-storage-proof" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-trait", "log", "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-inherents 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-trie 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-inherents", + "sp-runtime", + "sp-std", + "sp-trie", ] [[package]] name = "sp-trie" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "hash-db", "memory-db", "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "trie-db", - "trie-root", -] - -[[package]] -name = "sp-trie" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "hash-db", - "memory-db", - "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "trie-db", - "trie-root", -] - -[[package]] -name = "sp-trie" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "hash-db", - "memory-db", - "parity-scale-codec", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-core", + "sp-std", "trie-db", "trie-root", ] @@ -9817,7 +8914,7 @@ dependencies = [ [[package]] name = "sp-utils" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "futures 0.3.16", "futures-core", @@ -9829,70 +8926,20 @@ dependencies = [ [[package]] name = "sp-version" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "impl-serde", - "parity-scale-codec", - "serde", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "sp-version-proc-macro 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", -] - -[[package]] -name = "sp-version" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "impl-serde", - "parity-scale-codec", - "serde", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-version-proc-macro 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", -] - -[[package]] -name = "sp-version" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "impl-serde", "parity-scale-codec", "serde", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", - "sp-version-proc-macro 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-runtime", + "sp-std", + "sp-version-proc-macro", ] [[package]] name = "sp-version-proc-macro" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "parity-scale-codec", - "proc-macro-crate 1.0.0", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "sp-version-proc-macro" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "parity-scale-codec", - "proc-macro-crate 1.0.0", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "sp-version-proc-macro" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "parity-scale-codec", "proc-macro-crate 1.0.0", @@ -9904,33 +8951,11 @@ dependencies = [ [[package]] name = "sp-wasm-interface" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4#1d04678e20555e623c974ee1127bc8a45abcf3d6" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "impl-trait-for-tuples 0.2.1", "parity-scale-codec", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.4)", - "wasmi", -] - -[[package]] -name = "sp-wasm-interface" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" -dependencies = [ - "impl-trait-for-tuples 0.2.1", - "parity-scale-codec", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "wasmi", -] - -[[package]] -name = "sp-wasm-interface" -version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6#1d04678e20555e623c974ee1127bc8a45abcf3d6" -dependencies = [ - "impl-trait-for-tuples 0.2.1", - "parity-scale-codec", - "sp-std 3.0.0 (git+https://github.com/paritytech/substrate?rev=1d04678e20555e623c974ee1127bc8a45abcf3d6)", + "sp-std", "wasmi", ] @@ -10072,7 +9097,7 @@ dependencies = [ [[package]] name = "substrate-frame-rpc-system" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "frame-system-rpc-runtime-api", "futures 0.3.16", @@ -10084,18 +9109,18 @@ dependencies = [ "sc-client-api", "sc-rpc-api", "serde", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-block-builder", "sp-blockchain", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-runtime", "sp-transaction-pool", ] [[package]] name = "substrate-prometheus-endpoint" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "async-std", "derive_more", @@ -10131,7 +9156,7 @@ dependencies = [ "atty", "build-helper", "cargo_metadata 0.13.1", - "sp-maybe-compressed-blob 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.7)", + "sp-maybe-compressed-blob", "tempfile", "toml", "walkdir", @@ -10794,7 +9819,7 @@ checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" [[package]] name = "try-runtime-cli" version = "0.9.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" +source = "git+https://github.com/paritytech//substrate?rev=74101dc21cfffb4c2d014fcc28edc166d5ca1b16#74101dc21cfffb4c2d014fcc28edc166d5ca1b16" dependencies = [ "frame-try-runtime", "log", @@ -10806,14 +9831,14 @@ dependencies = [ "sc-executor", "sc-service", "serde", - "sp-api 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-api", "sp-blockchain", - "sp-core 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-externalities 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-io 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-keystore 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-runtime 3.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", - "sp-state-machine 0.9.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.8)", + "sp-core", + "sp-externalities", + "sp-io", + "sp-keystore", + "sp-runtime", + "sp-state-machine", "structopt", ]