* Start to remove the `As` bound on `SimpleArtithmetic`

This just introduces standard numeric bounds, assuming a minimum of
`u32`. Also included is a saturating from/into trait allowing ergonomic
infallible conversion when you don't care if it saturates.

* Remove As from Balances trait

* Remove As from Aura module

* Remove As from Babe module

* Expunge `As` from contract

* Council module

* Democracy

* Finality tracker

* Grandpa

* First bit of indices

* indices

* Line lengths

* session

* system

* Staking

* Square up all other uses of As.

* RHD update

* Fix build/test

* Remove As trait

* line widths

* Remove final As ref

* Update srml/staking/src/lib.rs

Co-Authored-By: Bastian Köcher <bkchr@users.noreply.github.com>

* Update core/client/src/cht.rs

Co-Authored-By: Bastian Köcher <bkchr@users.noreply.github.com>

* Update core/client/db/src/light.rs

Co-Authored-By: Bastian Köcher <bkchr@users.noreply.github.com>

* Apply suggestions from code review

Co-Authored-By: Bastian Köcher <bkchr@users.noreply.github.com>

* whitespace

* Apply suggestions from code review

Co-Authored-By: Bastian Köcher <bkchr@users.noreply.github.com>
Co-Authored-By: André Silva <andre.beat@gmail.com>

* Bring back u32 check for number on CLI
This commit is contained in:
Gavin Wood
2019-05-22 23:11:38 +01:00
committed by GitHub
parent 36987c0205
commit 3860d7c810
60 changed files with 695 additions and 491 deletions
+13 -15
View File
@@ -53,7 +53,7 @@ pub use timestamp;
use rstd::{result, prelude::*};
use srml_support::storage::StorageValue;
use srml_support::{decl_storage, decl_module};
use primitives::traits::{As, Zero};
use primitives::traits::{SaturatedConversion, Saturating, Zero, One};
use timestamp::OnTimestampSet;
#[cfg(feature = "std")]
use timestamp::TimestampInherentData;
@@ -154,7 +154,7 @@ pub trait Trait: timestamp::Trait {
decl_storage! {
trait Store for Module<T: Trait> as Aura {
/// The last timestamp.
LastTimestamp get(last) build(|_| T::Moment::sa(0)): T::Moment;
LastTimestamp get(last) build(|_| 0.into()): T::Moment;
}
}
@@ -192,43 +192,41 @@ impl AuraReport {
impl<T: Trait> Module<T> {
/// Determine the Aura slot-duration based on the Timestamp module configuration.
pub fn slot_duration() -> u64 {
pub fn slot_duration() -> T::Moment {
// we double the minimum block-period so each author can always propose within
// the majority of its slot.
<timestamp::Module<T>>::minimum_period().as_().saturating_mul(2)
<timestamp::Module<T>>::minimum_period().saturating_mul(2.into())
}
fn on_timestamp_set<H: HandleReport>(now: T::Moment, slot_duration: T::Moment) {
let last = Self::last();
<Self as Store>::LastTimestamp::put(now.clone());
if last == T::Moment::zero() {
if last.is_zero() {
return;
}
assert!(slot_duration > T::Moment::zero(), "Aura slot duration cannot be zero.");
assert!(!slot_duration.is_zero(), "Aura slot duration cannot be zero.");
let last_slot = last / slot_duration.clone();
let first_skipped = last_slot.clone() + T::Moment::sa(1);
let first_skipped = last_slot.clone() + One::one();
let cur_slot = now / slot_duration;
assert!(last_slot < cur_slot, "Only one block may be authored per slot.");
if cur_slot == first_skipped { return }
let slot_to_usize = |slot: T::Moment| { slot.as_() as usize };
let skipped_slots = cur_slot - last_slot - T::Moment::sa(1);
let skipped_slots = cur_slot - last_slot - One::one();
H::handle_report(AuraReport {
start_slot: slot_to_usize(first_skipped),
skipped: slot_to_usize(skipped_slots),
start_slot: first_skipped.saturated_into::<usize>(),
skipped: skipped_slots.saturated_into::<usize>(),
})
}
}
impl<T: Trait> OnTimestampSet<T::Moment> for Module<T> {
fn on_timestamp_set(moment: T::Moment) {
Self::on_timestamp_set::<T::HandleReport>(moment, T::Moment::sa(Self::slot_duration()))
Self::on_timestamp_set::<T::HandleReport>(moment, Self::slot_duration())
}
}
@@ -265,9 +263,9 @@ impl<T: Trait> ProvideInherent for Module<T> {
_ => return Ok(()),
};
let timestamp_based_slot = timestamp.as_() / Self::slot_duration();
let timestamp_based_slot = timestamp / Self::slot_duration();
let seal_slot = data.aura_inherent_data()?;
let seal_slot = data.aura_inherent_data()?.saturated_into();
if timestamp_based_slot == seal_slot {
Ok(())
+4 -6
View File
@@ -22,8 +22,8 @@ pub use timestamp;
use rstd::{result, prelude::*};
use srml_support::{decl_storage, decl_module};
use primitives::traits::As;
use timestamp::{OnTimestampSet, Trait};
use primitives::traits::{SaturatedConversion, Saturating};
#[cfg(feature = "std")]
use timestamp::TimestampInherentData;
use parity_codec::Decode;
@@ -116,10 +116,10 @@ decl_module! {
impl<T: Trait> Module<T> {
/// Determine the BABE slot duration based on the Timestamp module configuration.
pub fn slot_duration() -> u64 {
pub fn slot_duration() -> T::Moment {
// we double the minimum block-period so each author can always propose within
// the majority of their slot.
<timestamp::Module<T>>::minimum_period().as_().saturating_mul(2)
<timestamp::Module<T>>::minimum_period().saturating_mul(2.into())
}
}
@@ -142,10 +142,8 @@ impl<T: Trait> ProvideInherent for Module<T> {
_ => return Ok(()),
};
let timestamp_based_slot = timestamp.as_() / Self::slot_duration();
let timestamp_based_slot = (timestamp / Self::slot_duration()).saturated_into::<u64>();
let seal_slot = data.babe_inherent_data()?;
if timestamp_based_slot == seal_slot {
Ok(())
} else {
+15 -12
View File
@@ -155,7 +155,7 @@ use srml_support::traits::{
};
use srml_support::dispatch::Result;
use primitives::traits::{
Zero, SimpleArithmetic, As, StaticLookup, Member, CheckedAdd, CheckedSub,
Zero, SimpleArithmetic, StaticLookup, Member, CheckedAdd, CheckedSub,
MaybeSerializeDebug, Saturating
};
use system::{IsDeadAccount, OnNewAccount, ensure_signed};
@@ -167,7 +167,8 @@ pub use self::imbalances::{PositiveImbalance, NegativeImbalance};
pub trait Subtrait<I: Instance = DefaultInstance>: system::Trait {
/// The balance of an account.
type Balance: Parameter + Member + SimpleArithmetic + Codec + Default + Copy + MaybeSerializeDebug;
type Balance: Parameter + Member + SimpleArithmetic + Codec + Default + Copy +
MaybeSerializeDebug + From<Self::BlockNumber>;
/// A function that is invoked when the free-balance has fallen below the existential deposit and
/// has been reduced to zero.
@@ -181,7 +182,8 @@ pub trait Subtrait<I: Instance = DefaultInstance>: system::Trait {
pub trait Trait<I: Instance = DefaultInstance>: system::Trait {
/// The balance of an account.
type Balance: Parameter + Member + SimpleArithmetic + Codec + Default + Copy + MaybeSerializeDebug;
type Balance: Parameter + Member + SimpleArithmetic + Codec + Default + Copy +
MaybeSerializeDebug + From<Self::BlockNumber>;
/// A function that is invoked when the free-balance has fallen below the existential deposit and
/// has been reduced to zero.
@@ -236,10 +238,12 @@ pub struct VestingSchedule<Balance> {
pub per_block: Balance,
}
impl<Balance: SimpleArithmetic + Copy + As<u64>> VestingSchedule<Balance> {
impl<Balance: SimpleArithmetic + Copy> VestingSchedule<Balance> {
/// Amount locked at block `n`.
pub fn locked_at<BlockNumber: As<u64>>(&self, n: BlockNumber) -> Balance {
if let Some(x) = Balance::sa(n.as_()).checked_mul(&self.per_block) {
pub fn locked_at<BlockNumber>(&self, n: BlockNumber) -> Balance
where Balance: From<BlockNumber>
{
if let Some(x) = Balance::from(n).checked_mul(&self.per_block) {
self.offset.max(x) - x
} else {
Zero::zero()
@@ -276,10 +280,8 @@ decl_storage! {
/// Information regarding the vesting of a given account.
pub Vesting get(vesting) build(|config: &GenesisConfig<T, I>| {
config.vesting.iter().filter_map(|&(ref who, begin, length)| {
let begin: u64 = begin.as_();
let length: u64 = length.as_();
let begin: T::Balance = As::sa(begin);
let length: T::Balance = As::sa(length);
let begin = <T::Balance as From<T::BlockNumber>>::from(begin);
let length = <T::Balance as From<T::BlockNumber>>::from(length);
config.balances.iter()
.find(|&&(ref w, _)| w == who)
@@ -380,7 +382,8 @@ impl<T: Trait<I>, I: Instance> Module<T, I> {
/// Get the amount that is currently being vested and cannot be transferred out of this account.
pub fn vesting_balance(who: &T::AccountId) -> T::Balance {
if let Some(v) = Self::vesting(who) {
Self::free_balance(who).min(v.locked_at(<system::Module<T>>::block_number()))
Self::free_balance(who)
.min(v.locked_at::<T::BlockNumber>(<system::Module<T>>::block_number()))
} else {
Zero::zero()
}
@@ -1013,7 +1016,7 @@ where
impl<T: Trait<I>, I: Instance> MakePayment<T::AccountId> for Module<T, I> {
fn make_payment(transactor: &T::AccountId, encoded_len: usize) -> Result {
let encoded_len = <T::Balance as As<u64>>::sa(encoded_len as u64);
let encoded_len = T::Balance::from(encoded_len as u32);
let transaction_fee = Self::transaction_base_fee() + Self::transaction_byte_fee() * encoded_len;
let imbalance = Self::withdraw(
transactor,
+2 -2
View File
@@ -140,10 +140,10 @@ impl<T: Trait> AccountDb<T> for DirectAccountDb {
for (k, v) in changed.storage.into_iter() {
if let Some(value) = child::get_raw(&new_info.trie_id[..], &blake2_256(&k)) {
new_info.storage_size -= value.len() as u64;
new_info.storage_size -= value.len() as u32;
}
if let Some(value) = v {
new_info.storage_size += value.len() as u64;
new_info.storage_size += value.len() as u32;
child::put_raw(&new_info.trie_id[..], &blake2_256(&k), &value[..]);
} else {
child::kill(&new_info.trie_id[..], &blake2_256(&k));
+4 -5
View File
@@ -16,7 +16,7 @@
use crate::{GasSpent, Module, Trait, BalanceOf, NegativeImbalanceOf};
use runtime_primitives::BLOCK_FULL;
use runtime_primitives::traits::{As, CheckedMul, CheckedSub, Zero};
use runtime_primitives::traits::{CheckedMul, CheckedSub, Zero, SaturatedConversion};
use srml_support::{StorageValue, traits::{OnUnbalanced, ExistenceRequirement, WithdrawReason, Currency, Imbalance}};
#[cfg(test)]
@@ -212,7 +212,7 @@ pub fn buy_gas<T: Trait>(
// Buy the specified amount of gas.
let gas_price = <Module<T>>::gas_price();
let cost = <T::Gas as As<BalanceOf<T>>>::as_(gas_limit.clone())
let cost = gas_limit.clone().into()
.checked_mul(&gas_price)
.ok_or("overflow multiplying gas limit by price")?;
@@ -248,7 +248,7 @@ pub fn refund_unused_gas<T: Trait>(
<GasSpent<T>>::mutate(|block_gas_spent| *block_gas_spent += gas_spent);
// Refund gas left by the price it was bought at.
let refund = <T::Gas as As<BalanceOf<T>>>::as_(gas_left) * gas_meter.gas_price;
let refund = gas_left.into() * gas_meter.gas_price;
let refund_imbalance = T::Currency::deposit_creating(transactor, refund);
if let Ok(imbalance) = imbalance.offset(refund_imbalance) {
T::GasPayment::on_unbalanced(imbalance);
@@ -258,8 +258,7 @@ pub fn refund_unused_gas<T: Trait>(
/// A little handy utility for converting a value in balance units into approximate value in gas units
/// at the given gas price.
pub fn approx_gas_for_balance<T: Trait>(gas_price: BalanceOf<T>, balance: BalanceOf<T>) -> T::Gas {
let amount_in_gas: BalanceOf<T> = balance / gas_price;
<T::Gas as As<BalanceOf<T>>>::sa(amount_in_gas)
(balance / gas_price).saturated_into::<T::Gas>()
}
/// A simple utility macro that helps to match against a
+26 -26
View File
@@ -94,10 +94,9 @@ use crate::account_db::{AccountDb, DirectAccountDb};
#[cfg(feature = "std")]
use serde::{Serialize, Deserialize};
use substrate_primitives::crypto::UncheckedFrom;
use rstd::prelude::*;
use rstd::marker::PhantomData;
use rstd::{prelude::*, marker::PhantomData, convert::TryFrom};
use parity_codec::{Codec, Encode, Decode};
use runtime_primitives::traits::{Hash, As, SimpleArithmetic, Bounded, StaticLookup, Zero};
use runtime_primitives::traits::{Hash, SimpleArithmetic, Bounded, StaticLookup, Zero};
use srml_support::dispatch::{Result, Dispatchable};
use srml_support::{Parameter, StorageMap, StorageValue, decl_module, decl_event, decl_storage, storage::child};
use srml_support::traits::{OnFreeBalanceZero, OnUnbalanced, Currency};
@@ -188,7 +187,7 @@ pub struct RawAliveContractInfo<CodeHash, Balance, BlockNumber> {
/// Unique ID for the subtree encoded as a bytes vector.
pub trie_id: TrieId,
/// The size of stored value in octet.
pub storage_size: u64,
pub storage_size: u32,
/// The code associated with a given account.
pub code_hash: CodeHash,
pub rent_allowance: Balance,
@@ -199,7 +198,7 @@ pub struct RawAliveContractInfo<CodeHash, Balance, BlockNumber> {
pub struct TombstoneContractInfo<T: Trait>(T::Hash);
impl<T: Trait> TombstoneContractInfo<T> {
fn new(storage_root: Vec<u8>, storage_size: u64, code_hash: CodeHash<T>) -> Self {
fn new(storage_root: Vec<u8>, storage_size: u32, code_hash: CodeHash<T>) -> Self {
let mut buf = Vec::new();
storage_root.using_encoded(|encoded| buf.extend_from_slice(encoded));
storage_size.using_encoded(|encoded| buf.extend_from_slice(encoded));
@@ -252,7 +251,8 @@ where
}
pub type BalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;
pub type NegativeImbalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance;
pub type NegativeImbalanceOf<T> =
<<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance;
pub trait Trait: timestamp::Trait {
type Currency: Currency<Self::AccountId>;
@@ -263,8 +263,8 @@ pub trait Trait: timestamp::Trait {
/// The overarching event type.
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
// `As<u32>` is needed for wasm-utils
type Gas: Parameter + Default + Codec + SimpleArithmetic + Bounded + Copy + As<BalanceOf<Self>> + As<u64> + As<u32>;
type Gas: Parameter + Default + Codec + SimpleArithmetic + Bounded + Copy +
Into<BalanceOf<Self>> + TryFrom<BalanceOf<Self>>;
/// A function type to get the contract address given the creator.
type DetermineContractAddress: ContractAddressFor<CodeHash<Self>, Self::AccountId>;
@@ -310,10 +310,10 @@ where
pub struct DefaultDispatchFeeComputor<T: Trait>(PhantomData<T>);
impl<T: Trait> ComputeDispatchFee<T::Call, BalanceOf<T>> for DefaultDispatchFeeComputor<T> {
fn compute_dispatch_fee(call: &T::Call) -> BalanceOf<T> {
let encoded_len = call.using_encoded(|encoded| encoded.len());
let encoded_len = call.using_encoded(|encoded| encoded.len() as u32);
let base_fee = <Module<T>>::transaction_base_fee();
let byte_fee = <Module<T>>::transaction_byte_fee();
base_fee + byte_fee * <BalanceOf<T> as As<u64>>::sa(encoded_len as u64)
base_fee + byte_fee * encoded_len.into()
}
}
@@ -553,7 +553,7 @@ decl_storage! {
TombstoneDeposit get(tombstone_deposit) config(): BalanceOf<T>;
/// Size of a contract at the time of creation. This is a simple way to ensure
/// that empty contracts eventually gets deleted.
StorageSizeOffset get(storage_size_offset) config(): u64;
StorageSizeOffset get(storage_size_offset) config(): u32;
/// Price of a byte of storage per one block interval. Should be greater than 0.
RentByteFee get(rent_byte_price) config(): BalanceOf<T>;
/// The amount of funds a contract should deposit in order to offset
@@ -576,17 +576,17 @@ decl_storage! {
/// The fee to be paid for making a transaction; the per-byte portion.
TransactionByteFee get(transaction_byte_fee) config(): BalanceOf<T>;
/// The fee required to create a contract instance.
ContractFee get(contract_fee) config(): BalanceOf<T> = BalanceOf::<T>::sa(21);
ContractFee get(contract_fee) config(): BalanceOf<T> = 21.into();
/// The base fee charged for calling into a contract.
CallBaseFee get(call_base_fee) config(): T::Gas = T::Gas::sa(135);
CallBaseFee get(call_base_fee) config(): T::Gas = 135.into();
/// The base fee charged for creating a contract.
CreateBaseFee get(create_base_fee) config(): T::Gas = T::Gas::sa(175);
CreateBaseFee get(create_base_fee) config(): T::Gas = 175.into();
/// The price of one unit of gas.
GasPrice get(gas_price) config(): BalanceOf<T> = BalanceOf::<T>::sa(1);
GasPrice get(gas_price) config(): BalanceOf<T> = 1.into();
/// The maximum nesting level of a call/create stack.
MaxDepth get(max_depth) config(): u32 = 100;
/// The maximum amount of gas that could be expended per block.
BlockGasLimit get(block_gas_limit) config(): T::Gas = T::Gas::sa(10_000_000);
BlockGasLimit get(block_gas_limit) config(): T::Gas = 10_000_000.into();
/// Gas spent so far in this block.
GasSpent get(gas_spent): T::Gas;
/// Current cost schedule for contracts.
@@ -692,19 +692,19 @@ pub struct Schedule<Gas> {
pub enable_println: bool,
}
impl<Gas: As<u64>> Default for Schedule<Gas> {
impl<Gas: From<u32>> Default for Schedule<Gas> {
fn default() -> Schedule<Gas> {
Schedule {
version: 0,
put_code_per_byte_cost: Gas::sa(1),
grow_mem_cost: Gas::sa(1),
regular_op_cost: Gas::sa(1),
return_data_per_byte_cost: Gas::sa(1),
event_data_per_byte_cost: Gas::sa(1),
event_per_topic_cost: Gas::sa(1),
event_base_cost: Gas::sa(1),
sandbox_data_read_cost: Gas::sa(1),
sandbox_data_write_cost: Gas::sa(1),
put_code_per_byte_cost: 1.into(),
grow_mem_cost: 1.into(),
regular_op_cost: 1.into(),
return_data_per_byte_cost: 1.into(),
event_data_per_byte_cost: 1.into(),
event_per_topic_cost: 1.into(),
event_base_cost: 1.into(),
sandbox_data_read_cost: 1.into(),
sandbox_data_write_cost: 1.into(),
max_event_topics: 4,
max_stack_height: 64 * 1024,
max_memory_pages: 16,
+5 -4
View File
@@ -15,7 +15,8 @@
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use crate::{BalanceOf, ContractInfo, ContractInfoOf, Module, TombstoneContractInfo, Trait};
use runtime_primitives::traits::{As, Bounded, CheckedDiv, CheckedMul, Saturating, Zero};
use runtime_primitives::traits::{Bounded, CheckedDiv, CheckedMul, Saturating, Zero,
SaturatedConversion};
use srml_support::traits::{Currency, ExistenceRequirement, Imbalance, WithdrawReason};
use srml_support::StorageMap;
@@ -75,10 +76,10 @@ fn try_evict_or_and_pay_rent<T: Trait>(
let fee_per_block = {
let free_storage = balance
.checked_div(&<Module<T>>::rent_deposit_offset())
.unwrap_or(<BalanceOf<T>>::sa(0));
.unwrap_or_else(Zero::zero);
let effective_storage_size =
<BalanceOf<T>>::sa(contract.storage_size).saturating_sub(free_storage);
<BalanceOf<T>>::from(contract.storage_size).saturating_sub(free_storage);
effective_storage_size
.checked_mul(&<Module<T>>::rent_byte_price())
@@ -95,7 +96,7 @@ fn try_evict_or_and_pay_rent<T: Trait>(
let subsistence_threshold = T::Currency::minimum_balance() + <Module<T>>::tombstone_deposit();
let dues = fee_per_block
.checked_mul(&<BalanceOf<T>>::sa(blocks_passed.as_()))
.checked_mul(&blocks_passed.saturated_into::<u32>().into())
.unwrap_or(<BalanceOf<T>>::max_value());
let dues_limited = dues.min(contract.rent_allowance);
+9 -9
View File
@@ -21,8 +21,8 @@
use crate::account_db::{AccountDb, DirectAccountDb, OverlayAccountDb};
use crate::{
BalanceOf, ComputeDispatchFee, ContractAddressFor, ContractInfo, ContractInfoOf, GenesisConfig, Module,
RawAliveContractInfo, RawEvent, Trait, TrieId, TrieIdFromParentCounter, TrieIdGenerator,
BalanceOf, ComputeDispatchFee, ContractAddressFor, ContractInfo, ContractInfoOf, GenesisConfig,
Module, RawAliveContractInfo, RawEvent, Trait, TrieId, TrieIdFromParentCounter, TrieIdGenerator,
};
use assert_matches::assert_matches;
use hex_literal::*;
@@ -30,7 +30,7 @@ use parity_codec::{Decode, Encode, KeyedVec};
use runtime_io;
use runtime_io::with_externalities;
use runtime_primitives::testing::{Digest, DigestItem, Header, UintAuthorityId, H256};
use runtime_primitives::traits::{As, BlakeTwo256, IdentityLookup};
use runtime_primitives::traits::{BlakeTwo256, IdentityLookup};
use runtime_primitives::BuildStorage;
use srml_support::{
assert_ok, impl_outer_dispatch, impl_outer_event, impl_outer_origin, storage::child,
@@ -689,7 +689,7 @@ fn storage_size() {
Origin::signed(ALICE),
30_000,
100_000, HASH_SET_RENT.into(),
<Test as balances::Trait>::Balance::sa(1_000u64).encode() // rent allowance
<Test as balances::Trait>::Balance::from(1_000u32).encode() // rent allowance
));
let bob_contract = super::ContractInfoOf::<Test>::get(BOB).unwrap().get_alive().unwrap();
assert_eq!(bob_contract.storage_size, Contract::storage_size_offset() + 4);
@@ -719,7 +719,7 @@ fn deduct_blocks() {
Origin::signed(ALICE),
30_000,
100_000, HASH_SET_RENT.into(),
<Test as balances::Trait>::Balance::sa(1_000u64).encode() // rent allowance
<Test as balances::Trait>::Balance::from(1_000u32).encode() // rent allowance
));
// Check creation
@@ -812,7 +812,7 @@ fn claim_surcharge(blocks: u64, trigger_call: impl Fn() -> bool, removes: bool)
Origin::signed(ALICE),
100,
100_000, HASH_SET_RENT.into(),
<Test as balances::Trait>::Balance::sa(1_000u64).encode() // rent allowance
<Test as balances::Trait>::Balance::from(1_000u32).encode() // rent allowance
));
// Advance blocks
@@ -848,7 +848,7 @@ fn removals(trigger_call: impl Fn() -> bool) {
Origin::signed(ALICE),
100,
100_000, HASH_SET_RENT.into(),
<Test as balances::Trait>::Balance::sa(1_000u64).encode() // rent allowance
<Test as balances::Trait>::Balance::from(1_000u32).encode() // rent allowance
));
// Trigger rent must have no effect
@@ -882,7 +882,7 @@ fn removals(trigger_call: impl Fn() -> bool) {
Origin::signed(ALICE),
1_000,
100_000, HASH_SET_RENT.into(),
<Test as balances::Trait>::Balance::sa(100u64).encode() // rent allowance
<Test as balances::Trait>::Balance::from(100u32).encode() // rent allowance
));
// Trigger rent must have no effect
@@ -916,7 +916,7 @@ fn removals(trigger_call: impl Fn() -> bool) {
Origin::signed(ALICE),
50+Balances::minimum_balance(),
100_000, HASH_SET_RENT.into(),
<Test as balances::Trait>::Balance::sa(1_000u64).encode() // rent allowance
<Test as balances::Trait>::Balance::from(1_000u32).encode() // rent allowance
));
// Trigger rent must have no effect
@@ -29,7 +29,7 @@ use crate::gas::{GasMeter, Token};
use crate::wasm::{prepare, runtime::Env, PrefabWasmModule};
use crate::{CodeHash, CodeStorage, PristineCode, Schedule, Trait};
use rstd::prelude::*;
use runtime_primitives::traits::{As, CheckedMul, Hash, Bounded};
use runtime_primitives::traits::{CheckedMul, Hash, Bounded};
use srml_support::StorageMap;
/// Gas metering token that used for charging storing code into the code storage.
@@ -37,16 +37,15 @@ use srml_support::StorageMap;
/// Specifies the code length in bytes.
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
#[derive(Copy, Clone)]
pub struct PutCodeToken(u64);
pub struct PutCodeToken(u32);
impl<T: Trait> Token<T> for PutCodeToken {
type Metadata = Schedule<T::Gas>;
fn calculate_amount(&self, metadata: &Schedule<T::Gas>) -> T::Gas {
let code_len_in_gas = <T::Gas as As<u64>>::sa(self.0);
metadata
.put_code_per_byte_cost
.checked_mul(&code_len_in_gas)
.checked_mul(&self.0.into())
.unwrap_or_else(|| Bounded::max_value())
}
}
@@ -63,7 +62,7 @@ pub fn save<T: Trait>(
// The first time instrumentation is on the user. However, consequent reinstrumentation
// due to the schedule changes is on governance system.
if gas_meter
.charge(schedule, PutCodeToken(original_code.len() as u64))
.charge(schedule, PutCodeToken(original_code.len() as u32))
.is_out_of_gas()
{
return Err("there is not enough gas for storing the code");
@@ -195,7 +195,7 @@ macro_rules! define_env {
mod tests {
use parity_wasm::elements::FunctionType;
use parity_wasm::elements::ValueType;
use runtime_primitives::traits::{As, Zero};
use runtime_primitives::traits::Zero;
use sandbox::{self, ReturnValue, TypedValue};
use crate::wasm::tests::MockExt;
use crate::wasm::Runtime;
@@ -256,7 +256,7 @@ mod tests {
#[test]
fn macro_define_func() {
define_func!( <E: Ext> ext_gas (_ctx, amount: u32) => {
let amount = <<E::T as Trait>::Gas as As<u32>>::sa(amount);
let amount = <E::T as Trait>::Gas::from(amount);
if !amount.is_zero() {
Ok(())
} else {
@@ -308,7 +308,7 @@ mod tests {
define_env!(Env, <E: Ext>,
ext_gas( _ctx, amount: u32 ) => {
let amount = <<E::T as Trait>::Gas as As<u32>>::sa(amount);
let amount = <E::T as Trait>::Gas::from(amount);
if !amount.is_zero() {
Ok(())
} else {
+4 -4
View File
@@ -26,7 +26,7 @@ use parity_wasm::elements::{self, Internal, External, MemoryType, Type};
use pwasm_utils;
use pwasm_utils::rules;
use rstd::prelude::*;
use runtime_primitives::traits::As;
use runtime_primitives::traits::{UniqueSaturatedInto, SaturatedConversion};
struct ContractModule<'a, Gas: 'a> {
/// A deserialized module. The module is valid (this is Guaranteed by `new` method).
@@ -38,7 +38,7 @@ struct ContractModule<'a, Gas: 'a> {
schedule: &'a Schedule<Gas>,
}
impl<'a, Gas: 'a + As<u32> + Clone> ContractModule<'a, Gas> {
impl<'a, Gas: 'a + From<u32> + UniqueSaturatedInto<u32> + Clone> ContractModule<'a, Gas> {
/// Creates a new instance of `ContractModule`.
///
/// Returns `Err` if the `original_code` couldn't be decoded or
@@ -85,10 +85,10 @@ impl<'a, Gas: 'a + As<u32> + Clone> ContractModule<'a, Gas> {
fn inject_gas_metering(&mut self) -> Result<(), &'static str> {
let gas_rules =
rules::Set::new(
self.schedule.regular_op_cost.clone().as_(),
self.schedule.regular_op_cost.clone().saturated_into(),
Default::default(),
)
.with_grow_cost(self.schedule.grow_mem_cost.clone().as_())
.with_grow_cost(self.schedule.grow_mem_cost.clone().saturated_into())
.with_forbidden_floats();
let module = self
+10 -11
View File
@@ -27,7 +27,7 @@ use system;
use rstd::prelude::*;
use rstd::mem;
use parity_codec::{Decode, Encode};
use runtime_primitives::traits::{As, CheckedMul, CheckedAdd, Bounded};
use runtime_primitives::traits::{CheckedMul, CheckedAdd, Bounded, SaturatedConversion};
/// Enumerates all possible *special* trap conditions.
///
@@ -122,24 +122,24 @@ impl<T: Trait> Token<T> for RuntimeToken<T::Gas> {
fn calculate_amount(&self, metadata: &Schedule<T::Gas>) -> T::Gas {
use self::RuntimeToken::*;
let value = match *self {
Explicit(amount) => Some(<T::Gas as As<u32>>::sa(amount)),
Explicit(amount) => Some(amount.into()),
ReadMemory(byte_count) => metadata
.sandbox_data_read_cost
.checked_mul(&<T::Gas as As<u32>>::sa(byte_count)),
.checked_mul(&byte_count.into()),
WriteMemory(byte_count) => metadata
.sandbox_data_write_cost
.checked_mul(&<T::Gas as As<u32>>::sa(byte_count)),
.checked_mul(&byte_count.into()),
ReturnData(byte_count) => metadata
.return_data_per_byte_cost
.checked_mul(&<T::Gas as As<u32>>::sa(byte_count)),
.checked_mul(&byte_count.into()),
DepositEvent(topic_count, data_byte_count) => {
let data_cost = metadata
.event_data_per_byte_cost
.checked_mul(&<T::Gas as As<u32>>::sa(data_byte_count));
.checked_mul(&data_byte_count.into());
let topics_cost = metadata
.event_per_topic_cost
.checked_mul(&<T::Gas as As<u32>>::sa(topic_count));
.checked_mul(&topic_count.into());
data_cost
.and_then(|data_cost| {
@@ -340,7 +340,7 @@ define_env!(Env, <E: Ext>,
let nested_gas_limit = if gas == 0 {
ctx.gas_meter.gas_left()
} else {
<<E::T as Trait>::Gas as As<u64>>::sa(gas)
gas.saturated_into()
};
let ext = &mut ctx.ext;
let call_outcome = ctx.gas_meter.with_nested(nested_gas_limit, |nested_meter| {
@@ -413,7 +413,7 @@ define_env!(Env, <E: Ext>,
let nested_gas_limit = if gas == 0 {
ctx.gas_meter.gas_left()
} else {
<<E::T as Trait>::Gas as As<u64>>::sa(gas)
gas.saturated_into()
};
let ext = &mut ctx.ext;
let instantiate_outcome = ctx.gas_meter.with_nested(nested_gas_limit, |nested_meter| {
@@ -535,8 +535,7 @@ define_env!(Env, <E: Ext>,
// Load the latest block timestamp into the scratch buffer
ext_now(ctx) => {
let now: u64 = As::as_(ctx.ext.now().clone());
ctx.scratch_buf = now.encode();
ctx.scratch_buf = ctx.ext.now().encode();
Ok(())
},
+7 -7
View File
@@ -17,7 +17,7 @@
//! Council system: Handles the voting in and maintenance of council members.
use rstd::prelude::*;
use primitives::traits::{Zero, One, As, StaticLookup};
use primitives::traits::{Zero, One, StaticLookup};
use runtime_io::print;
use srml_support::{
StorageValue, StorageMap, dispatch::Result, decl_storage, decl_event, ensure,
@@ -230,7 +230,7 @@ decl_module! {
let (_, _, expiring) = Self::next_finalize().ok_or("cannot present outside of presentation period")?;
let stakes = Self::snapshoted_stakes();
let voters = Self::voters();
let bad_presentation_punishment = Self::present_slash_per_voter() * BalanceOf::<T>::sa(voters.len() as u64);
let bad_presentation_punishment = Self::present_slash_per_voter() * BalanceOf::<T>::from(voters.len() as u32);
ensure!(T::Currency::can_slash(&who, bad_presentation_punishment), "presenter must have sufficient slashable funds");
let mut leaderboard = Self::leaderboard().ok_or("leaderboard must exist while present phase active")?;
@@ -313,22 +313,22 @@ decl_storage! {
// parameters
/// How much should be locked up in order to submit one's candidacy.
pub CandidacyBond get(candidacy_bond) config(): BalanceOf<T> = BalanceOf::<T>::sa(9);
pub CandidacyBond get(candidacy_bond) config(): BalanceOf<T> = 9.into();
/// How much should be locked up in order to be able to submit votes.
pub VotingBond get(voting_bond) config(voter_bond): BalanceOf<T>;
/// The punishment, per voter, if you provide an invalid presentation.
pub PresentSlashPerVoter get(present_slash_per_voter) config(): BalanceOf<T> = BalanceOf::<T>::sa(1);
pub PresentSlashPerVoter get(present_slash_per_voter) config(): BalanceOf<T> = 1.into();
/// How many runners-up should have their approvals persist until the next vote.
pub CarryCount get(carry_count) config(): u32 = 2;
/// How long to give each top candidate to present themselves after the vote ends.
pub PresentationDuration get(presentation_duration) config(): T::BlockNumber = T::BlockNumber::sa(1000);
pub PresentationDuration get(presentation_duration) config(): T::BlockNumber = 1000.into();
/// How many vote indexes need to go by after a target voter's last vote before they can be reaped if their
/// approvals are moot.
pub InactiveGracePeriod get(inactivity_grace_period) config(inactive_grace_period): VoteIndex = 1;
/// How often (in blocks) to check for new votes.
pub VotingPeriod get(voting_period) config(approval_voting_period): T::BlockNumber = T::BlockNumber::sa(1000);
pub VotingPeriod get(voting_period) config(approval_voting_period): T::BlockNumber = 1000.into();
/// How long each position is active for.
pub TermDuration get(term_duration) config(): T::BlockNumber = T::BlockNumber::sa(5);
pub TermDuration get(term_duration) config(): T::BlockNumber = 5.into();
/// Number of accounts that should be sitting on the council.
pub DesiredSeats get(desired_seats) config(): u32;
+4 -4
View File
@@ -18,7 +18,7 @@
use rstd::prelude::*;
use rstd::borrow::Borrow;
use primitives::traits::{Hash, As, Zero};
use primitives::traits::{Hash, Zero};
use runtime_io::print;
use srml_support::dispatch::Result;
use srml_support::{StorageValue, StorageMap, IsSubType, decl_module, decl_storage, decl_event, ensure};
@@ -113,10 +113,10 @@ decl_module! {
decl_storage! {
trait Store for Module<T: Trait> as CouncilVoting {
pub CooloffPeriod get(cooloff_period) config(): T::BlockNumber = T::BlockNumber::sa(1000);
pub VotingPeriod get(voting_period) config(): T::BlockNumber = T::BlockNumber::sa(3);
pub CooloffPeriod get(cooloff_period) config(): T::BlockNumber = 1000.into();
pub VotingPeriod get(voting_period) config(): T::BlockNumber = 3.into();
/// Number of blocks by which to delay enactment of successful, non-unanimous-council-instigated referendum proposals.
pub EnactDelayPeriod get(enact_delay_period) config(): T::BlockNumber = T::BlockNumber::sa(0);
pub EnactDelayPeriod get(enact_delay_period) config(): T::BlockNumber = 0.into();
pub Proposals get(proposals) build(|_| vec![]): Vec<(T::BlockNumber, T::Hash)>; // ordered by expiry.
pub ProposalOf get(proposal_of): map T::Hash => Option<T::Proposal>;
pub ProposalVoters get(proposal_voters): map T::Hash => Vec<T::AccountId>;
+9 -9
View File
@@ -20,7 +20,7 @@
use rstd::prelude::*;
use rstd::result;
use primitives::traits::{Zero, As, Bounded};
use primitives::traits::{Zero, Bounded};
use parity_codec::{Encode, Decode};
use srml_support::{StorageValue, StorageMap, Parameter, Dispatchable, IsSubType, EnumerableStorageMap};
use srml_support::{decl_module, decl_storage, decl_event, ensure};
@@ -196,7 +196,7 @@ decl_module! {
// Indefinite lock is reduced to the maximum voting lock that could be possible.
let lock_period = Self::public_delay();
let now = <system::Module<T>>::block_number();
let locked_until = now + lock_period * T::BlockNumber::sa(d.1 as u64);
let locked_until = now + lock_period * (d.1 as u32).into();
T::Currency::set_lock(DEMOCRACY_ID, &who, Bounded::max_value(), locked_until, WithdrawReason::Transfer.into());
Self::deposit_event(RawEvent::Undelegated(who));
}
@@ -234,7 +234,7 @@ decl_storage! {
/// Those who have locked a deposit.
pub DepositOf get(deposit_of): map PropIndex => Option<(BalanceOf<T>, Vec<T::AccountId>)>;
/// How often (in blocks) new public referenda are launched.
pub LaunchPeriod get(launch_period) config(): T::BlockNumber = T::BlockNumber::sa(1000);
pub LaunchPeriod get(launch_period) config(): T::BlockNumber = 1000.into();
/// The minimum amount to be used as a deposit for a public referendum proposal.
pub MinimumDeposit get(minimum_deposit) config(): BalanceOf<T>;
/// The delay before enactment for all public referenda.
@@ -243,7 +243,7 @@ decl_storage! {
pub MaxLockPeriods get(max_lock_periods) config(): LockPeriods;
/// How often (in blocks) to check for new votes.
pub VotingPeriod get(voting_period) config(): T::BlockNumber = T::BlockNumber::sa(1000);
pub VotingPeriod get(voting_period) config(): T::BlockNumber = 1000.into();
/// The next free referendum index, aka the number of referenda started so far.
pub ReferendumCount get(referendum_count) build(|_| 0 as ReferendumIndex): ReferendumIndex;
@@ -290,7 +290,7 @@ impl<T: Trait> Module<T> {
/// Get the amount locked in support of `proposal`; `None` if proposal isn't a valid proposal
/// index.
pub fn locked_for(proposal: PropIndex) -> Option<BalanceOf<T>> {
Self::deposit_of(proposal).map(|(d, l)| d * BalanceOf::<T>::sa(l.len() as u64))
Self::deposit_of(proposal).map(|(d, l)| d * (l.len() as u32).into())
}
/// Return true if `ref_index` is an on-going referendum.
@@ -325,9 +325,9 @@ impl<T: Trait> Module<T> {
))
.map(|(bal, vote)|
if vote.is_aye() {
(bal * BalanceOf::<T>::sa(vote.multiplier() as u64), Zero::zero(), bal)
(bal * (vote.multiplier() as u32).into(), Zero::zero(), bal)
} else {
(Zero::zero(), bal * BalanceOf::<T>::sa(vote.multiplier() as u64), bal)
(Zero::zero(), bal * (vote.multiplier() as u32).into(), bal)
}
).fold((Zero::zero(), Zero::zero(), Zero::zero()), |(a, b, c), (d, e, f)| (a + d, b + e, c + f));
let (del_approve, del_against, del_capital) = Self::tally_delegation(ref_index);
@@ -361,7 +361,7 @@ impl<T: Trait> Module<T> {
.fold((Zero::zero(), Zero::zero()), |(votes_acc, balance_acc), (delegator, (_delegate, periods))| {
let lock_periods = if min_lock_periods <= periods { min_lock_periods } else { periods };
let balance = T::Currency::total_balance(&delegator);
let votes = T::Currency::total_balance(&delegator) * BalanceOf::<T>::sa(lock_periods as u64);
let votes = T::Currency::total_balance(&delegator) * (lock_periods as u32).into();
let (del_votes, del_balance) = Self::delegated_votes(ref_index, delegator, lock_periods, recursion_limit - 1);
(votes_acc + votes + del_votes, balance_acc + balance + del_balance)
})
@@ -469,7 +469,7 @@ impl<T: Trait> Module<T> {
{
// now plus: the base lock period multiplied by the number of periods this voter offered to
// lock should they win...
let locked_until = now + lock_period * T::BlockNumber::sa((vote.multiplier()) as u64);
let locked_until = now + lock_period * (vote.multiplier() as u32).into();
// ...extend their bondage until at least then.
T::Currency::extend_lock(DEMOCRACY_ID, &a, Bounded::max_value(), locked_until, WithdrawReason::Transfer.into());
}
+8 -8
View File
@@ -26,7 +26,7 @@ use inherents::{
InherentData, MakeFatalError,
};
use srml_support::StorageValue;
use primitives::traits::{As, One, Zero};
use primitives::traits::{One, Zero, SaturatedConversion};
use rstd::{prelude::*, result, cmp, vec};
use parity_codec::Decode;
use srml_system::{ensure_none, Trait as SystemTrait};
@@ -34,8 +34,8 @@ use srml_system::{ensure_none, Trait as SystemTrait};
#[cfg(feature = "std")]
use parity_codec::Encode;
const DEFAULT_WINDOW_SIZE: u64 = 101;
const DEFAULT_DELAY: u64 = 1000;
const DEFAULT_WINDOW_SIZE: u32 = 101;
const DEFAULT_DELAY: u32 = 1000;
/// The identifier for the `finalnum` inherent.
pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"finalnum";
@@ -100,9 +100,9 @@ decl_storage! {
/// The median.
Median get(median) build(|_| T::BlockNumber::zero()): T::BlockNumber;
/// The number of recent samples to keep from this chain. Default is n-100
pub WindowSize get(window_size) config(window_size): T::BlockNumber = T::BlockNumber::sa(DEFAULT_WINDOW_SIZE);
pub WindowSize get(window_size) config(window_size): T::BlockNumber = DEFAULT_WINDOW_SIZE.into();
/// The delay after which point things become suspicious.
pub ReportLatency get(report_latency) config(report_latency): T::BlockNumber = T::BlockNumber::sa(DEFAULT_DELAY);
pub ReportLatency get(report_latency) config(report_latency): T::BlockNumber = DEFAULT_DELAY.into();
/// Final hint to apply in the block. `None` means "same as parent".
Update: Option<T::BlockNumber>;
@@ -154,7 +154,7 @@ impl<T: Trait> Module<T> {
// the sample size has just been shrunk.
{
// take into account the item we haven't pushed yet.
let to_prune = (recent.len() + 1).saturating_sub(window_size.as_() as usize);
let to_prune = (recent.len() + 1).saturating_sub(window_size.saturated_into::<usize>());
for drained in recent.drain(..to_prune) {
let idx = ordered.binary_search(&drained)
@@ -188,13 +188,13 @@ impl<T: Trait> Module<T> {
}
};
let our_window_size = recent.len();
let our_window_size = recent.len() as u32;
<Self as Store>::RecentHints::put(recent);
<Self as Store>::OrderedHints::put(ordered);
<Self as Store>::Median::put(median);
if T::BlockNumber::sa(our_window_size as u64) == window_size {
if T::BlockNumber::from(our_window_size) == window_size {
let now = srml_system::Module::<T>::block_number();
let latency = Self::report_latency();
+1 -3
View File
@@ -275,8 +275,6 @@ impl<T: Trait> Module<T> {
in_blocks: T::BlockNumber,
forced: Option<T::BlockNumber>,
) -> Result {
use primitives::traits::As;
if Self::pending_change().is_none() {
let scheduled_at = system::ChainContext::<T>::default().current_height();
@@ -287,7 +285,7 @@ impl<T: Trait> Module<T> {
// only allow the next forced change when twice the window has passed since
// this one.
<NextForced<T>>::put(scheduled_at + in_blocks * T::BlockNumber::sa(2));
<NextForced<T>>::put(scheduled_at + in_blocks * 2.into());
}
<PendingChange<T>>::put(StoredPendingChange {
+34 -20
View File
@@ -18,7 +18,8 @@
#[cfg(feature = "std")]
use std::fmt;
use crate::{Member, Decode, Encode, As, Input, Output};
use rstd::convert::TryInto;
use crate::{Member, Decode, Encode, Input, Output};
/// An indices-aware address, which can be either a direct `AccountId` or
/// an index.
@@ -59,14 +60,20 @@ fn need_more_than<T: PartialOrd>(a: T, b: T) -> Option<T> {
impl<AccountId, AccountIndex> Decode for Address<AccountId, AccountIndex> where
AccountId: Member + Decode,
AccountIndex: Member + Decode + PartialOrd<AccountIndex> + Ord + As<u32> + As<u16> + As<u8> + Copy,
AccountIndex: Member + Decode + PartialOrd<AccountIndex> + Ord + From<u32> + Copy,
{
fn decode<I: Input>(input: &mut I) -> Option<Self> {
Some(match input.read_byte()? {
x @ 0x00...0xef => Address::Index(As::sa(x)),
0xfc => Address::Index(As::sa(need_more_than(0xef, u16::decode(input)?)?)),
0xfd => Address::Index(As::sa(need_more_than(0xffff, u32::decode(input)?)?)),
0xfe => Address::Index(need_more_than(As::sa(0xffffffffu32), Decode::decode(input)?)?),
x @ 0x00...0xef => Address::Index(AccountIndex::from(x as u32)),
0xfc => Address::Index(AccountIndex::from(
need_more_than(0xef, u16::decode(input)?)? as u32
)),
0xfd => Address::Index(AccountIndex::from(
need_more_than(0xffff, u32::decode(input)?)?
)),
0xfe => Address::Index(
need_more_than(0xffffffffu32.into(), Decode::decode(input)?)?
),
0xff => Address::Id(Decode::decode(input)?),
_ => return None,
})
@@ -75,7 +82,7 @@ impl<AccountId, AccountIndex> Decode for Address<AccountId, AccountIndex> where
impl<AccountId, AccountIndex> Encode for Address<AccountId, AccountIndex> where
AccountId: Member + Encode,
AccountIndex: Member + Encode + PartialOrd<AccountIndex> + Ord + As<u32> + As<u16> + As<u8> + Copy,
AccountIndex: Member + Encode + PartialOrd<AccountIndex> + Ord + Copy + From<u32> + TryInto<u32>,
{
fn encode_to<T: Output>(&self, dest: &mut T) {
match *self {
@@ -83,19 +90,26 @@ impl<AccountId, AccountIndex> Encode for Address<AccountId, AccountIndex> where
dest.push_byte(255);
dest.push(i);
}
Address::Index(i) if i > As::sa(0xffffffffu32) => {
dest.push_byte(254);
dest.push(&i);
}
Address::Index(i) if i > As::sa(0xffffu32) => {
dest.push_byte(253);
dest.push(&As::<u32>::as_(i));
}
Address::Index(i) if i >= As::sa(0xf0u32) => {
dest.push_byte(252);
dest.push(&As::<u16>::as_(i));
}
Address::Index(i) => dest.push_byte(As::<u8>::as_(i)),
Address::Index(i) => {
let maybe_u32: Result<u32, _> = i.try_into();
if let Ok(x) = maybe_u32 {
if x > 0xffff {
dest.push_byte(253);
dest.push(&x);
}
else if x >= 0xf0 {
dest.push_byte(252);
dest.push(&(x as u16));
}
else {
dest.push_byte(x as u8);
}
} else {
dest.push_byte(254);
dest.push(&i);
}
},
}
}
}
+40 -27
View File
@@ -19,10 +19,10 @@
#![cfg_attr(not(feature = "std"), no_std)]
use rstd::{prelude::*, result, marker::PhantomData};
use rstd::{prelude::*, result, marker::PhantomData, convert::TryInto};
use parity_codec::{Encode, Decode, Codec, Input, Output};
use srml_support::{StorageValue, StorageMap, Parameter, decl_module, decl_event, decl_storage};
use primitives::traits::{One, SimpleArithmetic, As, StaticLookup, Member};
use primitives::traits::{One, SimpleArithmetic, StaticLookup, Member};
use system::{IsDeadAccount, OnNewAccount};
use self::address::Address as RawAddress;
@@ -33,13 +33,13 @@ pub mod address;
mod tests;
/// Number of account IDs stored per enum set.
const ENUM_SET_SIZE: usize = 64;
const ENUM_SET_SIZE: u32 = 64;
pub type Address<T> = RawAddress<<T as system::Trait>::AccountId, <T as Trait>::AccountIndex>;
/// Turn an Id into an Index, or None for the purpose of getting
/// a hint at a possibly desired index.
pub trait ResolveHint<AccountId: Encode, AccountIndex: As<usize>> {
pub trait ResolveHint<AccountId, AccountIndex> {
/// Turn an Id into an Index, or None for the purpose of getting
/// a hint at a possibly desired index.
fn resolve_hint(who: &AccountId) -> Option<AccountIndex>;
@@ -47,9 +47,11 @@ pub trait ResolveHint<AccountId: Encode, AccountIndex: As<usize>> {
/// Simple encode-based resolve hint implemenntation.
pub struct SimpleResolveHint<AccountId, AccountIndex>(PhantomData<(AccountId, AccountIndex)>);
impl<AccountId: Encode, AccountIndex: As<usize>> ResolveHint<AccountId, AccountIndex> for SimpleResolveHint<AccountId, AccountIndex> {
impl<AccountId: Encode, AccountIndex: From<u32>>
ResolveHint<AccountId, AccountIndex> for SimpleResolveHint<AccountId, AccountIndex>
{
fn resolve_hint(who: &AccountId) -> Option<AccountIndex> {
Some(AccountIndex::sa(who.using_encoded(|e| e[0] as usize + e[1] as usize * 256)))
Some(AccountIndex::from(who.using_encoded(|e| e[0] as u32 + e[1] as u32 * 256)))
}
}
@@ -57,7 +59,7 @@ impl<AccountId: Encode, AccountIndex: As<usize>> ResolveHint<AccountId, AccountI
pub trait Trait: system::Trait {
/// Type used for storing an account's index; implies the maximum number of accounts the system
/// can hold.
type AccountIndex: Parameter + Member + Codec + Default + SimpleArithmetic + As<u8> + As<u16> + As<u32> + As<u64> + As<usize> + Copy;
type AccountIndex: Parameter + Member + Codec + Default + SimpleArithmetic + Copy;
/// Whether an account is dead or not.
type IsDeadAccount: IsDeadAccount<Self::AccountId>;
@@ -92,15 +94,18 @@ decl_storage! {
trait Store for Module<T: Trait> as Indices {
/// The next free enumeration set.
pub NextEnumSet get(next_enum_set) build(|config: &GenesisConfig<T>| {
T::AccountIndex::sa(config.ids.len() / ENUM_SET_SIZE)
(config.ids.len() as u32 / ENUM_SET_SIZE).into()
}): T::AccountIndex;
/// The enumeration sets.
pub EnumSet get(enum_set) build(|config: &GenesisConfig<T>| {
(0..(config.ids.len() + ENUM_SET_SIZE - 1) / ENUM_SET_SIZE)
(0..((config.ids.len() as u32) + ENUM_SET_SIZE - 1) / ENUM_SET_SIZE)
.map(|i| (
T::AccountIndex::sa(i),
config.ids[i * ENUM_SET_SIZE..config.ids.len().min((i + 1) * ENUM_SET_SIZE)].to_owned(),
i.into(),
config.ids[
(i * ENUM_SET_SIZE) as usize..
config.ids.len().min(((i + 1) * ENUM_SET_SIZE) as usize)
].to_owned(),
))
.collect::<Vec<_>>()
}): map T::AccountIndex => Vec<T::AccountId>;
@@ -117,7 +122,7 @@ impl<T: Trait> Module<T> {
pub fn lookup_index(index: T::AccountIndex) -> Option<T::AccountId> {
let enum_set_size = Self::enum_set_size();
let set = Self::enum_set(index / enum_set_size);
let i: usize = (index % enum_set_size).as_();
let i: usize = (index % enum_set_size).try_into().ok()?;
set.get(i).cloned()
}
@@ -125,12 +130,18 @@ impl<T: Trait> Module<T> {
pub fn can_reclaim(try_index: T::AccountIndex) -> bool {
let enum_set_size = Self::enum_set_size();
let try_set = Self::enum_set(try_index / enum_set_size);
let i = (try_index % enum_set_size).as_();
i < try_set.len() && T::IsDeadAccount::is_dead_account(&try_set[i])
let maybe_usize: Result<usize, _> = (try_index % enum_set_size).try_into();
if let Ok(i) = maybe_usize {
i < try_set.len() && T::IsDeadAccount::is_dead_account(&try_set[i])
} else {
false
}
}
/// Lookup an address to get an Id, if there's one there.
pub fn lookup_address(a: address::Address<T::AccountId, T::AccountIndex>) -> Option<T::AccountId> {
pub fn lookup_address(
a: address::Address<T::AccountId, T::AccountIndex>
) -> Option<T::AccountId> {
match a {
address::Address::Id(i) => Some(i),
address::Address::Index(i) => Self::lookup_index(i),
@@ -140,7 +151,7 @@ impl<T: Trait> Module<T> {
// PUBLIC MUTABLES (DANGEROUS)
fn enum_set_size() -> T::AccountIndex {
T::AccountIndex::sa(ENUM_SET_SIZE)
ENUM_SET_SIZE.into()
}
}
@@ -153,36 +164,38 @@ impl<T: Trait> OnNewAccount<T::AccountId> for Module<T> {
// then check to see if this account id identifies a dead account index.
let set_index = try_index / enum_set_size;
let mut try_set = Self::enum_set(set_index);
let item_index = (try_index % enum_set_size).as_();
if item_index < try_set.len() {
if T::IsDeadAccount::is_dead_account(&try_set[item_index]) {
// yup - this index refers to a dead account. can be reused.
try_set[item_index] = who.clone();
<EnumSet<T>>::insert(set_index, try_set);
if let Ok(item_index) = (try_index % enum_set_size).try_into() {
if item_index < try_set.len() {
if T::IsDeadAccount::is_dead_account(&try_set[item_index]) {
// yup - this index refers to a dead account. can be reused.
try_set[item_index] = who.clone();
<EnumSet<T>>::insert(set_index, try_set);
return
return
}
}
}
}
// insert normally as a back up
let mut set_index = next_set_index;
// defensive only: this loop should never iterate since we keep NextEnumSet up to date later.
// defensive only: this loop should never iterate since we keep NextEnumSet up to date
// later.
let mut set = loop {
let set = Self::enum_set(set_index);
if set.len() < ENUM_SET_SIZE {
if set.len() < ENUM_SET_SIZE as usize {
break set;
}
set_index += One::one();
};
let index = T::AccountIndex::sa(set_index.as_() * ENUM_SET_SIZE + set.len());
let index = set_index * enum_set_size + T::AccountIndex::from(set.len() as u32);
// update set.
set.push(who.clone());
// keep NextEnumSet up to date
if set.len() == ENUM_SET_SIZE {
if set.len() == ENUM_SET_SIZE as usize {
<NextEnumSet<T>>::put(set_index + One::one());
}
+3 -3
View File
@@ -116,7 +116,7 @@
#![cfg_attr(not(feature = "std"), no_std)]
use rstd::prelude::*;
use primitives::traits::{As, Zero, One, Convert};
use primitives::traits::{Zero, One, Convert};
use srml_support::{StorageValue, StorageMap, for_each_tuple, decl_module, decl_event, decl_storage};
use srml_support::{dispatch::Result, traits::OnFreeBalanceZero};
use system::ensure_signed;
@@ -200,9 +200,9 @@ decl_storage! {
/// The current set of validators.
pub Validators get(validators) config(): Vec<T::AccountId>;
/// Current length of the session.
pub SessionLength get(length) config(session_length): T::BlockNumber = T::BlockNumber::sa(1000);
pub SessionLength get(length) config(session_length): T::BlockNumber = 1000.into();
/// Current index of the session.
pub CurrentIndex get(current_index) build(|_| T::BlockNumber::sa(0)): T::BlockNumber;
pub CurrentIndex get(current_index) build(|_| 0.into()): T::BlockNumber;
/// Timestamp when current session started.
pub CurrentStart get(current_start) build(|_| T::Moment::zero()): T::Moment;
+15 -8
View File
@@ -247,7 +247,10 @@ use srml_support::traits::{
};
use session::OnSessionChange;
use primitives::Perbill;
use primitives::traits::{Convert, Zero, One, As, StaticLookup, CheckedSub, CheckedShl, Saturating, Bounded};
use primitives::traits::{
Convert, Zero, One, StaticLookup, CheckedSub, CheckedShl, Saturating,
Bounded, SaturatedConversion
};
#[cfg(feature = "std")]
use primitives::{Serialize, Deserialize};
use system::ensure_signed;
@@ -396,7 +399,7 @@ type NegativeImbalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::
type RawAssignment<T> = (<T as system::Trait>::AccountId, ExtendedBalance);
type Assignment<T> = (<T as system::Trait>::AccountId, ExtendedBalance, BalanceOf<T>);
type ExpoMap<T> = BTreeMap::<<T as system::Trait>::AccountId, Exposure<<T as system::Trait>::AccountId, BalanceOf<T>>>;
type ExpoMap<T> = BTreeMap<<T as system::Trait>::AccountId, Exposure<<T as system::Trait>::AccountId, BalanceOf<T>>>;
pub trait Trait: system::Trait + session::Trait {
/// The staking balance.
@@ -432,7 +435,7 @@ decl_storage! {
/// Minimum number of staking participants before emergency conditions are imposed.
pub MinimumValidatorCount get(minimum_validator_count) config(): u32 = DEFAULT_MINIMUM_VALIDATOR_COUNT;
/// The length of a staking era in sessions.
pub SessionsPerEra get(sessions_per_era) config(): T::BlockNumber = T::BlockNumber::sa(1000);
pub SessionsPerEra get(sessions_per_era) config(): T::BlockNumber = 1000.into();
/// Maximum reward, per validator, that is provided per acceptable session.
pub SessionReward get(session_reward) config(): Perbill = Perbill::from_parts(60);
/// Slash, per validator that is taken for the first time they are found to be offline.
@@ -440,7 +443,7 @@ decl_storage! {
/// Number of instances of offline reports before slashing begins for validators.
pub OfflineSlashGrace get(offline_slash_grace) config(): u32;
/// The length of the bonding duration in eras.
pub BondingDuration get(bonding_duration) config(): T::BlockNumber = T::BlockNumber::sa(12);
pub BondingDuration get(bonding_duration) config(): T::BlockNumber = 12.into();
/// 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.
@@ -867,8 +870,12 @@ impl<T: Trait> Module<T> {
if ideal_elapsed.is_zero() {
return Self::current_session_reward();
}
let per65536: u64 = (T::Moment::sa(65536u64) * ideal_elapsed.clone() / actual_elapsed.max(ideal_elapsed)).as_();
Self::current_session_reward() * <BalanceOf<T>>::sa(per65536) / <BalanceOf<T>>::sa(65536u64)
// Assumes we have 16-bits free at the top of T::Moment. Holds true for moment as seconds
// in a u64 for the forseeable future, but more correct would be to handle overflows
// explicitly.
let per65536 = T::Moment::from(65536) * ideal_elapsed.clone() / actual_elapsed.max(ideal_elapsed);
let per65536: BalanceOf<T> = per65536.saturated_into::<u32>().into();
Self::current_session_reward() * per65536 / 65536.into()
}
/// Session has just changed. We need to determine whether we pay a reward, slash and/or
@@ -901,8 +908,8 @@ impl<T: Trait> Module<T> {
Self::reward_validator(v, reward);
}
Self::deposit_event(RawEvent::Reward(reward));
let len = validators.len() as u64; // validators length can never overflow u64
let len = BalanceOf::<T>::sa(len);
let len = validators.len() as u32; // validators length can never overflow u64
let len: BalanceOf<T> = len.into();
let total_minted = reward * len;
let total_rewarded_stake = Self::slot_stake() * len;
T::OnRewardMinted::on_dilution(total_minted, total_rewarded_stake);
+5 -4
View File
@@ -77,8 +77,8 @@ use rstd::prelude::*;
#[cfg(any(feature = "std", test))]
use rstd::map;
use primitives::traits::{self, CheckEqual, SimpleArithmetic, SimpleBitOps, One, Bounded, Lookup,
Hash, Member, MaybeDisplay, EnsureOrigin, Digest as DigestT, As, CurrentHeight, BlockNumberToHash,
MaybeSerializeDebugButNotDeserialize, MaybeSerializeDebug, StaticLookup
Hash, Member, MaybeDisplay, EnsureOrigin, Digest as DigestT, CurrentHeight, BlockNumberToHash,
MaybeSerializeDebugButNotDeserialize, MaybeSerializeDebug, StaticLookup, SaturatedConversion
};
#[cfg(any(feature = "std", test))]
use primitives::traits::Zero;
@@ -311,7 +311,7 @@ decl_storage! {
/// ring buffer with the `i8` prefix being the index into the `Vec` of the oldest hash.
RandomMaterial get(random_material): (i8, Vec<T::Hash>);
/// The current block number being processed. Set by `execute_block`.
Number get(block_number) build(|_| T::BlockNumber::sa(1u64)): T::BlockNumber;
Number get(block_number) build(|_| 1.into()): T::BlockNumber;
/// Hash of the previous block.
ParentHash get(parent_hash) build(|_| hash69()): T::Hash;
/// Extrinsics root of the current block, also part of the block header.
@@ -493,7 +493,8 @@ impl<T: Trait> Module<T> {
let mut digest = <Digest<T>>::take();
let extrinsics_root = <ExtrinsicsRoot<T>>::take();
let storage_root = T::Hashing::storage_root();
let storage_changes_root = T::Hashing::storage_changes_root(parent_hash, number.as_() - 1);
let number_u64 = number.saturated_into::<u64>();
let storage_changes_root = T::Hashing::storage_changes_root(parent_hash, number_u64 - 1);
// we can't compute changes trie root earlier && put it to the Digest
// because it will include all currently existing temporaries.
+12 -10
View File
@@ -87,6 +87,7 @@
#![cfg_attr(not(feature = "std"), no_std)]
use rstd::{result, ops::{Mul, Div}, cmp};
use parity_codec::Encode;
#[cfg(feature = "std")]
use parity_codec::Decode;
@@ -94,9 +95,8 @@ use parity_codec::Decode;
use inherents::ProvideInherentData;
use srml_support::{StorageValue, Parameter, decl_storage, decl_module};
use srml_support::for_each_tuple;
use runtime_primitives::traits::{As, SimpleArithmetic, Zero};
use runtime_primitives::traits::{SimpleArithmetic, Zero, SaturatedConversion};
use system::ensure_none;
use rstd::{result, ops::{Mul, Div}, cmp};
use inherents::{RuntimeString, InherentIdentifier, ProvideInherent, IsFatalError, InherentData};
/// The identifier for the `timestamp` inherent.
@@ -252,7 +252,7 @@ decl_module! {
decl_storage! {
trait Store for Module<T: Trait> as Timestamp {
/// Current time for the current block.
pub Now get(now) build(|_| T::Moment::sa(0)): T::Moment;
pub Now get(now) build(|_| 0.into()): T::Moment;
/// Old storage item provided for compatibility. Remove after all networks upgraded.
// TODO: #2133
@@ -262,7 +262,7 @@ decl_storage! {
/// that the block production apparatus provides. Your chosen consensus system will generally
/// work with this to determine a sensible block time. e.g. For Aura, it will be double this
/// period on default settings.
pub MinimumPeriod get(minimum_period) config(): T::Moment = T::Moment::sa(3);
pub MinimumPeriod get(minimum_period) config(): T::Moment = 3.into();
/// Did the timestamp get updated in this block?
DidUpdate: bool;
@@ -297,23 +297,25 @@ impl<T: Trait> ProvideInherent for Module<T> {
const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
fn create_inherent(data: &InherentData) -> Option<Self::Call> {
let data = extract_inherent_data(data).expect("Gets and decodes timestamp inherent data");
let data: T::Moment = extract_inherent_data(data)
.expect("Gets and decodes timestamp inherent data")
.saturated_into();
let next_time = cmp::max(As::sa(data), Self::now() + <MinimumPeriod<T>>::get());
let next_time = cmp::max(data, Self::now() + <MinimumPeriod<T>>::get());
Some(Call::set(next_time.into()))
}
fn check_inherent(call: &Self::Call, data: &InherentData) -> result::Result<(), Self::Error> {
const MAX_TIMESTAMP_DRIFT: u64 = 60;
let t = match call {
Call::set(ref t) => t.clone(),
let t: u64 = match call {
Call::set(ref t) => t.clone().saturated_into::<u64>(),
_ => return Ok(()),
}.as_();
};
let data = extract_inherent_data(data).map_err(|e| InherentError::Other(e))?;
let minimum = (Self::now() + <MinimumPeriod<T>>::get()).as_();
let minimum = (Self::now() + <MinimumPeriod<T>>::get()).saturated_into::<u64>();
if t > data + MAX_TIMESTAMP_DRIFT {
Err(InherentError::Other("Timestamp too far in future to accept".into()))
} else if t < minimum {