Skip to content

Commit

Permalink
more type safe currency unit calculation (#423)
Browse files Browse the repository at this point in the history
  • Loading branch information
hussein-aitlahcen committed Jan 5, 2022
1 parent a150c48 commit 8e570a1
Show file tree
Hide file tree
Showing 12 changed files with 78 additions and 88 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 9 additions & 6 deletions frame/composable-traits/src/currency.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use core::ops::Div;

use codec::FullCodec;
use frame_support::pallet_prelude::*;
use scale_info::TypeInfo;
Expand All @@ -6,21 +8,22 @@ use sp_std::fmt::Debug;

pub type Exponent = u32;

/// A asset that can be priced.
pub trait PriceableAsset
where
Self: Copy,
{
/// if currency has `decimals` of 3, than it will return
fn decimals(&self) -> Exponent;
fn unit<T: From<u64>>(&self) -> T {
T::from(10_u64.pow(self.decimals() as u32))
T::from(10_u64.pow(self.decimals()))
}
fn milli<T: From<u64> + Div<Output = T>>(&self) -> T {
self.unit::<T>() / T::from(1000_u64)
}

/// Return the decimals of an asset.
fn decimals(self) -> Exponent;
}

impl PriceableAsset for u128 {
fn decimals(self) -> Exponent {
fn decimals(&self) -> Exponent {
0
}
}
Expand Down
2 changes: 1 addition & 1 deletion frame/dutch-auction/src/mock/currency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ impl Default for CurrencyId {
}

impl PriceableAsset for CurrencyId {
fn decimals(self) -> composable_traits::currency::Exponent {
fn decimals(&self) -> composable_traits::currency::Exponent {
match self {
CurrencyId::PICA => 0,
CurrencyId::BTC => 8,
Expand Down
4 changes: 2 additions & 2 deletions frame/lending/src/mocks/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{self as pallet_lending, *};
use composable_traits::{
currency::{DynamicCurrencyId, PriceableAsset},
currency::{DynamicCurrencyId, Exponent, PriceableAsset},
defi::DeFiComposableConfig,
governance::{GovernanceRegistry, SignedRawOrigin},
};
Expand Down Expand Up @@ -95,7 +95,7 @@ impl Default for MockCurrencyId {
}

impl PriceableAsset for MockCurrencyId {
fn decimals(self) -> composable_traits::currency::Exponent {
fn decimals(&self) -> Exponent {
match self {
MockCurrencyId::PICA => 0,
MockCurrencyId::BTC => 8,
Expand Down
7 changes: 3 additions & 4 deletions node/src/chain_spec.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use common::{AccountId, AuraId, Balance};
use common::{AccountId, AuraId};
use cumulus_primitives_core::ParaId;
use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup, Properties};
use sc_service::ChainType;
Expand All @@ -10,7 +10,6 @@ pub mod picasso;
// Parachin ID
const PARA_ID: ParaId = ParaId::new(2000);

const PICASSO_ED: Balance = picasso_runtime::EXISTENTIAL_DEPOSIT;
/// The extensions for the [`ChainSpec`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)]
#[serde(deny_unknown_fields)]
Expand Down Expand Up @@ -111,7 +110,7 @@ pub fn picasso_dev() -> picasso::ChainSpec {
],
dev_accounts(),
PARA_ID,
PICASSO_ED,
picasso_runtime::ExistentialDeposit::get(),
)
},
vec![],
Expand Down Expand Up @@ -153,7 +152,7 @@ pub fn composable_dev() -> composable::ChainSpec {
],
dev_accounts(),
PARA_ID,
PICASSO_ED,
picasso_runtime::ExistentialDeposit::get(),
)
},
vec![],
Expand Down
3 changes: 2 additions & 1 deletion runtime/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-li
orml-tokens = { git = "https://github.com/open-web3-stack/open-runtime-module-library", rev = "17a791edf431d7d7aee1ea3dfaeeb7bc21944301" }
sudo = { package = "pallet-sudo", git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.13", default-features = false }
num-traits = { version = "0.2.14", default-features = false }
composable-traits = { path = "../../frame/composable-traits" , default-features = false}

[features]
default = ["std"]
Expand All @@ -53,5 +54,5 @@ std = [
"crowdloan-bonus/std",
"treasury/std",
"polkadot-primitives/std",
"scale-info/std",
"scale-info/std",
]
5 changes: 3 additions & 2 deletions runtime/common/src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,9 @@ where
#[cfg(test)]
mod tests {
use super::*;
use crate::{constants::PICA, Balance, BlockNumber, DAYS};
use crate::{Balance, BlockNumber, DAYS};
use collator_selection::IdentityCollator;
use composable_traits::currency::PriceableAsset;
use frame_support::{
ord_parameter_types, parameter_types,
traits::{Everything, FindAuthor, ValidatorRegistration},
Expand Down Expand Up @@ -241,7 +242,7 @@ mod tests {
/// percentage of proposal that most be bonded by the proposer
pub const ProposalBond: Permill = Permill::from_percent(5);
// TODO: rationale?
pub const ProposalBondMinimum: Balance = 5 * PICA;
pub ProposalBondMinimum: Balance = 5 * CurrencyId::PICA.unit::<Balance>();
pub const SpendPeriod: BlockNumber = 7 * DAYS;
pub const Burn: Permill = Permill::from_percent(0);

Expand Down
7 changes: 1 addition & 6 deletions runtime/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ mod types {

/// Common constants of statemint and statemine
mod constants {
use super::types::{AccountId, Balance, BlockNumber, CouncilInstance};
use super::types::{AccountId, BlockNumber, CouncilInstance};
use frame_support::weights::{constants::WEIGHT_PER_SECOND, Weight};
use frame_system::{EnsureOneOf, EnsureRoot};
use sp_core::u32_trait::{_1, _2};
Expand All @@ -77,11 +77,6 @@ mod constants {
pub const HOURS: BlockNumber = MINUTES * 60;
pub const DAYS: BlockNumber = HOURS * 24;

// PICA = 12 decimals
pub const PICA: Balance = 1_000_000_000_000;
pub const MILLI_PICA: Balance = PICA / 1_000;
pub const MICRO_PICA: Balance = MILLI_PICA / 1_000;

/// We assume that ~5% of the block weight is consumed by `on_initialize` handlers. This is
/// used to limit the maximal weight of a single extrinsic.
// TODO changed to be more in line with statemine
Expand Down
28 changes: 13 additions & 15 deletions runtime/composable/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
use common::{
impls::DealWithFees, AccountId, AccountIndex, Address, Amount, AuraId, Balance, BlockNumber,
CouncilInstance, EnsureRootOrHalfCouncil, Hash, Signature, AVERAGE_ON_INITIALIZE_RATIO, DAYS,
HOURS, MAXIMUM_BLOCK_WEIGHT, MILLI_PICA, NORMAL_DISPATCH_RATIO, PICA, SLOT_DURATION,
HOURS, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO, SLOT_DURATION,
};
use composable_traits::currency::PriceableAsset;
use orml_traits::parameter_type_with_key;
use primitives::currency::CurrencyId;
use sp_api::impl_runtime_apis;
Expand Down Expand Up @@ -218,12 +219,9 @@ impl timestamp::Config for Runtime {
type WeightInfo = weights::timestamp::WeightInfo<Runtime>;
}

/// minimum account balance is given as 0.1 PICA ~ 100 MILLI_PICA
pub const EXISTENTIAL_DEPOSIT: Balance = 100 * MILLI_PICA;

parameter_types! {
/// Minimum amount an account has to hold to stay in state.
pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
pub ExistentialDeposit: Balance = 100 * CurrencyId::PICA.milli::<Balance>();
/// Max locks that can be placed on an account. Capped for storage
/// concerns.
pub const MaxLocks: u32 = 50;
Expand All @@ -245,7 +243,7 @@ impl balances::Config for Runtime {

parameter_types! {
/// 1 milli-pica/byte should be fine
pub const TransactionByteFee: Balance = MILLI_PICA;
pub TransactionByteFee: Balance = CurrencyId::PICA.milli::<Balance>();

// 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.
Expand All @@ -266,7 +264,7 @@ pub struct WeightToFee;
impl WeightToFeePolynomial for WeightToFee {
type Balance = Balance;
fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
let p = MILLI_PICA;
let p = CurrencyId::PICA.milli::<Balance>();
let q = 10 * Balance::from(ExtrinsicBaseWeight::get());
smallvec::smallvec![WeightToFeeCoefficient {
degree: 1,
Expand Down Expand Up @@ -294,7 +292,7 @@ impl sudo::Config for Runtime {

parameter_types! {
/// Deposit required to get an index.
pub const IndexDeposit: Balance = 100 * PICA;
pub IndexDeposit: Balance = 100 * CurrencyId::PICA.unit::<Balance>();
}

impl indices::Config for Runtime {
Expand Down Expand Up @@ -501,7 +499,7 @@ parameter_types! {
/// percentage of proposal that most be bonded by the proposer
pub const ProposalBond: Permill = Permill::from_percent(5);
// TODO: rationale?
pub const ProposalBondMinimum: Balance = 5 * PICA;
pub ProposalBondMinimum: Balance = 5 * CurrencyId::PICA.unit::<Balance>();
pub const SpendPeriod: BlockNumber = 7 * DAYS;
pub const Burn: Permill = Permill::from_percent(0);

Expand Down Expand Up @@ -586,11 +584,11 @@ parameter_types! {
pub const VotingPeriod: BlockNumber = 5 * DAYS;
pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS;

pub MinimumDeposit: Balance = 100 * PICA;
pub MinimumDeposit: Balance = 100 * CurrencyId::PICA.unit::<Balance>();
pub const EnactmentPeriod: BlockNumber = 2 * DAYS;
pub const CooloffPeriod: BlockNumber = 7 * DAYS;
// TODO: prod value
pub PreimageByteDeposit: Balance = MILLI_PICA;
pub PreimageByteDeposit: Balance = CurrencyId::PICA.milli::<Balance>();
pub const InstantAllowed: bool = true;
pub const MaxVotes: u32 = 100;
pub const MaxProposals: u32 = 100;
Expand Down Expand Up @@ -635,10 +633,10 @@ impl democracy::Config for Runtime {

parameter_types! {
pub const MaxStrategies: usize = 255;
pub const NativeAssetId: CurrencyId = CurrencyId::PICA;
pub const CreationDeposit: Balance = 10 * PICA;
pub const VaultExistentialDeposit: Balance = 1000 * PICA;
pub const RentPerBlock: Balance = MILLI_PICA;
pub NativeAssetId: CurrencyId = CurrencyId::PICA;
pub CreationDeposit: Balance = 10 * CurrencyId::PICA.unit::<Balance>();
pub VaultExistentialDeposit: Balance = 1000 * CurrencyId::PICA.unit::<Balance>();
pub RentPerBlock: Balance = CurrencyId::PICA.milli::<Balance>();
pub const VaultMinimumDeposit: Balance = 10_000;
pub const VaultMinimumWithdrawal: Balance = 10_000;
pub const VaultPalletId: PalletId = PalletId(*b"cubic___");
Expand Down
40 changes: 19 additions & 21 deletions runtime/dali/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ mod xcmp;
use common::{
impls::DealWithFees, AccountId, AccountIndex, Address, Amount, AuraId, Balance, BlockNumber,
CouncilInstance, EnsureRootOrHalfCouncil, Hash, Signature, AVERAGE_ON_INITIALIZE_RATIO, DAYS,
HOURS, MAXIMUM_BLOCK_WEIGHT, MILLI_PICA, NORMAL_DISPATCH_RATIO, PICA, SLOT_DURATION,
HOURS, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO, SLOT_DURATION,
};
use composable_traits::currency::PriceableAsset;
use orml_traits::parameter_type_with_key;
use primitives::currency::CurrencyId;
use sp_api::impl_runtime_apis;
Expand Down Expand Up @@ -199,12 +200,12 @@ impl aura::Config for Runtime {
impl cumulus_pallet_aura_ext::Config for Runtime {}

parameter_types! {
pub const BasicDeposit: Balance = 8 * PICA;
pub const FieldDeposit: Balance = 256 * MILLI_PICA;
pub BasicDeposit: Balance = 8 * CurrencyId::PICA.unit::<Balance>();
pub FieldDeposit: Balance = 256 * CurrencyId::PICA.milli::<Balance>();
pub const MaxAdditionalFields: u32 = 32;
pub const MaxRegistrars: u32 = 8;
pub const MaxSubAccounts: u32 = 32;
pub const SubAccountDeposit: Balance = 2 * PICA;
pub SubAccountDeposit: Balance = 2 * CurrencyId::PICA.unit::<Balance>();
}

impl identity::Config for Runtime {
Expand All @@ -223,8 +224,8 @@ impl identity::Config for Runtime {
}

parameter_types! {
pub const DepositBase: u64 = PICA as u64;
pub const DepositFactor: u64 = 32 * MILLI_PICA as u64;
pub DepositBase: u64 = CurrencyId::PICA.unit();
pub DepositFactor: u64 = 32 * CurrencyId::PICA.milli::<u64>();
pub const MaxSignatories: u16 = 5;
}

Expand Down Expand Up @@ -253,12 +254,9 @@ impl timestamp::Config for Runtime {
type WeightInfo = weights::timestamp::WeightInfo<Runtime>;
}

/// minimum account balance is given as 0.1 PICA ~ 100 MILLI_PICA
pub const EXISTENTIAL_DEPOSIT: Balance = 100 * MILLI_PICA;

parameter_types! {
/// Minimum amount an account has to hold to stay in state.
pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
pub ExistentialDeposit: Balance = 100 * CurrencyId::PICA.milli::<Balance>();
/// Max locks that can be placed on an account. Capped for storage
/// concerns.
pub const MaxLocks: u32 = 50;
Expand All @@ -280,7 +278,7 @@ impl balances::Config for Runtime {

parameter_types! {
/// 1 milli-pica/byte should be fine
pub const TransactionByteFee: Balance = MILLI_PICA;
pub TransactionByteFee: Balance = CurrencyId::PICA.milli::<Balance>();

// 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.
Expand All @@ -301,7 +299,7 @@ pub struct WeightToFee;
impl WeightToFeePolynomial for WeightToFee {
type Balance = Balance;
fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
let p = MILLI_PICA;
let p = CurrencyId::PICA.milli::<Balance>();
let q = 10 * Balance::from(ExtrinsicBaseWeight::get());
smallvec::smallvec![WeightToFeeCoefficient {
degree: 1,
Expand Down Expand Up @@ -329,7 +327,7 @@ impl sudo::Config for Runtime {

parameter_types! {
/// Deposit required to get an index.
pub const IndexDeposit: Balance = 100 * PICA;
pub IndexDeposit: Balance = 100 * CurrencyId::PICA.unit::<Balance>();
}

impl indices::Config for Runtime {
Expand Down Expand Up @@ -407,7 +405,7 @@ parameter_types! {
pub const StalePrice: BlockNumber = 5;

/// TODO: discuss with omar/cosmin
pub const MinStake: Balance = 1000 * PICA;
pub MinStake: Balance = 1000 * CurrencyId::PICA.unit::<Balance>();
// Shouldn't this be a ratio based on locked amount?
pub const SlashAmount: Balance = 5;
pub const MaxAnswerBound: u32 = 25;
Expand Down Expand Up @@ -569,7 +567,7 @@ parameter_types! {
/// percentage of proposal that most be bonded by the proposer
pub const ProposalBond: Permill = Permill::from_percent(5);
// TODO: rationale?
pub const ProposalBondMinimum: Balance = 5 * PICA;
pub ProposalBondMinimum: Balance = 5 * CurrencyId::PICA.unit::<Balance>();
pub const SpendPeriod: BlockNumber = 7 * DAYS;
pub const Burn: Permill = Permill::from_percent(0);

Expand Down Expand Up @@ -654,11 +652,11 @@ parameter_types! {
pub const VotingPeriod: BlockNumber = 5 * DAYS;
pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS;

pub MinimumDeposit: Balance = 100 * PICA;
pub MinimumDeposit: Balance = 100 * CurrencyId::PICA.unit::<Balance>();
pub const EnactmentPeriod: BlockNumber = 2 * DAYS;
pub const CooloffPeriod: BlockNumber = 7 * DAYS;
// TODO: prod value
pub PreimageByteDeposit: Balance = MILLI_PICA;
pub PreimageByteDeposit: Balance = CurrencyId::PICA.milli::<Balance>();
pub const InstantAllowed: bool = true;
pub const MaxVotes: u32 = 100;
pub const MaxProposals: u32 = 100;
Expand Down Expand Up @@ -703,10 +701,10 @@ impl democracy::Config for Runtime {

parameter_types! {
pub const MaxStrategies: usize = 255;
pub const NativeAssetId: CurrencyId = CurrencyId::PICA;
pub const CreationDeposit: Balance = 10 * PICA;
pub const VaultExistentialDeposit: Balance = 1000 * PICA;
pub const RentPerBlock: Balance = MILLI_PICA;
pub NativeAssetId: CurrencyId = CurrencyId::PICA;
pub CreationDeposit: Balance = 10 * CurrencyId::PICA.unit::<Balance>();
pub VaultExistentialDeposit: Balance = 1000 * CurrencyId::PICA.unit::<Balance>();
pub RentPerBlock: Balance = CurrencyId::PICA.milli::<Balance>();
pub const VaultMinimumDeposit: Balance = 10_000;
pub const VaultMinimumWithdrawal: Balance = 10_000;
pub const VaultPalletId: PalletId = PalletId(*b"cubic___");
Expand Down

0 comments on commit 8e570a1

Please sign in to comment.