Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
70 lines (54 sloc) 2.21 KB
use rstd::prelude::*;
use support::{dispatch::Result, StorageValue, StorageMap, decl_storage, decl_module, decl_event, ensure};
use system::{self, ensure_signed};
// the module configuration trait
pub trait Trait: system::Trait {
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
}
// storage for this runtime module
decl_storage! {
trait Store for Module<T: Trait> as Template {
pub TotalSupply get(total_supply): u64 = 21000000;
pub BalanceOf get(balance_of): map T::AccountId => u64;
Init get(is_init): bool;
}
}
// events
decl_event!(
pub enum Event<T> where AccountId = <T as system::Trait>::AccountId {
// event for transfer of tokens
// from, to, value
Transfer(AccountId, AccountId, u64),
}
);
// public interface for this runtime module
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
// initialize the default event for this module
fn deposit_event<T>() = default;
// initialize the token
// transfers the total_supply amout to the caller
fn init(origin) -> Result {
let sender = ensure_signed(origin)?;
ensure!(Self::is_init() == false, "Already initialized.");
<BalanceOf<T>>::insert(sender, Self::total_supply());
<Init<T>>::put(true);
Ok(())
}
// transfer tokens from one account to another
fn transfer(_origin, to: T::AccountId, value: u64) -> Result {
let sender = ensure_signed(_origin)?;
let sender_balance = Self::balance_of(sender.clone());
ensure!(sender_balance >= value, "Not enough balance.");
let updated_from_balance = sender_balance.checked_sub(value).ok_or("overflow in calculating balance")?;
let receiver_balance = Self::balance_of(to.clone());
let updated_to_balance = receiver_balance.checked_add(value).ok_or("overflow in calculating balance")?;
// reduce sender's balance
<BalanceOf<T>>::insert(sender.clone(), updated_from_balance);
// increase receiver's balance
<BalanceOf<T>>::insert(to.clone(), updated_to_balance);
Self::deposit_event(RawEvent::Transfer(sender, to, value));
Ok(())
}
}
}
You can’t perform that action at this time.