Skip to content

Commit

Permalink
add kton storage initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
sekisamu committed Jul 24, 2019
1 parent 4d5304d commit 7c4e258
Show file tree
Hide file tree
Showing 13 changed files with 227 additions and 72 deletions.
8 changes: 8 additions & 0 deletions Cargo.lock

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

12 changes: 6 additions & 6 deletions node/cli/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,9 @@ fn staging_testnet_config_genesis() -> GenesisConfig {
vesting: vec![],
}),
kton: Some(KtonConfig {
balances: endowed_accounts.iter().cloned()
.map(|k| (k, ENDOWMENT))
.chain(initial_authorities.iter().map(|x| (x.0.clone(), ENDOWMENT)))
ring_balances: endowed_accounts.iter().cloned()
.map(|k| (k, ENDOWMENT, 12))
.chain(initial_authorities.iter().map(|x| (x.0.clone(), ENDOWMENT, 12)))
.collect(),
vesting: vec![],
sys_acc: hex!["984d592d15d930ac36e6716407fbed3f7d1e2e62bc11f8429345f8b8b0dfc107"].unchecked_into(),
Expand Down Expand Up @@ -242,9 +242,9 @@ pub fn testnet_genesis(
vesting: vec![],
}),
kton: Some(KtonConfig {
balances: endowed_accounts.iter().cloned()
.map(|k| (k, ENDOWMENT))
.chain(initial_authorities.iter().map(|x| (x.0.clone(), ENDOWMENT)))
ring_balances: endowed_accounts.iter().cloned()
.map(|k| (k, ENDOWMENT, 12))
.chain(initial_authorities.iter().map(|x| (x.0.clone(), ENDOWMENT, 12)))
.collect(),
vesting: vec![],
sys_acc: hex!["984d592d15d930ac36e6716407fbed3f7d1e2e62bc11f8429345f8b8b0dfc107"].unchecked_into(),
Expand Down
3 changes: 2 additions & 1 deletion srml/kton/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ system = { package = "srml-system", git = 'https://github.com/paritytech/substra
timestamp = { package = "srml-timestamp", git = 'https://github.com/paritytech/substrate.git', default-features = false }
substrate-primitives = { git = 'https://github.com/paritytech/substrate.git', default-features = false }
dsupport = { package = "evo-support", path = "../support", default-features = false }
runtime_io = { package = "sr-io", git = 'https://github.com/paritytech/substrate.git' }

[dev-dependencies]
runtime_io = { package = "sr-io", git = 'https://github.com/paritytech/substrate.git' }
substrate-primitives = { git = 'https://github.com/paritytech/substrate.git' }
balances = { package = "srml-balances", git = 'https://github.com/paritytech/substrate.git' }
node-runtime = { path = "../../node/runtime" }
Expand All @@ -36,5 +36,6 @@ std = [
"system/std",
"timestamp/std",
"substrate-primitives/std",
"runtime_io/std",
"dsupport/std",
]
94 changes: 42 additions & 52 deletions srml/kton/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

use parity_codec::{Codec, Decode, Encode};
use primitives::traits::{
CheckedAdd, CheckedSub, MaybeSerializeDebug, Member, Saturating, SimpleArithmetic,
StaticLookup, Zero, Bounded
Bounded, CheckedAdd, CheckedSub, MaybeSerializeDebug, Member, Saturating,
SimpleArithmetic, StaticLookup, Zero,
};

use rstd::{cmp, convert::{TryFrom, TryInto}, result};
use rstd::prelude::*;
use rstd::{cmp, result, convert::{ TryInto, TryFrom}};
use srml_support::{decl_event, decl_module, decl_storage, Parameter, StorageMap, StorageValue, ensure};
use srml_support::{decl_event, decl_module, decl_storage, ensure, Parameter, StorageMap, StorageValue};
use srml_support::dispatch::Result;
use srml_support::traits::{
Currency, ExistenceRequirement, Imbalance, LockableCurrency, LockIdentifier,
Expand All @@ -18,11 +17,14 @@ use srml_support::traits::{
use substrate_primitives::U256;
use system::ensure_signed;

#[cfg(feature = "std")]
use runtime_io::with_storage;

// customed
use dsupport::traits::SystemCurrency;
mod imbalance;
use imbalance::{NegativeImbalance, PositiveImbalance};

mod imbalance;
mod mock;
mod tests;

Expand Down Expand Up @@ -141,41 +143,40 @@ decl_storage! {
// like `existential_deposit`, but always set to 0
pub MinimumBalance get(minimum_balance): T::Balance = 0.into();

pub TotalIssuance get(total_issuance) build(|config: &GenesisConfig<T>| {
config.balances.iter().fold(Zero::zero(), |acc: T::Balance, &(_, n)| acc + n)
}): T::Balance;
pub TotalIssuance get(total_issuance) : T::Balance;

pub FreeBalance get(free_balance) build(|config: &GenesisConfig<T>| config.balances.clone()): map T::AccountId => T::Balance;
pub FreeBalance get(free_balance) : map T::AccountId => T::Balance;

pub ReservedBalance get(reserved_balance): map T::AccountId => T::Balance;

pub Locks get(locks): map T::AccountId => Vec<BalanceLock<T::Balance, T::BlockNumber>>;

pub TotalLock get(total_lock): T::Balance;

pub Vesting get(vesting) build(|config: &GenesisConfig<T>| {
config.vesting.iter().filter_map(|&(ref who, begin, 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)
.map(|&(_, balance)| {
// <= begin it should be >= balance
// >= begin+length it should be <= 0

let per_block = balance / length.max(primitives::traits::One::one());
let offset = begin * per_block + balance;

(who.clone(), VestingSchedule { offset, per_block })
})
}).collect::<Vec<_>>()
}): map T::AccountId => Option<VestingSchedule<T::Balance>>;
pub Vesting get(vesting): map T::AccountId => Option<VestingSchedule<T::Balance>>;
}
add_extra_genesis {
config(balances): Vec<(T::AccountId, T::Balance)>;
config(vesting): Vec<(T::AccountId, T::BlockNumber, T::BlockNumber)>;
}
// for ring
config(ring_balances): Vec<(T::AccountId, CurrencyOf<T>, u32)>;
config(vesting): Vec <(T::AccountId, T::BlockNumber, T::BlockNumber)>;
build( |
storage: & mut primitives::StorageOverlay,
_: & mut primitives::ChildrenStorageOverlay,
config: & GenesisConfig<T>
| {
with_storage(storage, || {
for &(ref depositor, balance, months) in &config.ring_balances {
assert!(T::Currency::free_balance(&depositor) >= balance);
let _ = <Module<T>>::deposit(
T::Origin::from(Some(depositor.clone()).into()),
balance,
months
);

}
});
});
}
}

decl_module! {
Expand Down Expand Up @@ -259,23 +260,22 @@ decl_module! {
}

impl<T: Trait> Module<T> {

fn update_deposit(who: &T::AccountId, deposit: &Deposit<CurrencyOf<T>, T::Balance, T::Moment>) {
T::Currency::set_lock(
DEPOSIT_ID,
&who,
deposit.total,
// u32::max_value().into(),
T::BlockNumber::max_value(),
WithdrawReasons::all()
WithdrawReasons::all(),
);
<DepositLedger<T>>::insert(who, deposit);
}


fn convert_to_paid_out(value: T::Balance) -> CurrencyOf<T> {
let value: u64 = value.try_into().unwrap_or_default() as u64;
let additional_reward_paid_out: CurrencyOf<T> = Self::reward_per_share() * value.try_into().unwrap_or_default();
let additional_reward_paid_out: CurrencyOf<T> = Self::reward_per_share() * value.try_into().unwrap_or_default();
additional_reward_paid_out
}

Expand All @@ -285,7 +285,7 @@ impl<T: Trait> Module<T> {

if !months.is_zero() {
let no = U256::from(67_u128).pow(U256::from(months));
let de = U256::from(66_u128). pow(U256::from(months));
let de = U256::from(66_u128).pow(U256::from(months));

let quotient = no / de;
let remainder = no % de;
Expand All @@ -295,7 +295,6 @@ impl<T: Trait> Module<T> {
} else {
None
}

}

pub fn vesting_balance(who: &T::AccountId) -> T::Balance {
Expand Down Expand Up @@ -374,7 +373,7 @@ impl<T: Trait> Currency<T::AccountId> for Module<T> {
}
let locks = Self::locks(who);
if locks.is_empty() {
return Ok(())
return Ok(());
}

let now = <system::Module<T>>::block_number();
Expand All @@ -394,7 +393,6 @@ impl<T: Trait> Currency<T::AccountId> for Module<T> {

// TODO: add fee
fn transfer(transactor: &T::AccountId, dest: &T::AccountId, value: Self::Balance) -> Result {

let from_balance = Self::free_balance(transactor);
let to_balance = Self::free_balance(dest);

Expand All @@ -416,15 +414,15 @@ impl<T: Trait> Currency<T::AccountId> for Module<T> {
// settle transactor reward
let from_should_withdraw = Self::convert_to_paid_out(value);
#[cfg(test)]
runtime_io::print(from_should_withdraw.try_into().unwrap_or_default() as u64);
runtime_io::print(from_should_withdraw.try_into().unwrap_or_default() as u64);
Self::update_reward_paid_out(transactor, from_should_withdraw, true);
// settle dest reward
Self::update_reward_paid_out(dest, from_should_withdraw, false);

Self::set_free_balance(transactor, new_from_balance);
Self::set_free_balance(dest, new_to_balance);

Self::deposit_event(RawEvent:: TokenTransfer(transactor.clone(), dest.clone(), value));
Self::deposit_event(RawEvent::TokenTransfer(transactor.clone(), dest.clone(), value));
}

Ok(())
Expand All @@ -439,7 +437,7 @@ impl<T: Trait> Currency<T::AccountId> for Module<T> {
) -> result::Result<Self::NegativeImbalance, &'static str> {
if let Some(new_balance) = Self::free_balance(who).checked_sub(&value) {
if liveness == ExistenceRequirement::KeepAlive && new_balance < Self::minimum_balance() {
return Err("payment would kill account")
return Err("payment would kill account");
}
let additional_reward_paid_out = Self::convert_to_paid_out(value);
Self::update_reward_paid_out(who, additional_reward_paid_out, true);
Expand All @@ -450,13 +448,12 @@ impl<T: Trait> Currency<T::AccountId> for Module<T> {
} else {
Err("too few free funds in account")
}

}


fn slash(
who: &T::AccountId,
value: Self::Balance
value: Self::Balance,
) -> (Self::NegativeImbalance, Self::Balance) {
let free_balance = Self::free_balance(who);
let free_slash = cmp::min(free_balance, value);
Expand All @@ -479,7 +476,7 @@ impl<T: Trait> Currency<T::AccountId> for Module<T> {

fn deposit_into_existing(
who: &T::AccountId,
value: Self::Balance
value: Self::Balance,
) -> result::Result<Self::PositiveImbalance, &'static str> {
if Self::total_balance(who).is_zero() {
return Err("beneficiary account must pre-exist");
Expand All @@ -494,7 +491,6 @@ impl<T: Trait> Currency<T::AccountId> for Module<T> {
who: &T::AccountId,
value: Self::Balance,
) -> Self::PositiveImbalance {

let (imbalance, _) = Self::make_free_balance_be(who, Self::free_balance(who) + value);

if let SignedImbalance::Positive(p) = imbalance {
Expand Down Expand Up @@ -553,7 +549,6 @@ impl<T: Trait> Currency<T::AccountId> for Module<T> {
);
NegativeImbalance::new(amount)
}

}


Expand Down Expand Up @@ -659,22 +654,20 @@ impl<T: Trait> SystemCurrency<T::AccountId, CurrencyOf<T>> for Module<T> {
fn reward_can_withdraw(who: &T::AccountId) -> CurrencyOf<T> {
let free_balance = Self::free_balance(who);
let max_should_withdraw = Self::convert_to_paid_out(free_balance);
let max_should_withdraw: u64 = max_should_withdraw.try_into().unwrap_or_default() as u64;
let max_should_withdraw: u64 = max_should_withdraw.try_into().unwrap_or_default() as u64;
let should_withdraw = i128::from(max_should_withdraw) - Self::reward_paid_out(who);
if should_withdraw <= 0 {
0.into()
} else {
u64::try_from(should_withdraw).unwrap_or_default().try_into().unwrap_or_default()
}

}

/// pay system fee with reward
fn withdraw_from_sys_reward(
who: &T::AccountId,
value: CurrencyOf<T>)
-> result::Result<(Self::NegativeImbalanceOf, Self::NegativeImbalanceOf), &'static str> {

let can_withdraw_value = Self::reward_can_withdraw(who);

let mut system_imbalance = Self::NegativeImbalanceOf::zero();
Expand Down Expand Up @@ -702,9 +695,6 @@ impl<T: Trait> SystemCurrency<T::AccountId, CurrencyOf<T>> for Module<T> {
}

Ok((system_imbalance, acc_imbalance))

}


}

8 changes: 6 additions & 2 deletions srml/kton/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,10 +182,14 @@ impl ExtBuilder {

let _ = GenesisConfig::<Test> {
sys_acc: 42,
balances: vec![],
ring_balances: vec![
(1, 10 * balance_factor, 12),
(2, 20 * balance_factor, 12),
(3, 300 * balance_factor, 12),
(4, 400 * balance_factor, 12),
],
vesting: vec![],
}.assimilate_storage(&mut t, &mut c);

t.into()

}
Expand Down
25 changes: 21 additions & 4 deletions srml/kton/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,21 @@ fn deposit_with_decimals_pre() {
Kton::deposit(Origin::signed(21), 1_000_000_000 * COIN, 36);
}

#[test]
fn build_genesis_storage_should_work() {
with_externalities(&mut ExtBuilder::default()
.existential_deposit(1).build(), || {

assert_eq!(Kton::free_balance(&1), 1 * COIN);
assert_eq!(Kton::free_balance(&2), 2 * COIN);
assert_eq!(Kton::free_balance(&3), 30 * COIN);
assert_eq!(Kton::free_balance(&4), 40 * COIN);

assert_eq!(Kton::total_issuance(), (40 + 30 + 2 + 1) * COIN);
});

}

#[test]
fn ext_builer_should_work() {
// test existential_deposit setting
Expand Down Expand Up @@ -79,11 +94,12 @@ fn reward_per_share_not_zero() {

// acc 91 and 92 deposit 10k ring for 12 months
// in return, acc 91 and 92 will get 1 kton
let old_total_issuance = Kton::total_issuance();
Kton::deposit(Origin::signed(91), 10_000 * COIN, 12);
Kton::deposit(Origin::signed(92), 10_000 * COIN, 12);
assert_eq!(Kton::total_issuance(), 2 * COIN);
assert_eq!(Kton::total_issuance(), old_total_issuance + 2 * COIN);

Kton::reward_to_pot(6000 * COIN);
Kton::reward_to_pot(225000 * COIN);
assert_eq!(Kton::reward_per_share(), 3000);
}

Expand Down Expand Up @@ -124,8 +140,9 @@ fn transfer_should_work() {

// new things happen!
// reward_per_share now change to
Kton::reward_to_pot(3000 * COIN);
assert_eq!(Ring::free_balance(&Kton::sys_acc()), 9000 * COIN);
assert_eq!(Kton::total_issuance(), 76 * COIN);
Kton::reward_to_pot(76000 * COIN);
assert_eq!(Ring::free_balance(&Kton::sys_acc()), 301000 * COIN);
assert_eq!(Kton::reward_per_share(), 4000);
assert_eq!(Kton::reward_can_withdraw(&93), 1000 * COIN);

Expand Down

0 comments on commit 7c4e258

Please sign in to comment.