difftreelog
Code style update
in: master
9 files changed
node/src/cli.rsdiffbeforeafterboth--- a/node/src/cli.rs
+++ b/node/src/cli.rs
@@ -3,9 +3,9 @@
#[derive(Debug, StructOpt)]
pub struct Cli {
- #[structopt(subcommand)]
- pub subcommand: Option<Subcommand>,
+ #[structopt(subcommand)]
+ pub subcommand: Option<Subcommand>,
- #[structopt(flatten)]
- pub run: RunCmd,
+ #[structopt(flatten)]
+ pub run: RunCmd,
}
node/src/command.rsdiffbeforeafterboth--- a/node/src/command.rs
+++ b/node/src/command.rs
@@ -21,61 +21,57 @@
use sc_cli::SubstrateCli;
impl SubstrateCli for Cli {
- fn impl_name() -> &'static str {
- "Substrate Node"
- }
+ fn impl_name() -> &'static str {
+ "Substrate Node"
+ }
- fn impl_version() -> &'static str {
- env!("SUBSTRATE_CLI_IMPL_VERSION")
- }
+ fn impl_version() -> &'static str {
+ env!("SUBSTRATE_CLI_IMPL_VERSION")
+ }
- fn description() -> &'static str {
- env!("CARGO_PKG_DESCRIPTION")
- }
+ fn description() -> &'static str {
+ env!("CARGO_PKG_DESCRIPTION")
+ }
- fn author() -> &'static str {
- env!("CARGO_PKG_AUTHORS")
- }
+ fn author() -> &'static str {
+ env!("CARGO_PKG_AUTHORS")
+ }
- fn support_url() -> &'static str {
- "support.anonymous.an"
- }
+ fn support_url() -> &'static str {
+ "support.anonymous.an"
+ }
- fn copyright_start_year() -> i32 {
- 2017
- }
+ fn copyright_start_year() -> i32 {
+ 2017
+ }
- fn executable_name() -> &'static str {
- env!("CARGO_PKG_NAME")
- }
+ fn executable_name() -> &'static str {
+ env!("CARGO_PKG_NAME")
+ }
- fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
- Ok(match id {
- "dev" => Box::new(chain_spec::development_config()),
- "" | "local" => Box::new(chain_spec::local_testnet_config()),
- path => Box::new(chain_spec::ChainSpec::from_json_file(
- std::path::PathBuf::from(path),
- )?),
- })
- }
+ fn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {
+ Ok(match id {
+ "dev" => Box::new(chain_spec::development_config()),
+ "" | "local" => Box::new(chain_spec::local_testnet_config()),
+ path => Box::new(chain_spec::ChainSpec::from_json_file(
+ std::path::PathBuf::from(path),
+ )?),
+ })
+ }
}
/// Parse and run command line arguments
pub fn run() -> sc_cli::Result<()> {
- let cli = Cli::from_args();
+ let cli = Cli::from_args();
- match &cli.subcommand {
- Some(subcommand) => {
- let runner = cli.create_runner(subcommand)?;
- runner.run_subcommand(subcommand, |config| Ok(new_full_start!(config).0))
- }
- None => {
- let runner = cli.create_runner(&cli.run)?;
- runner.run_node(
- service::new_light,
- service::new_full,
- nft_runtime::VERSION
- )
- }
- }
-}
\ No newline at end of file
+ match &cli.subcommand {
+ Some(subcommand) => {
+ let runner = cli.create_runner(subcommand)?;
+ runner.run_subcommand(subcommand, |config| Ok(new_full_start!(config).0))
+ }
+ None => {
+ let runner = cli.create_runner(&cli.run)?;
+ runner.run_node(service::new_light, service::new_full, nft_runtime::VERSION)
+ }
+ }
+}
node/src/main.rsdiffbeforeafterboth--- a/node/src/main.rs
+++ b/node/src/main.rs
@@ -8,5 +8,5 @@
mod command;
fn main() -> sc_cli::Result<()> {
- command::run()
+ command::run()
}
node/src/service.rsdiffbeforeafterboth--- a/node/src/service.rs
+++ b/node/src/service.rs
@@ -188,7 +188,7 @@
prometheus_registry: service.prometheus_registry(),
shared_voter_state: SharedVoterState::empty(),
};
-
+
// the GRANDPA voter task is considered infallible, i.e.
// if it fails we take down the service with it.
service.spawn_essential_task_handle().spawn_blocking(
pallets/nft/src/lib.rsdiffbeforeafterboth--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -2,34 +2,37 @@
/// For more guidance on Substrate FRAME, see the example pallet
/// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs
-
use codec::{Decode, Encode};
pub use frame_support::{
- decl_event, decl_module, decl_storage,
- construct_runtime, parameter_types,
- traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason, Imbalance},
+ construct_runtime, decl_event, decl_module, decl_storage,
+ dispatch::DispatchResult,
+ ensure, parameter_types,
+ traits::{
+ Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,
+ Randomness, WithdrawReason,
+ },
weights::{
- DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
- IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,
+ constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
+ DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,
+ WeightToFeePolynomial,
},
- StorageValue,
- dispatch::DispatchResult,
- IsSubType,
- ensure
+ IsSubType, StorageValue,
};
use frame_system::{self as system, ensure_signed};
use sp_runtime::sp_std::prelude::Vec;
-use sp_std::prelude::*;
use sp_runtime::{
- FixedU128, FixedPointOperand,
- transaction_validity::{
- TransactionPriority, ValidTransaction, InvalidTransaction, TransactionValidityError, TransactionValidity
- },
- traits::{
- Saturating, Dispatchable, DispatchInfoOf, PostDispatchInfoOf, SignedExtension, Zero, SaturatedConversion,
- },
+ traits::{
+ DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SaturatedConversion, Saturating,
+ SignedExtension, Zero,
+ },
+ transaction_validity::{
+ InvalidTransaction, TransactionPriority, TransactionValidity, TransactionValidityError,
+ ValidTransaction,
+ },
+ FixedPointOperand, FixedU128,
};
+use sp_std::prelude::*;
#[cfg(test)]
mod mock;
@@ -45,11 +48,11 @@
// decimal points
Fungible(u32),
// custom data size and decimal points
- ReFungible(u32, u32),
+ ReFungible(u32, u32),
}
impl Into<u8> for CollectionMode {
- fn into(self) -> u8{
+ fn into(self) -> u8 {
match self {
CollectionMode::Invalid => 0,
CollectionMode::NFT(_) => 1,
@@ -62,17 +65,25 @@
#[derive(Encode, Decode, Debug, Clone, PartialEq)]
pub enum AccessMode {
Normal,
- WhiteList,
+ WhiteList,
}
-impl Default for AccessMode { fn default() -> Self { Self::Normal } }
+impl Default for AccessMode {
+ fn default() -> Self {
+ Self::Normal
+ }
+}
-impl Default for CollectionMode { fn default() -> Self { Self::Invalid } }
+impl Default for CollectionMode {
+ fn default() -> Self {
+ Self::Invalid
+ }
+}
#[derive(Encode, Decode, Default, Clone, PartialEq)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct Ownership<AccountId> {
pub owner: AccountId,
- pub fraction: u128
+ pub fraction: u128,
}
#[derive(Encode, Decode, Default, Clone, PartialEq)]
@@ -87,7 +98,7 @@
pub token_prefix: Vec<u8>, // 16 include null escape char
pub custom_data_size: u32,
pub offchain_schema: Vec<u8>,
- pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender
+ pub sponsor: AccountId, // Who pays fees. If set to default address, the fees are applied to the transaction sender
pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship
}
@@ -126,24 +137,22 @@
#[cfg_attr(feature = "std", derive(Debug))]
pub struct ApprovePermissions<AccountId> {
pub approved: AccountId,
- pub amount: u64
+ pub amount: u64,
}
#[derive(Encode, Decode, Default, Clone, PartialEq)]
#[cfg_attr(feature = "std", derive(Debug))]
-pub struct VestingItem<AccountId, Moment>
-{
+pub struct VestingItem<AccountId, Moment> {
pub sender: AccountId,
pub recipient: AccountId,
pub collection_id: u64,
pub item_id: u64,
pub amount: u64,
- pub vesting_date: Moment
+ pub vesting_date: Moment,
}
pub trait Trait: system::Trait {
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
-
}
decl_storage! {
@@ -222,7 +231,7 @@
};
// check params
- ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4");
+ ensure!(decimal_points <= 4, "decimal_points parameter must be lower than 4");
let mut name = collection_name.to_vec();
name.push(0);
@@ -377,7 +386,7 @@
Ok(())
}
-
+
#[weight = 0]
pub fn create_item(origin, collection_id: u64, properties: Vec<u8>, owner: T::AccountId) -> DispatchResult {
@@ -385,8 +394,7 @@
let target_collection = <Collection<T>>::get(collection_id);
Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;
- // TODO: implement other modes
- match target_collection.mode
+ match target_collection.mode
{
CollectionMode::NFT(_) => {
@@ -399,9 +407,9 @@
owner: owner,
data: properties,
};
-
+
Self::add_nft_item(item)?;
-
+
},
CollectionMode::Fungible(_) => {
@@ -413,7 +421,7 @@
owner: owner,
value: (10 as u128).pow(target_collection.decimal_points)
};
-
+
Self::add_fungible_item(item)?;
},
CollectionMode::ReFungible(_, _) => {
@@ -430,7 +438,7 @@
owner: owner_list,
data: properties
};
-
+
Self::add_refungible_item(item)?;
},
_ => ()
@@ -453,7 +461,7 @@
}
let target_collection = <Collection<T>>::get(collection_id);
- match target_collection.mode
+ match target_collection.mode
{
CollectionMode::NFT(_) => Self::burn_nft_item(collection_id, item_id)?,
CollectionMode::Fungible(_) => Self::burn_fungible_item(collection_id, item_id)?,
@@ -476,7 +484,7 @@
let target_collection = <Collection<T>>::get(collection_id);
// TODO: implement other modes
- match target_collection.mode
+ match target_collection.mode
{
CollectionMode::NFT(_) => Self::transfer_nft(collection_id, item_id, sender.clone(), recipient)?,
CollectionMode::Fungible(_) => Self::transfer_fungible(collection_id, item_id, value, sender.clone(), recipient)?,
@@ -526,8 +534,8 @@
{
let list_itm = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()));
let opt_item = list_itm.iter().find(|i| i.approved == sender.clone());
- ensure!(opt_item.is_some(), "No approve found");
- ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");
+ ensure!(opt_item.is_some(), "No approve found");
+ ensure!(opt_item.unwrap().amount >= value, "Requested value more than approved");
// remove approve
let approve_list: Vec<ApprovePermissions<T::AccountId>> = <ApprovedList<T>>::get(collection_id, (item_id, from.clone()))
@@ -538,7 +546,7 @@
{
Self::check_owner_or_admin_permissions(collection_id, sender)?;
}
-
+
let target_collection = <Collection<T>>::get(collection_id);
match target_collection.mode
@@ -575,23 +583,21 @@
) -> DispatchResult {
let sender = ensure_signed(origin)?;
Self::check_owner_or_admin_permissions(collection_id, sender.clone())?;
-
+
let mut target_collection = <Collection<T>>::get(collection_id);
target_collection.offchain_schema = schema;
<Collection<T>>::insert(collection_id, target_collection);
- Ok(())
+ Ok(())
}
}
}
impl<T: Trait> Module<T> {
-
fn add_fungible_item(item: FungibleItemType<T::AccountId>) -> DispatchResult {
-
let current_index = <ItemListIndex>::get(item.collection)
- .checked_add(1)
- .expect("Item list index id error");
+ .checked_add(1)
+ .expect("Item list index id error");
let itemcopy = item.clone();
let owner = item.owner.clone();
let value = item.value as u64;
@@ -599,20 +605,21 @@
Self::add_token_index(item.collection, current_index, owner.clone())?;
<ItemListIndex>::insert(item.collection, current_index);
- <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);
-
+ <FungibleItemList<T>>::insert(item.collection, current_index, itemcopy);
+
// Update balance
- let new_balance = <Balance<T>>::get(item.collection, owner.clone()).checked_add(value).unwrap();
- <Balance<T>>::insert(item.collection, owner.clone(), new_balance);
+ let new_balance = <Balance<T>>::get(item.collection, owner.clone())
+ .checked_add(value)
+ .unwrap();
+ <Balance<T>>::insert(item.collection, owner.clone(), new_balance);
Ok(())
}
fn add_refungible_item(item: ReFungibleItemType<T::AccountId>) -> DispatchResult {
-
let current_index = <ItemListIndex>::get(item.collection)
- .checked_add(1)
- .expect("Item list index id error");
+ .checked_add(1)
+ .expect("Item list index id error");
let itemcopy = item.clone();
let value = item.owner.first().unwrap().fraction as u64;
@@ -621,20 +628,21 @@
Self::add_token_index(item.collection, current_index, owner.clone())?;
<ItemListIndex>::insert(item.collection, current_index);
- <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);
-
+ <ReFungibleItemList<T>>::insert(item.collection, current_index, itemcopy);
+
// Update balance
- let new_balance = <Balance<T>>::get(item.collection, owner.clone()).checked_add(value).unwrap();
- <Balance<T>>::insert(item.collection, owner.clone(), new_balance);
+ let new_balance = <Balance<T>>::get(item.collection, owner.clone())
+ .checked_add(value)
+ .unwrap();
+ <Balance<T>>::insert(item.collection, owner.clone(), new_balance);
Ok(())
}
fn add_nft_item(item: NftItemType<T::AccountId>) -> DispatchResult {
-
let current_index = <ItemListIndex>::get(item.collection)
- .checked_add(1)
- .expect("Item list index id error");
+ .checked_add(1)
+ .expect("Item list index id error");
let item_owner = item.owner.clone();
let collection_id = item.collection.clone();
@@ -644,26 +652,40 @@
<NftItemList<T>>::insert(collection_id, current_index, item);
// Update balance
- let new_balance = <Balance<T>>::get(collection_id, item_owner.clone()).checked_add(1).unwrap();
+ let new_balance = <Balance<T>>::get(collection_id, item_owner.clone())
+ .checked_add(1)
+ .unwrap();
<Balance<T>>::insert(collection_id, item_owner.clone(), new_balance);
Ok(())
}
- fn burn_refungible_item(collection_id: u64, item_id: u64, owner: T::AccountId) -> DispatchResult {
-
- ensure!(<ReFungibleItemList<T>>::contains_key(collection_id, item_id), "Item does not exists");
+ fn burn_refungible_item(
+ collection_id: u64,
+ item_id: u64,
+ owner: T::AccountId,
+ ) -> DispatchResult {
+ ensure!(
+ <ReFungibleItemList<T>>::contains_key(collection_id, item_id),
+ "Item does not exists"
+ );
let collection = <ReFungibleItemList<T>>::get(collection_id, item_id);
- let item = collection.owner.iter().filter(|&i| i.owner == owner).next().unwrap();
+ let item = collection
+ .owner
+ .iter()
+ .filter(|&i| i.owner == owner)
+ .next()
+ .unwrap();
Self::remove_token_index(collection_id, item_id, owner.clone())?;
// remove approve list
<ApprovedList<T>>::remove(collection_id, (item_id, owner.clone()));
// update balance
- let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.fraction as u64).unwrap();
+ let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())
+ .checked_sub(item.fraction as u64)
+ .unwrap();
<Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);
-
<ReFungibleItemList<T>>::remove(collection_id, item_id);
@@ -671,8 +693,10 @@
}
fn burn_nft_item(collection_id: u64, item_id: u64) -> DispatchResult {
-
- ensure!(<NftItemList<T>>::contains_key(collection_id, item_id), "Item does not exists");
+ ensure!(
+ <NftItemList<T>>::contains_key(collection_id, item_id),
+ "Item does not exists"
+ );
let item = <NftItemList<T>>::get(collection_id, item_id);
Self::remove_token_index(collection_id, item_id, item.owner.clone())?;
@@ -680,7 +704,9 @@
<ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));
// update balance
- let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();
+ let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())
+ .checked_sub(1)
+ .unwrap();
<Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);
<NftItemList<T>>::remove(collection_id, item_id);
@@ -688,8 +714,10 @@
}
fn burn_fungible_item(collection_id: u64, item_id: u64) -> DispatchResult {
-
- ensure!(<FungibleItemList<T>>::contains_key(collection_id, item_id), "Item does not exists");
+ ensure!(
+ <FungibleItemList<T>>::contains_key(collection_id, item_id),
+ "Item does not exists"
+ );
let item = <FungibleItemList<T>>::get(collection_id, item_id);
Self::remove_token_index(collection_id, item_id, item.owner.clone())?;
@@ -697,31 +725,40 @@
<ApprovedList<T>>::remove(collection_id, (item_id, item.owner.clone()));
// update balance
- let new_balance = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(item.value as u64).unwrap();
+ let new_balance = <Balance<T>>::get(collection_id, item.owner.clone())
+ .checked_sub(item.value as u64)
+ .unwrap();
<Balance<T>>::insert(collection_id, item.owner.clone(), new_balance);
<FungibleItemList<T>>::remove(collection_id, item_id);
- Ok(())
+ Ok(())
}
- fn collection_exists(collection_id: u64) -> DispatchResult{
- ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");
+ fn collection_exists(collection_id: u64) -> DispatchResult {
+ ensure!(
+ <Collection<T>>::contains_key(collection_id),
+ "This collection does not exist"
+ );
Ok(())
}
fn check_owner_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {
-
Self::collection_exists(collection_id)?;
let target_collection = <Collection<T>>::get(collection_id);
- ensure!(subject == target_collection.owner, "You do not own this collection");
+ ensure!(
+ subject == target_collection.owner,
+ "You do not own this collection"
+ );
Ok(())
}
- fn check_owner_or_admin_permissions(collection_id: u64, subject: T::AccountId) -> DispatchResult {
-
+ fn check_owner_or_admin_permissions(
+ collection_id: u64,
+ subject: T::AccountId,
+ ) -> DispatchResult {
Self::collection_exists(collection_id)?;
let target_collection = <Collection<T>>::get(collection_id);
@@ -730,34 +767,52 @@
let no_perm_mes = "You do not have permissions to modify this collection";
let exists = <AdminList<T>>::contains_key(collection_id);
- if !is_owner
- {
+ if !is_owner {
ensure!(exists, no_perm_mes);
- ensure!(<AdminList<T>>::get(collection_id).contains(&subject), no_perm_mes);
+ ensure!(
+ <AdminList<T>>::get(collection_id).contains(&subject),
+ no_perm_mes
+ );
}
Ok(())
}
- fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool{
-
+ fn is_item_owner(subject: T::AccountId, collection_id: u64, item_id: u64) -> bool {
let target_collection = <Collection<T>>::get(collection_id);
match target_collection.mode {
- CollectionMode::NFT(_) => <NftItemList<T>>::get(collection_id, item_id).owner == subject,
- CollectionMode::Fungible(_) => <FungibleItemList<T>>::get(collection_id, item_id).owner == subject,
- CollectionMode::ReFungible(_, _) => <ReFungibleItemList<T>>::get(collection_id, item_id).owner.iter().any(|i| i.owner == subject),
- CollectionMode::Invalid => false
+ CollectionMode::NFT(_) => {
+ <NftItemList<T>>::get(collection_id, item_id).owner == subject
+ }
+ CollectionMode::Fungible(_) => {
+ <FungibleItemList<T>>::get(collection_id, item_id).owner == subject
+ }
+ CollectionMode::ReFungible(_, _) => {
+ <ReFungibleItemList<T>>::get(collection_id, item_id)
+ .owner
+ .iter()
+ .any(|i| i.owner == subject)
+ }
+ CollectionMode::Invalid => false,
}
}
- fn transfer_fungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {
+ fn transfer_fungible(
+ collection_id: u64,
+ item_id: u64,
+ value: u64,
+ owner: T::AccountId,
+ new_owner: T::AccountId,
+ ) -> DispatchResult {
let full_item = <FungibleItemList<T>>::get(collection_id, item_id);
let amount = full_item.value;
- ensure!(amount >= value.into(),"Item balance not enouth");
+ ensure!(amount >= value.into(), "Item balance not enouth");
// update balance
- let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone()).checked_sub(value).unwrap();
+ let balance_old_owner = <Balance<T>>::get(collection_id, owner.clone())
+ .checked_sub(value)
+ .unwrap();
<Balance<T>>::insert(collection_id, owner.clone(), balance_old_owner);
let mut new_owner_account_id = 0;
@@ -769,8 +824,7 @@
let val64 = value.into();
// transfer
- if amount == val64 && new_owner_account_id == 0
- {
+ if amount == val64 && new_owner_account_id == 0 {
// change owner
// new owner do not have account
let mut new_full_item = full_item.clone();
@@ -778,45 +832,44 @@
<FungibleItemList<T>>::insert(collection_id, item_id, new_full_item);
// update balance
- let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();
+ let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())
+ .checked_add(value)
+ .unwrap();
<Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);
// update index collection
Self::move_token_index(collection_id, item_id, owner.clone(), new_owner.clone())?;
- }
- else
- {
+ } else {
let mut new_full_item = full_item.clone();
new_full_item.value -= val64;
// separate amount
if new_owner_account_id > 0 {
-
// new owner has account
let mut item = <FungibleItemList<T>>::get(collection_id, new_owner_account_id);
item.value += val64;
// update balance
- let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();
+ let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())
+ .checked_add(value)
+ .unwrap();
<Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);
<FungibleItemList<T>>::insert(collection_id, new_owner_account_id, item);
- }
- else
- {
+ } else {
// new owner do not have account
let item = FungibleItemType {
collection: collection_id,
owner: new_owner.clone(),
- value: val64
+ value: val64,
};
Self::add_fungible_item(item)?;
}
- if amount == val64{
+ if amount == val64 {
Self::remove_token_index(collection_id, item_id, full_item.owner.clone())?;
-
+
// remove approve list
<ApprovedList<T>>::remove(collection_id, (item_id, full_item.owner.clone()));
<FungibleItemList<T>>::remove(collection_id, item_id);
@@ -828,18 +881,33 @@
Ok(())
}
- fn transfer_refungible(collection_id: u64, item_id: u64, value: u64, owner: T::AccountId, new_owner: T::AccountId) -> DispatchResult {
+ fn transfer_refungible(
+ collection_id: u64,
+ item_id: u64,
+ value: u64,
+ owner: T::AccountId,
+ new_owner: T::AccountId,
+ ) -> DispatchResult {
let full_item = <ReFungibleItemList<T>>::get(collection_id, item_id);
- let item = full_item.owner.iter().filter(|i| i.owner == owner).next().unwrap();
+ let item = full_item
+ .owner
+ .iter()
+ .filter(|i| i.owner == owner)
+ .next()
+ .unwrap();
let amount = item.fraction;
- ensure!(amount >= value.into(),"Item balance not enouth");
+ ensure!(amount >= value.into(), "Item balance not enouth");
// update balance
- let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(value).unwrap();
+ let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())
+ .checked_sub(value)
+ .unwrap();
<Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);
- let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(value).unwrap();
+ let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())
+ .checked_add(value)
+ .unwrap();
<Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);
let old_owner = item.owner.clone();
@@ -847,31 +915,44 @@
let val64 = value.into();
// transfer
- if amount == val64 && !new_owner_has_account
- {
+ if amount == val64 && !new_owner_has_account {
// change owner
// new owner do not have account
let mut new_full_item = full_item.clone();
- new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().owner = new_owner.clone();
+ new_full_item
+ .owner
+ .iter_mut()
+ .find(|i| i.owner == owner)
+ .unwrap()
+ .owner = new_owner.clone();
<ReFungibleItemList<T>>::insert(collection_id, item_id, new_full_item);
// update index collection
Self::move_token_index(collection_id, item_id, old_owner.clone(), new_owner.clone())?;
- }
- else
- {
+ } else {
let mut new_full_item = full_item.clone();
- new_full_item.owner.iter_mut().find(|i| i.owner == owner).unwrap().fraction -= val64;
+ new_full_item
+ .owner
+ .iter_mut()
+ .find(|i| i.owner == owner)
+ .unwrap()
+ .fraction -= val64;
// separate amount
if new_owner_has_account {
// new owner has account
- new_full_item.owner.iter_mut().find(|i| i.owner == new_owner).unwrap().fraction += val64;
- }
- else
- {
+ new_full_item
+ .owner
+ .iter_mut()
+ .find(|i| i.owner == new_owner)
+ .unwrap()
+ .fraction += val64;
+ } else {
// new owner do not have account
- new_full_item.owner.push(Ownership { owner: new_owner.clone(), fraction: val64});
+ new_full_item.owner.push(Ownership {
+ owner: new_owner.clone(),
+ fraction: val64,
+ });
Self::add_token_index(collection_id, item_id, new_owner.clone())?;
}
@@ -880,18 +961,29 @@
Ok(())
}
-
- fn transfer_nft(collection_id: u64, item_id: u64, sender: T::AccountId, new_owner: T::AccountId) -> DispatchResult {
+ fn transfer_nft(
+ collection_id: u64,
+ item_id: u64,
+ sender: T::AccountId,
+ new_owner: T::AccountId,
+ ) -> DispatchResult {
let mut item = <NftItemList<T>>::get(collection_id, item_id);
- ensure!(sender == item.owner,"sender parameter and item owner must be equal");
+ ensure!(
+ sender == item.owner,
+ "sender parameter and item owner must be equal"
+ );
// update balance
- let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone()).checked_sub(1).unwrap();
+ let balance_old_owner = <Balance<T>>::get(collection_id, item.owner.clone())
+ .checked_sub(1)
+ .unwrap();
<Balance<T>>::insert(collection_id, item.owner.clone(), balance_old_owner);
- let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone()).checked_add(1).unwrap();
+ let balance_new_owner = <Balance<T>>::get(collection_id, new_owner.clone())
+ .checked_add(1)
+ .unwrap();
<Balance<T>>::insert(collection_id, new_owner.clone(), balance_new_owner);
// change owner
@@ -959,72 +1051,76 @@
}
}
-
////////////////////////////////////////////////////////////////////////////////////////////////////
// Economic models
/// Fee multiplier.
pub type Multiplier = FixedU128;
-type BalanceOf<T> =
- <<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;
+type BalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<
+ <T as system::Trait>::AccountId,
+>>::Balance;
type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<
- <T as system::Trait>::AccountId,>>::NegativeImbalance;
-
-
+ <T as system::Trait>::AccountId,
+>>::NegativeImbalance;
/// Require the transactor pay for themselves and maybe include a tip to gain additional priority
/// in the queue.
#[derive(Encode, Decode, Clone, Eq, PartialEq)]
-pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);
+pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(
+ #[codec(compact)] BalanceOf<T>,
+);
-impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {
- #[cfg(feature = "std")]
- fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
- write!(f, "ChargeTransactionPayment<{:?}>", self.0)
- }
- #[cfg(not(feature = "std"))]
- fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
- Ok(())
- }
+impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug
+ for ChargeTransactionPayment<T>
+{
+ #[cfg(feature = "std")]
+ fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
+ write!(f, "ChargeTransactionPayment<{:?}>", self.0)
+ }
+ #[cfg(not(feature = "std"))]
+ fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
+ Ok(())
+ }
}
-impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where
- T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,
- BalanceOf<T>: Send + Sync + FixedPointOperand,
+impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>
+where
+ T::Call:
+ Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,
+ BalanceOf<T>: Send + Sync + FixedPointOperand,
{
- /// utility constructor. Used only in client/factory code.
- pub fn from(fee: BalanceOf<T>) -> Self {
- Self(fee)
- }
+ /// utility constructor. Used only in client/factory code.
+ pub fn from(fee: BalanceOf<T>) -> Self {
+ Self(fee)
+ }
pub fn traditional_fee(
len: usize,
info: &DispatchInfoOf<T::Call>,
tip: BalanceOf<T>,
- ) -> BalanceOf<T> where
- T::Call: Dispatchable<Info=DispatchInfo>,
+ ) -> BalanceOf<T>
+ where
+ T::Call: Dispatchable<Info = DispatchInfo>,
{
<transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)
}
- fn withdraw_fee(
- &self,
+ fn withdraw_fee(
+ &self,
who: &T::AccountId,
call: &T::Call,
- info: &DispatchInfoOf<T::Call>,
- len: usize,
- ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {
+ info: &DispatchInfoOf<T::Call>,
+ len: usize,
+ ) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {
let tip = self.0;
// Set fee based on call type. Creating collection costs 1 Unique.
// All other transactions have traditional fees so far
let fee = match call.is_sub_type() {
Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),
- _ => Self::traditional_fee(len, info, tip)
-
- // Flat fee model, use only for testing purposes
- // _ => <BalanceOf<T>>::from(100)
+ _ => Self::traditional_fee(len, info, tip), // Flat fee model, use only for testing purposes
+ // _ => <BalanceOf<T>>::from(100)
};
// Determine who is paying transaction fee based on ecnomic model
@@ -1032,12 +1128,12 @@
let sponsor: T::AccountId = match call.is_sub_type() {
Some(Call::create_item(collection_id, _properties, _owner)) => {
<Collection<T>>::get(collection_id).sponsor
- },
+ }
Some(Call::transfer(_new_owner, collection_id, _item_id, _value)) => {
<Collection<T>>::get(collection_id).sponsor
- },
+ }
- _ => T::AccountId::default()
+ _ => T::AccountId::default(),
};
let mut who_pays_fee: T::AccountId = sponsor.clone();
@@ -1045,98 +1141,109 @@
who_pays_fee = who.clone();
}
- // Only mess with balances if fee is not zero.
- if fee.is_zero() {
- return Ok((fee, None));
- }
+ // Only mess with balances if fee is not zero.
+ if fee.is_zero() {
+ return Ok((fee, None));
+ }
- match <T as transaction_payment::Trait>::Currency::withdraw(
- &who_pays_fee,
- fee,
- if tip.is_zero() {
- WithdrawReason::TransactionPayment.into()
- } else {
- WithdrawReason::TransactionPayment | WithdrawReason::Tip
- },
- ExistenceRequirement::KeepAlive,
- ) {
- Ok(imbalance) => Ok((fee, Some(imbalance))),
- Err(_) => Err(InvalidTransaction::Payment.into()),
- }
- }
+ match <T as transaction_payment::Trait>::Currency::withdraw(
+ &who_pays_fee,
+ fee,
+ if tip.is_zero() {
+ WithdrawReason::TransactionPayment.into()
+ } else {
+ WithdrawReason::TransactionPayment | WithdrawReason::Tip
+ },
+ ExistenceRequirement::KeepAlive,
+ ) {
+ Ok(imbalance) => Ok((fee, Some(imbalance))),
+ Err(_) => Err(InvalidTransaction::Payment.into()),
+ }
+ }
}
-impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where
+impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension
+ for ChargeTransactionPayment<T>
+where
BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,
- T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,
+ T::Call:
+ Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Module<T>, T>,
{
- const IDENTIFIER: &'static str = "ChargeTransactionPayment";
- type AccountId = T::AccountId;
- type Call = T::Call;
- type AdditionalSigned = ();
- type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);
- fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }
+ const IDENTIFIER: &'static str = "ChargeTransactionPayment";
+ type AccountId = T::AccountId;
+ type Call = T::Call;
+ type AdditionalSigned = ();
+ type Pre = (
+ BalanceOf<T>,
+ Self::AccountId,
+ Option<NegativeImbalanceOf<T>>,
+ BalanceOf<T>,
+ );
+ fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {
+ Ok(())
+ }
- fn validate(
- &self,
- who: &Self::AccountId,
- call: &Self::Call,
- info: &DispatchInfoOf<Self::Call>,
- len: usize,
- ) -> TransactionValidity {
- let (fee, _) = self.withdraw_fee(who, call, info, len)?;
+ fn validate(
+ &self,
+ who: &Self::AccountId,
+ call: &Self::Call,
+ info: &DispatchInfoOf<Self::Call>,
+ len: usize,
+ ) -> TransactionValidity {
+ let (fee, _) = self.withdraw_fee(who, call, info, len)?;
- let mut r = ValidTransaction::default();
- // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which
- // will be a bit more than setting the priority to tip. For now, this is enough.
- r.priority = fee.saturated_into::<TransactionPriority>();
- Ok(r)
- }
+ let mut r = ValidTransaction::default();
+ // NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which
+ // will be a bit more than setting the priority to tip. For now, this is enough.
+ r.priority = fee.saturated_into::<TransactionPriority>();
+ Ok(r)
+ }
- fn pre_dispatch(
- self,
- who: &Self::AccountId,
- call: &Self::Call,
- info: &DispatchInfoOf<Self::Call>,
- len: usize
- ) -> Result<Self::Pre, TransactionValidityError> {
- let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;
- Ok((self.0, who.clone(), imbalance, fee))
- }
+ fn pre_dispatch(
+ self,
+ who: &Self::AccountId,
+ call: &Self::Call,
+ info: &DispatchInfoOf<Self::Call>,
+ len: usize,
+ ) -> Result<Self::Pre, TransactionValidityError> {
+ let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;
+ Ok((self.0, who.clone(), imbalance, fee))
+ }
- fn post_dispatch(
- pre: Self::Pre,
- info: &DispatchInfoOf<Self::Call>,
- post_info: &PostDispatchInfoOf<Self::Call>,
- len: usize,
- _result: &DispatchResult,
- ) -> Result<(), TransactionValidityError> {
- let (tip, who, imbalance, fee) = pre;
- if let Some(payed) = imbalance {
- let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(
- len as u32,
- info,
- post_info,
- tip,
- );
- let refund = fee.saturating_sub(actual_fee);
- let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {
- Ok(refund_imbalance) => {
- // The refund cannot be larger than the up front payed max weight.
- // `PostDispatchInfo::calc_unspent` guards against such a case.
- match payed.offset(refund_imbalance) {
- Ok(actual_payment) => actual_payment,
- Err(_) => return Err(InvalidTransaction::Payment.into()),
- }
- }
- // We do not recreate the account using the refund. The up front payment
- // is gone in that case.
- Err(_) => payed,
- };
- let imbalances = actual_payment.split(tip);
- <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()
- .chain(Some(imbalances.1)));
- }
- Ok(())
- }
+ fn post_dispatch(
+ pre: Self::Pre,
+ info: &DispatchInfoOf<Self::Call>,
+ post_info: &PostDispatchInfoOf<Self::Call>,
+ len: usize,
+ _result: &DispatchResult,
+ ) -> Result<(), TransactionValidityError> {
+ let (tip, who, imbalance, fee) = pre;
+ if let Some(payed) = imbalance {
+ let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(
+ len as u32, info, post_info, tip,
+ );
+ let refund = fee.saturating_sub(actual_fee);
+ let actual_payment =
+ match <T as transaction_payment::Trait>::Currency::deposit_into_existing(
+ &who, refund,
+ ) {
+ Ok(refund_imbalance) => {
+ // The refund cannot be larger than the up front payed max weight.
+ // `PostDispatchInfo::calc_unspent` guards against such a case.
+ match payed.offset(refund_imbalance) {
+ Ok(actual_payment) => actual_payment,
+ Err(_) => return Err(InvalidTransaction::Payment.into()),
+ }
+ }
+ // We do not recreate the account using the refund. The up front payment
+ // is gone in that case.
+ Err(_) => payed,
+ };
+ let imbalances = actual_payment.split(tip);
+ <T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(
+ Some(imbalances.0).into_iter().chain(Some(imbalances.1)),
+ );
+ }
+ Ok(())
+ }
}
pallets/nft/src/mock.rsdiffbeforeafterboth--- a/pallets/nft/src/mock.rs
+++ b/pallets/nft/src/mock.rs
@@ -1,19 +1,19 @@
// Creating mock runtime here
use crate::{Module, Trait};
+use frame_support::{
+ impl_outer_origin, parameter_types,
+ weights::{
+ constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight},
+ Weight,
+ },
+};
use frame_system as system;
use sp_core::H256;
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup, Saturating},
Perbill,
-};
-use frame_support::{
- parameter_types, impl_outer_origin,
- weights::{
- constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight},
- Weight,
- },
};
impl_outer_origin! {
@@ -49,9 +49,9 @@
type MaximumBlockWeight = MaximumBlockWeight;
type MaximumBlockLength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
- type BaseCallFilter = ();
- type DbWeight = RocksDbWeight;
- type BlockExecutionWeight = BlockExecutionWeight;
+ type BaseCallFilter = ();
+ type DbWeight = RocksDbWeight;
+ type BlockExecutionWeight = BlockExecutionWeight;
type ExtrinsicBaseWeight = ExtrinsicBaseWeight;
type MaximumExtrinsicWeight = MaximumExtrinsicWeight;
type Version = ();
pallets/nft/src/tests.rsdiffbeforeafterboth--- a/pallets/nft/src/tests.rs
+++ b/pallets/nft/src/tests.rs
@@ -1,6 +1,6 @@
// Tests to be written here
use crate::mock::*;
-use crate::{CollectionMode, Ownership, ApprovePermissions};
+use crate::{ApprovePermissions, CollectionMode, Ownership};
use frame_support::{assert_noop, assert_ok};
#[test]
@@ -21,9 +21,13 @@
));
assert_eq!(TemplateModule::collection(1).owner, 1);
-
- assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
- assert_eq!(TemplateModule::nft_item_id(1,1).data, [1,2,3].to_vec());
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 2, 3].to_vec(),
+ 1
+ ));
+ assert_eq!(TemplateModule::nft_item_id(1, 1).data, [1, 2, 3].to_vec());
});
}
@@ -45,10 +49,23 @@
));
assert_eq!(TemplateModule::collection(1).owner, 1);
-
- assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
- assert_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());
- assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 1, fraction: 1000 });
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 2, 3].to_vec(),
+ 1
+ ));
+ assert_eq!(
+ TemplateModule::refungible_item_id(1, 1).data,
+ [1, 2, 3].to_vec()
+ );
+ assert_eq!(
+ TemplateModule::refungible_item_id(1, 1).owner[0],
+ Ownership {
+ owner: 1,
+ fraction: 1000
+ }
+ );
});
}
@@ -70,10 +87,15 @@
));
assert_eq!(TemplateModule::collection(1).owner, 1);
- assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [].to_vec(), 1));
- assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 1);
- assert_eq!(TemplateModule::balance_count(1,1), 1000);
- assert_eq!(TemplateModule::address_tokens(1,1), [1]);
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [].to_vec(),
+ 1
+ ));
+ assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 1);
+ assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
});
}
@@ -96,37 +118,42 @@
));
assert_eq!(TemplateModule::collection(1).owner, 1);
- assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [].to_vec(), 1));
- assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 1);
- assert_eq!(TemplateModule::balance_count(1,1), 1000);
- assert_eq!(TemplateModule::address_tokens(1,1), [1]);
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [].to_vec(),
+ 1
+ ));
+ assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 1);
+ assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
// change owner scenario
assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1000));
- assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 2);
- assert_eq!(TemplateModule::fungible_item_id(1,1).value, 1000);
- assert_eq!(TemplateModule::balance_count(1,1), 0);
- assert_eq!(TemplateModule::balance_count(1,2), 1000);
- assert_eq!(TemplateModule::address_tokens(1,1), []);
- assert_eq!(TemplateModule::address_tokens(1,2), [1]);
+ assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 2);
+ assert_eq!(TemplateModule::fungible_item_id(1, 1).value, 1000);
+ assert_eq!(TemplateModule::balance_count(1, 1), 0);
+ assert_eq!(TemplateModule::balance_count(1, 2), 1000);
+ assert_eq!(TemplateModule::address_tokens(1, 1), []);
+ assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
// split item scenario
assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 500));
- assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 2);
- assert_eq!(TemplateModule::fungible_item_id(1,2).owner, 3);
- assert_eq!(TemplateModule::balance_count(1,2), 500);
- assert_eq!(TemplateModule::balance_count(1,3), 500);
- assert_eq!(TemplateModule::address_tokens(1,2), [1]);
- assert_eq!(TemplateModule::address_tokens(1,3), [2]);
+ assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 2);
+ assert_eq!(TemplateModule::fungible_item_id(1, 2).owner, 3);
+ assert_eq!(TemplateModule::balance_count(1, 2), 500);
+ assert_eq!(TemplateModule::balance_count(1, 3), 500);
+ assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+ assert_eq!(TemplateModule::address_tokens(1, 3), [2]);
// split item and new owner has account scenario
assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 200));
- assert_eq!(TemplateModule::fungible_item_id(1,1).value, 300);
- assert_eq!(TemplateModule::fungible_item_id(1,2).value, 700);
- assert_eq!(TemplateModule::balance_count(1,2), 300);
- assert_eq!(TemplateModule::balance_count(1,3), 700);
- assert_eq!(TemplateModule::address_tokens(1,2), [1]);
- assert_eq!(TemplateModule::address_tokens(1,3), [2]);
+ assert_eq!(TemplateModule::fungible_item_id(1, 1).value, 300);
+ assert_eq!(TemplateModule::fungible_item_id(1, 2).value, 700);
+ assert_eq!(TemplateModule::balance_count(1, 2), 300);
+ assert_eq!(TemplateModule::balance_count(1, 3), 700);
+ assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+ assert_eq!(TemplateModule::address_tokens(1, 3), [2]);
});
}
@@ -149,37 +176,81 @@
));
assert_eq!(TemplateModule::collection(1).owner, 1);
- assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
- assert_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());
- assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 1, fraction: 1000 });
- assert_eq!(TemplateModule::balance_count(1,1), 1000);
- assert_eq!(TemplateModule::address_tokens(1,1), [1]);
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 2, 3].to_vec(),
+ 1
+ ));
+ assert_eq!(
+ TemplateModule::refungible_item_id(1, 1).data,
+ [1, 2, 3].to_vec()
+ );
+ assert_eq!(
+ TemplateModule::refungible_item_id(1, 1).owner[0],
+ Ownership {
+ owner: 1,
+ fraction: 1000
+ }
+ );
+ assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
// change owner scenario
assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1000));
- assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 2, fraction: 1000 });
- assert_eq!(TemplateModule::balance_count(1,1), 0);
- assert_eq!(TemplateModule::balance_count(1,2), 1000);
- assert_eq!(TemplateModule::address_tokens(1,1), []);
- assert_eq!(TemplateModule::address_tokens(1,2), [1]);
+ assert_eq!(
+ TemplateModule::refungible_item_id(1, 1).owner[0],
+ Ownership {
+ owner: 2,
+ fraction: 1000
+ }
+ );
+ assert_eq!(TemplateModule::balance_count(1, 1), 0);
+ assert_eq!(TemplateModule::balance_count(1, 2), 1000);
+ assert_eq!(TemplateModule::address_tokens(1, 1), []);
+ assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
// split item scenario
assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 500));
- assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 2, fraction: 500 });
- assert_eq!(TemplateModule::refungible_item_id(1,1).owner[1], Ownership { owner: 3, fraction: 500 });
- assert_eq!(TemplateModule::balance_count(1,2), 500);
- assert_eq!(TemplateModule::balance_count(1,3), 500);
- assert_eq!(TemplateModule::address_tokens(1,2), [1]);
- assert_eq!(TemplateModule::address_tokens(1,3), [1]);
+ assert_eq!(
+ TemplateModule::refungible_item_id(1, 1).owner[0],
+ Ownership {
+ owner: 2,
+ fraction: 500
+ }
+ );
+ assert_eq!(
+ TemplateModule::refungible_item_id(1, 1).owner[1],
+ Ownership {
+ owner: 3,
+ fraction: 500
+ }
+ );
+ assert_eq!(TemplateModule::balance_count(1, 2), 500);
+ assert_eq!(TemplateModule::balance_count(1, 3), 500);
+ assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+ assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
// split item and new owner has account scenario
assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 200));
- assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 2, fraction: 300 });
- assert_eq!(TemplateModule::refungible_item_id(1,1).owner[1], Ownership { owner: 3, fraction: 700 });
- assert_eq!(TemplateModule::balance_count(1,2), 300);
- assert_eq!(TemplateModule::balance_count(1,3), 700);
- assert_eq!(TemplateModule::address_tokens(1,2), [1]);
- assert_eq!(TemplateModule::address_tokens(1,3), [1]);
+ assert_eq!(
+ TemplateModule::refungible_item_id(1, 1).owner[0],
+ Ownership {
+ owner: 2,
+ fraction: 300
+ }
+ );
+ assert_eq!(
+ TemplateModule::refungible_item_id(1, 1).owner[1],
+ Ownership {
+ owner: 3,
+ fraction: 700
+ }
+ );
+ assert_eq!(TemplateModule::balance_count(1, 2), 300);
+ assert_eq!(TemplateModule::balance_count(1, 3), 700);
+ assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
+ assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
});
}
@@ -201,19 +272,23 @@
));
assert_eq!(TemplateModule::collection(1).owner, 1);
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 2, 3].to_vec(),
+ 1
+ ));
+ assert_eq!(TemplateModule::nft_item_id(1, 1).data, [1, 2, 3].to_vec());
+ assert_eq!(TemplateModule::balance_count(1, 1), 1);
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
- assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
- assert_eq!(TemplateModule::nft_item_id(1,1).data, [1,2,3].to_vec());
- assert_eq!(TemplateModule::balance_count(1,1), 1);
- assert_eq!(TemplateModule::address_tokens(1,1), [1]);
-
// default scenario
assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1000));
- assert_eq!(TemplateModule::nft_item_id(1,1).owner, 2);
- assert_eq!(TemplateModule::balance_count(1,1), 0);
- assert_eq!(TemplateModule::balance_count(1,2), 1);
- assert_eq!(TemplateModule::address_tokens(1,1), []);
- assert_eq!(TemplateModule::address_tokens(1,2), [1]);
+ assert_eq!(TemplateModule::nft_item_id(1, 1).owner, 2);
+ assert_eq!(TemplateModule::balance_count(1, 1), 0);
+ assert_eq!(TemplateModule::balance_count(1, 2), 1);
+ assert_eq!(TemplateModule::address_tokens(1, 1), []);
+ assert_eq!(TemplateModule::address_tokens(1, 2), [1]);
});
}
@@ -235,12 +310,16 @@
mode
));
assert_eq!(TemplateModule::collection(1).owner, 1);
-
- assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
- assert_eq!(TemplateModule::nft_item_id(1,1).data, [1,2,3].to_vec());
- assert_eq!(TemplateModule::balance_count(1,1), 1);
- assert_eq!(TemplateModule::address_tokens(1,1), [1]);
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 2, 3].to_vec(),
+ 1
+ ));
+ assert_eq!(TemplateModule::nft_item_id(1, 1).data, [1, 2, 3].to_vec());
+ assert_eq!(TemplateModule::balance_count(1, 1), 1);
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
assert_noop!(
TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
@@ -249,13 +328,26 @@
// do approve
assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
- assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);
+ assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
assert_ok!(TemplateModule::approve(origin1.clone(), 10, 1, 1));
- assert_eq!(TemplateModule::approved(1,(1,1)).len(), 2);
- assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 2, amount: 100000000});
+ assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 2);
+ assert_eq!(
+ TemplateModule::approved(1, (1, 1))[0],
+ ApprovePermissions {
+ approved: 2,
+ amount: 100000000
+ }
+ );
- assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1));
- assert_eq!(TemplateModule::approved(1,(1,1)).len(), 0);
+ assert_ok!(TemplateModule::transfer_from(
+ origin2.clone(),
+ 1,
+ 3,
+ 1,
+ 1,
+ 1
+ ));
+ assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 0);
});
}
@@ -278,11 +370,25 @@
));
assert_eq!(TemplateModule::collection(1).owner, 1);
- assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));
- assert_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());
- assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 1, fraction: 1000 });
- assert_eq!(TemplateModule::balance_count(1,1), 1000);
- assert_eq!(TemplateModule::address_tokens(1,1), [1]);
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [1, 2, 3].to_vec(),
+ 1
+ ));
+ assert_eq!(
+ TemplateModule::refungible_item_id(1, 1).data,
+ [1, 2, 3].to_vec()
+ );
+ assert_eq!(
+ TemplateModule::refungible_item_id(1, 1).owner[0],
+ Ownership {
+ owner: 1,
+ fraction: 1000
+ }
+ );
+ assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
assert_noop!(
TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
@@ -291,19 +397,38 @@
// do approve
assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
- assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);
+ assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
assert_ok!(TemplateModule::approve(origin1.clone(), 10, 1, 1));
- assert_eq!(TemplateModule::approved(1,(1,1)).len(), 2);
- assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 2, amount: 100000000});
+ assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 2);
+ assert_eq!(
+ TemplateModule::approved(1, (1, 1))[0],
+ ApprovePermissions {
+ approved: 2,
+ amount: 100000000
+ }
+ );
- assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 100));
- assert_eq!(TemplateModule::balance_count(1,1), 900);
- assert_eq!(TemplateModule::balance_count(1,3), 100);
- assert_eq!(TemplateModule::address_tokens(1,1), [1]);
- assert_eq!(TemplateModule::address_tokens(1,3), [1]);
+ assert_ok!(TemplateModule::transfer_from(
+ origin2.clone(),
+ 1,
+ 3,
+ 1,
+ 1,
+ 100
+ ));
+ assert_eq!(TemplateModule::balance_count(1, 1), 900);
+ assert_eq!(TemplateModule::balance_count(1, 3), 100);
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+ assert_eq!(TemplateModule::address_tokens(1, 3), [1]);
- assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);
- assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 10, amount: 100000000});
+ assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
+ assert_eq!(
+ TemplateModule::approved(1, (1, 1))[0],
+ ApprovePermissions {
+ approved: 10,
+ amount: 100000000
+ }
+ );
});
}
@@ -326,10 +451,15 @@
));
assert_eq!(TemplateModule::collection(1).owner, 1);
- assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [].to_vec(), 1));
- assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 1);
- assert_eq!(TemplateModule::balance_count(1,1), 1000);
- assert_eq!(TemplateModule::address_tokens(1,1), [1]);
+ assert_ok!(TemplateModule::create_item(
+ origin1.clone(),
+ 1,
+ [].to_vec(),
+ 1
+ ));
+ assert_eq!(TemplateModule::fungible_item_id(1, 1).owner, 1);
+ assert_eq!(TemplateModule::balance_count(1, 1), 1000);
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
assert_noop!(
TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),
@@ -338,28 +468,54 @@
// do approve
assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
- assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);
+ assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
assert_ok!(TemplateModule::approve(origin1.clone(), 10, 1, 1));
- assert_eq!(TemplateModule::approved(1,(1,1)).len(), 2);
- assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 2, amount: 100000000});
+ assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 2);
+ assert_eq!(
+ TemplateModule::approved(1, (1, 1))[0],
+ ApprovePermissions {
+ approved: 2,
+ amount: 100000000
+ }
+ );
- assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 100));
- assert_eq!(TemplateModule::balance_count(1,1), 900);
- assert_eq!(TemplateModule::balance_count(1,3), 100);
- assert_eq!(TemplateModule::address_tokens(1,1), [1]);
- assert_eq!(TemplateModule::address_tokens(1,3), [2]);
+ assert_ok!(TemplateModule::transfer_from(
+ origin2.clone(),
+ 1,
+ 3,
+ 1,
+ 1,
+ 100
+ ));
+ assert_eq!(TemplateModule::balance_count(1, 1), 900);
+ assert_eq!(TemplateModule::balance_count(1, 3), 100);
+ assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
+ assert_eq!(TemplateModule::address_tokens(1, 3), [2]);
- assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);
- assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 10, amount: 100000000});
+ assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 1);
+ assert_eq!(
+ TemplateModule::approved(1, (1, 1))[0],
+ ApprovePermissions {
+ approved: 10,
+ amount: 100000000
+ }
+ );
assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
- assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 900));
- assert_eq!(TemplateModule::balance_count(1,1), 0);
- assert_eq!(TemplateModule::balance_count(1,3), 1000);
- assert_eq!(TemplateModule::address_tokens(1,1), []);
- assert_eq!(TemplateModule::address_tokens(1,3), [2]);
+ assert_ok!(TemplateModule::transfer_from(
+ origin2.clone(),
+ 1,
+ 3,
+ 1,
+ 1,
+ 900
+ ));
+ assert_eq!(TemplateModule::balance_count(1, 1), 0);
+ assert_eq!(TemplateModule::balance_count(1, 3), 1000);
+ assert_eq!(TemplateModule::address_tokens(1, 1), []);
+ assert_eq!(TemplateModule::address_tokens(1, 3), [2]);
- assert_eq!(TemplateModule::approved(1,(1,1)).len(), 0);
+ assert_eq!(TemplateModule::approved(1, (1, 1)).len(), 0);
});
}
@@ -433,7 +589,7 @@
1
));
- assert_eq!(TemplateModule::nft_item_id(1,1).data, [1,2,3].to_vec());
+ assert_eq!(TemplateModule::nft_item_id(1, 1).data, [1, 2, 3].to_vec());
// check balance (collection with id = 1, user id = 1)
assert_eq!(TemplateModule::balance_count(1, 1), 1);
@@ -509,11 +665,14 @@
assert_ok!(TemplateModule::create_item(
origin2.clone(),
1,
- [1,2,3].to_vec(),
+ [1, 2, 3].to_vec(),
1
));
- assert_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());
+ assert_eq!(
+ TemplateModule::refungible_item_id(1, 1).data,
+ [1, 2, 3].to_vec()
+ );
// check balance (collection with id = 1, user id = 2)
assert_eq!(TemplateModule::balance_count(1, 1), 1000);
@@ -769,7 +928,14 @@
// approve
assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));
assert_eq!(TemplateModule::approved(1, (1, 1))[0].approved, 2);
- assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 2, 1, 1, 1));
+ assert_ok!(TemplateModule::transfer_from(
+ origin2.clone(),
+ 1,
+ 2,
+ 1,
+ 1,
+ 1
+ ));
// after transfer
assert_eq!(TemplateModule::balance_count(1, 1), 0);
runtime/build.rsdiffbeforeafterboth--- a/runtime/build.rs
+++ b/runtime/build.rs
@@ -1,10 +1,10 @@
use wasm_builder_runner::WasmBuilder;
fn main() {
- WasmBuilder::new()
- .with_current_project()
- .with_wasm_builder_from_crates("1.0.11")
- .export_heap_base()
- .import_memory()
- .build()
+ WasmBuilder::new()
+ .with_current_project()
+ .with_wasm_builder_from_crates("1.0.11")
+ .export_heap_base()
+ .import_memory()
+ .build()
}
runtime/src/lib.rsdiffbeforeafterboth1//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.23#![cfg_attr(not(feature = "std"), no_std)]4// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.5#![recursion_limit = "256"]67// Make the WASM binary available.8#[cfg(feature = "std")]9include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1011use contracts_rpc_runtime_api::ContractExecResult;12use grandpa::fg_primitives;13use grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};14use sp_api::impl_runtime_apis;15use sp_consensus_aura::sr25519::AuthorityId as AuraId;16use sp_core::{crypto::KeyTypeId, OpaqueMetadata};17use sp_runtime::{18 create_runtime_str, generic, impl_opaque_keys,19 transaction_validity::{TransactionSource, TransactionValidity},20 ApplyExtrinsicResult, MultiSignature,21 traits::{22 BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating, Verify,23 },24};25use sp_std::prelude::*;26#[cfg(feature = "std")]27use sp_version::NativeVersion;28use sp_version::RuntimeVersion;2930// A few exports that help ease life for downstream crates.31pub use balances::Call as BalancesCall;32pub use contracts::Schedule as ContractsSchedule;33pub use frame_support::{34 construct_runtime, parameter_types,35 traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason},36 weights::{37 DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},38 IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,39 },40 StorageValue,41 dispatch::DispatchResult,42};43use system::{self as system};44#[cfg(any(feature = "std", test))]45pub use sp_runtime::BuildStorage;46use sp_runtime::{47 Perbill,48};495051pub use timestamp::Call as TimestampCall;5253/// Importing a nft pallet54pub use nft;5556/// An index to a block.57pub type BlockNumber = u32;5859/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.60pub type Signature = MultiSignature;6162/// Some way of identifying an account on the chain. We intentionally make it equivalent63/// to the public key of our transaction signing scheme.64pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;6566/// The type for looking up accounts. We don't expect more than 4 billion of them, but you67/// never know...68pub type AccountIndex = u32;6970/// Balance of an account.71pub type Balance = u128;7273/// Index of a transaction in the chain.74pub type Index = u32;7576/// A hash of some data used by the chain.77pub type Hash = sp_core::H256;7879/// Digest item type.80pub type DigestItem = generic::DigestItem<Hash>;8182/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know83/// the specifics of the runtime. They can then be made to be agnostic over specific formats84/// of data like extrinsics, allowing for them to continue syncing the network through upgrades85/// to even the core data structures.86pub mod opaque {87 use super::*;8889 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;9091 /// Opaque block header type.92 pub type Header = generic::Header<BlockNumber, BlakeTwo256>;93 /// Opaque block type.94 pub type Block = generic::Block<Header, UncheckedExtrinsic>;95 /// Opaque block identifier type.96 pub type BlockId = generic::BlockId<Block>;9798 impl_opaque_keys! {99 pub struct SessionKeys {100 pub aura: Aura,101 pub grandpa: Grandpa,102 }103 }104}105106/// This runtime version.107pub const VERSION: RuntimeVersion = RuntimeVersion {108 spec_name: create_runtime_str!("nft"),109 impl_name: create_runtime_str!("nft"),110 authoring_version: 1,111 spec_version: 1,112 impl_version: 1,113 apis: RUNTIME_API_VERSIONS,114 transaction_version: 1,115};116117pub const MILLISECS_PER_BLOCK: u64 = 6000;118119pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;120121// These time units are defined in number of blocks.122pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);123pub const HOURS: BlockNumber = MINUTES * 60;124pub const DAYS: BlockNumber = HOURS * 24;125126/// The version information used to identify this runtime when compiled natively.127#[cfg(feature = "std")]128pub fn native_version() -> NativeVersion {129 NativeVersion {130 runtime_version: VERSION,131 can_author_with: Default::default(),132 }133}134135parameter_types! {136 pub const BlockHashCount: BlockNumber = 2400;137 /// We allow for 2 seconds of compute with a 6 second average block time.138 pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND;139 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);140 /// Assume 10% of weight for average on_initialize calls.141 pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get()142 .saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get();143 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;144 pub const Version: RuntimeVersion = VERSION;145}146147impl system::Trait for Runtime {148 /// The basic call filter to use in dispatchable.149 type BaseCallFilter = ();150 /// The identifier used to distinguish between accounts.151 type AccountId = AccountId;152 /// The aggregated dispatch type that is available for extrinsics.153 type Call = Call;154 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.155 type Lookup = IdentityLookup<AccountId>;156 /// The index type for storing how many extrinsics an account has signed.157 type Index = Index;158 /// The index type for blocks.159 type BlockNumber = BlockNumber;160 /// The type for hashing blocks and tries.161 type Hash = Hash;162 /// The hashing algorithm used.163 type Hashing = BlakeTwo256;164 /// The header type.165 type Header = generic::Header<BlockNumber, BlakeTwo256>;166 /// The ubiquitous event type.167 type Event = Event;168 /// The ubiquitous origin type.169 type Origin = Origin;170 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).171 type BlockHashCount = BlockHashCount;172 /// Maximum weight of each block.173 type MaximumBlockWeight = MaximumBlockWeight;174 /// The weight of database operations that the runtime can invoke.175 type DbWeight = RocksDbWeight;176 /// The weight of the overhead invoked on the block import process, independent of the177 /// extrinsics included in that block.178 type BlockExecutionWeight = BlockExecutionWeight;179 /// The base weight of any extrinsic processed by the runtime, independent of the180 /// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...)181 type ExtrinsicBaseWeight = ExtrinsicBaseWeight;182 /// The maximum weight that a single extrinsic of `Normal` dispatch class can have,183 /// idependent of the logic of that extrinsics. (Roughly max block weight - average on184 /// initialize cost).185 type MaximumExtrinsicWeight = MaximumExtrinsicWeight;186 /// Maximum size of all encoded transactions (in bytes) that are allowed in one block.187 type MaximumBlockLength = MaximumBlockLength;188 /// Portion of the block weight that is available to all normal transactions.189 type AvailableBlockRatio = AvailableBlockRatio;190 /// Version of the runtime.191 type Version = Version;192 /// Converts a module to the index of the module in `construct_runtime!`.193 /// This type is being generated by `construct_runtime!`.194 type ModuleToIndex = ModuleToIndex;195 /// What to do if a new account is created.196 type OnNewAccount = ();197 /// What to do if an account is fully reaped from the system.198 type OnKilledAccount = ();199 /// The data to be stored in an account.200 type AccountData = balances::AccountData<Balance>;201}202203impl aura::Trait for Runtime {204 type AuthorityId = AuraId;205}206207impl grandpa::Trait for Runtime {208 type Event = Event;209 type Call = Call;210211 type KeyOwnerProofSystem = ();212213 type KeyOwnerProof =214 <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;215216 type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(217 KeyTypeId,218 GrandpaId,219 )>>::IdentificationTuple;220221 type HandleEquivocation = ();222}223224parameter_types! {225 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;226}227228impl timestamp::Trait for Runtime {229 /// A timestamp: milliseconds since the unix epoch.230 type Moment = u64;231 type OnTimestampSet = Aura;232 type MinimumPeriod = MinimumPeriod;233}234235parameter_types! {236 // pub const ExistentialDeposit: u128 = 500;237 pub const ExistentialDeposit: u128 = 0;238}239240impl balances::Trait for Runtime {241 /// The type for recording an account's balance.242 type Balance = Balance;243 /// The ubiquitous event type.244 type Event = Event;245 type DustRemoval = ();246 type ExistentialDeposit = ExistentialDeposit;247 type AccountStore = System;248}249250pub const MILLICENTS: Balance = 1_000_000_000;251pub const CENTS: Balance = 1_000 * MILLICENTS;252pub const DOLLARS: Balance = 100 * CENTS;253254parameter_types! {255 pub const TombstoneDeposit: Balance = 16 * MILLICENTS;256 pub const RentByteFee: Balance = 4 * MILLICENTS;257 pub const RentDepositOffset: Balance = 1000 * MILLICENTS;258 pub const SurchargeReward: Balance = 150 * MILLICENTS;259}260261impl contracts::Trait for Runtime {262 type Call = Call;263 type Time = Timestamp;264 type Randomness = RandomnessCollectiveFlip;265 type Currency = Balances;266 type Event = Event;267 type DetermineContractAddress = contracts::SimpleAddressDeterminer<Runtime>;268 type TrieIdGenerator = contracts::TrieIdFromParentCounter<Runtime>;269 type RentPayment = ();270 type SignedClaimHandicap = contracts::DefaultSignedClaimHandicap;271 type TombstoneDeposit = TombstoneDeposit;272 type StorageSizeOffset = contracts::DefaultStorageSizeOffset;273 type RentByteFee = RentByteFee;274 type RentDepositOffset = RentDepositOffset;275 type SurchargeReward = SurchargeReward;276 type MaxDepth = contracts::DefaultMaxDepth;277 type MaxValueSize = contracts::DefaultMaxValueSize;278 type WeightPrice = transaction_payment::Module<Self>;279}280281parameter_types! {282 pub const TransactionByteFee: Balance = 1;283}284285impl transaction_payment::Trait for Runtime {286 type Currency = balances::Module<Runtime>;287 type OnTransactionPayment = ();288 type TransactionByteFee = TransactionByteFee;289 type WeightToFee = IdentityFee<Balance>;290 type FeeMultiplierUpdate = ();291}292293impl sudo::Trait for Runtime {294 type Event = Event;295 type Call = Call;296}297298/// Used for the module nft in `./nft.rs`299impl nft::Trait for Runtime {300 type Event = Event;301}302303construct_runtime!(304 pub enum Runtime where305 Block = Block,306 NodeBlock = opaque::Block,307 UncheckedExtrinsic = UncheckedExtrinsic308 {309 System: system::{Module, Call, Config, Storage, Event<T>},310 RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},311 Contracts: contracts::{Module, Call, Config, Storage, Event<T>},312 Timestamp: timestamp::{Module, Call, Storage, Inherent},313 Aura: aura::{Module, Config<T>, Inherent(Timestamp)},314 Grandpa: grandpa::{Module, Call, Storage, Config, Event},315 Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},316 TransactionPayment: transaction_payment::{Module, Storage},317 Sudo: sudo::{Module, Call, Config<T>, Storage, Event<T>},318 Nft: nft::{Module, Call, Storage, Event<T>},319 }320);321322/// The address format for describing accounts.323pub type Address = AccountId;324/// Block header type as expected by this runtime.325pub type Header = generic::Header<BlockNumber, BlakeTwo256>;326/// Block type as expected by this runtime.327pub type Block = generic::Block<Header, UncheckedExtrinsic>;328/// A Block signed with a Justification329pub type SignedBlock = generic::SignedBlock<Block>;330/// BlockId type as expected by this runtime.331pub type BlockId = generic::BlockId<Block>;332/// The SignedExtension to the basic transaction logic.333pub type SignedExtra = (334 system::CheckSpecVersion<Runtime>,335 system::CheckTxVersion<Runtime>,336 system::CheckGenesis<Runtime>,337 system::CheckEra<Runtime>,338 system::CheckNonce<Runtime>,339 system::CheckWeight<Runtime>,340 nft::ChargeTransactionPayment<Runtime>,341);342/// Unchecked extrinsic type as expected by this runtime.343pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;344/// Extrinsic type that has already been checked.345pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;346/// Executive: handles dispatch to the various modules.347pub type Executive =348 frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;349350impl_runtime_apis! {351352 impl contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>353 for Runtime354 {355 fn call(356 origin: AccountId,357 dest: AccountId,358 value: Balance,359 gas_limit: u64,360 input_data: Vec<u8>,361 ) -> ContractExecResult {362 let exec_result =363 Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);364 match exec_result {365 Ok(v) => ContractExecResult::Success {366 status: v.status,367 data: v.data,368 },369 Err(_) => ContractExecResult::Error,370 }371 }372373 fn get_storage(374 address: AccountId,375 key: [u8; 32],376 ) -> contracts_primitives::GetStorageResult {377 Contracts::get_storage(address, key)378 }379380 fn rent_projection(381 address: AccountId,382 ) -> contracts_primitives::RentProjectionResult<BlockNumber> {383 Contracts::rent_projection(address)384 }385 }386387 impl sp_api::Core<Block> for Runtime {388 fn version() -> RuntimeVersion {389 VERSION390 }391392 fn execute_block(block: Block) {393 Executive::execute_block(block)394 }395396 fn initialize_block(header: &<Block as BlockT>::Header) {397 Executive::initialize_block(header)398 }399 }400401 impl sp_api::Metadata<Block> for Runtime {402 fn metadata() -> OpaqueMetadata {403 Runtime::metadata().into()404 }405 }406407 impl sp_block_builder::BlockBuilder<Block> for Runtime {408 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {409 Executive::apply_extrinsic(extrinsic)410 }411412 fn finalize_block() -> <Block as BlockT>::Header {413 Executive::finalize_block()414 }415416 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {417 data.create_extrinsics()418 }419420 fn check_inherents(421 block: Block,422 data: sp_inherents::InherentData,423 ) -> sp_inherents::CheckInherentsResult {424 data.check_extrinsics(&block)425 }426427 fn random_seed() -> <Block as BlockT>::Hash {428 RandomnessCollectiveFlip::random_seed()429 }430 }431432 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {433 fn validate_transaction(434 source: TransactionSource,435 tx: <Block as BlockT>::Extrinsic,436 ) -> TransactionValidity {437 Executive::validate_transaction(source, tx)438 }439 }440441 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {442 fn offchain_worker(header: &<Block as BlockT>::Header) {443 Executive::offchain_worker(header)444 }445 }446447 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {448 fn slot_duration() -> u64 {449 Aura::slot_duration()450 }451452 fn authorities() -> Vec<AuraId> {453 Aura::authorities()454 }455 }456457 impl sp_session::SessionKeys<Block> for Runtime {458 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {459 opaque::SessionKeys::generate(seed)460 }461462 fn decode_session_keys(463 encoded: Vec<u8>,464 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {465 opaque::SessionKeys::decode_into_raw_public_keys(&encoded)466 }467 }468469 impl fg_primitives::GrandpaApi<Block> for Runtime {470 fn grandpa_authorities() -> GrandpaAuthorityList {471 Grandpa::grandpa_authorities()472 }473474 fn submit_report_equivocation_extrinsic(475 _equivocation_proof: fg_primitives::EquivocationProof<476 <Block as BlockT>::Hash,477 NumberFor<Block>,478 >,479 _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,480 ) -> Option<()> {481 None482 }483484 fn generate_key_ownership_proof(485 _set_id: fg_primitives::SetId,486 _authority_id: GrandpaId,487 ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {488 // NOTE: this is the only implementation possible since we've489 // defined our key owner proof type as a bottom type (i.e. a type490 // with no values).491 None492 }493 }494}4951//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.23#![cfg_attr(not(feature = "std"), no_std)]4// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.5#![recursion_limit = "256"]67// Make the WASM binary available.8#[cfg(feature = "std")]9include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1011use contracts_rpc_runtime_api::ContractExecResult;12use grandpa::fg_primitives;13use grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};14use sp_api::impl_runtime_apis;15use sp_consensus_aura::sr25519::AuthorityId as AuraId;16use sp_core::{crypto::KeyTypeId, OpaqueMetadata};17use sp_runtime::{18 create_runtime_str, generic, impl_opaque_keys,19 traits::{20 BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating,21 Verify,22 },23 transaction_validity::{TransactionSource, TransactionValidity},24 ApplyExtrinsicResult, MultiSignature,25};26use sp_std::prelude::*;27#[cfg(feature = "std")]28use sp_version::NativeVersion;29use sp_version::RuntimeVersion;3031// A few exports that help ease life for downstream crates.32pub use balances::Call as BalancesCall;33pub use contracts::Schedule as ContractsSchedule;34pub use frame_support::{35 construct_runtime,36 dispatch::DispatchResult,37 parameter_types,38 traits::{39 Currency, ExistenceRequirement, Get, KeyOwnerProofSystem, OnUnbalanced, Randomness,40 WithdrawReason,41 },42 weights::{43 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},44 DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,45 WeightToFeePolynomial,46 },47 StorageValue,48};49#[cfg(any(feature = "std", test))]50pub use sp_runtime::BuildStorage;51use sp_runtime::Perbill;52use system::{self as system};5354pub use timestamp::Call as TimestampCall;5556/// Importing a nft pallet57pub use nft;5859/// An index to a block.60pub type BlockNumber = u32;6162/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.63pub type Signature = MultiSignature;6465/// Some way of identifying an account on the chain. We intentionally make it equivalent66/// to the public key of our transaction signing scheme.67pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;6869/// The type for looking up accounts. We don't expect more than 4 billion of them, but you70/// never know...71pub type AccountIndex = u32;7273/// Balance of an account.74pub type Balance = u128;7576/// Index of a transaction in the chain.77pub type Index = u32;7879/// A hash of some data used by the chain.80pub type Hash = sp_core::H256;8182/// Digest item type.83pub type DigestItem = generic::DigestItem<Hash>;8485/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know86/// the specifics of the runtime. They can then be made to be agnostic over specific formats87/// of data like extrinsics, allowing for them to continue syncing the network through upgrades88/// to even the core data structures.89pub mod opaque {90 use super::*;9192 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;9394 /// Opaque block header type.95 pub type Header = generic::Header<BlockNumber, BlakeTwo256>;96 /// Opaque block type.97 pub type Block = generic::Block<Header, UncheckedExtrinsic>;98 /// Opaque block identifier type.99 pub type BlockId = generic::BlockId<Block>;100101 impl_opaque_keys! {102 pub struct SessionKeys {103 pub aura: Aura,104 pub grandpa: Grandpa,105 }106 }107}108109/// This runtime version.110pub const VERSION: RuntimeVersion = RuntimeVersion {111 spec_name: create_runtime_str!("nft"),112 impl_name: create_runtime_str!("nft"),113 authoring_version: 1,114 spec_version: 1,115 impl_version: 1,116 apis: RUNTIME_API_VERSIONS,117 transaction_version: 1,118};119120pub const MILLISECS_PER_BLOCK: u64 = 6000;121122pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;123124// These time units are defined in number of blocks.125pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);126pub const HOURS: BlockNumber = MINUTES * 60;127pub const DAYS: BlockNumber = HOURS * 24;128129/// The version information used to identify this runtime when compiled natively.130#[cfg(feature = "std")]131pub fn native_version() -> NativeVersion {132 NativeVersion {133 runtime_version: VERSION,134 can_author_with: Default::default(),135 }136}137138parameter_types! {139 pub const BlockHashCount: BlockNumber = 2400;140 /// We allow for 2 seconds of compute with a 6 second average block time.141 pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND;142 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);143 /// Assume 10% of weight for average on_initialize calls.144 pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get()145 .saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get();146 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;147 pub const Version: RuntimeVersion = VERSION;148}149150impl system::Trait for Runtime {151 /// The basic call filter to use in dispatchable.152 type BaseCallFilter = ();153 /// The identifier used to distinguish between accounts.154 type AccountId = AccountId;155 /// The aggregated dispatch type that is available for extrinsics.156 type Call = Call;157 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.158 type Lookup = IdentityLookup<AccountId>;159 /// The index type for storing how many extrinsics an account has signed.160 type Index = Index;161 /// The index type for blocks.162 type BlockNumber = BlockNumber;163 /// The type for hashing blocks and tries.164 type Hash = Hash;165 /// The hashing algorithm used.166 type Hashing = BlakeTwo256;167 /// The header type.168 type Header = generic::Header<BlockNumber, BlakeTwo256>;169 /// The ubiquitous event type.170 type Event = Event;171 /// The ubiquitous origin type.172 type Origin = Origin;173 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).174 type BlockHashCount = BlockHashCount;175 /// Maximum weight of each block.176 type MaximumBlockWeight = MaximumBlockWeight;177 /// The weight of database operations that the runtime can invoke.178 type DbWeight = RocksDbWeight;179 /// The weight of the overhead invoked on the block import process, independent of the180 /// extrinsics included in that block.181 type BlockExecutionWeight = BlockExecutionWeight;182 /// The base weight of any extrinsic processed by the runtime, independent of the183 /// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...)184 type ExtrinsicBaseWeight = ExtrinsicBaseWeight;185 /// The maximum weight that a single extrinsic of `Normal` dispatch class can have,186 /// idependent of the logic of that extrinsics. (Roughly max block weight - average on187 /// initialize cost).188 type MaximumExtrinsicWeight = MaximumExtrinsicWeight;189 /// Maximum size of all encoded transactions (in bytes) that are allowed in one block.190 type MaximumBlockLength = MaximumBlockLength;191 /// Portion of the block weight that is available to all normal transactions.192 type AvailableBlockRatio = AvailableBlockRatio;193 /// Version of the runtime.194 type Version = Version;195 /// Converts a module to the index of the module in `construct_runtime!`.196 /// This type is being generated by `construct_runtime!`.197 type ModuleToIndex = ModuleToIndex;198 /// What to do if a new account is created.199 type OnNewAccount = ();200 /// What to do if an account is fully reaped from the system.201 type OnKilledAccount = ();202 /// The data to be stored in an account.203 type AccountData = balances::AccountData<Balance>;204}205206impl aura::Trait for Runtime {207 type AuthorityId = AuraId;208}209210impl grandpa::Trait for Runtime {211 type Event = Event;212 type Call = Call;213214 type KeyOwnerProofSystem = ();215216 type KeyOwnerProof =217 <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;218219 type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(220 KeyTypeId,221 GrandpaId,222 )>>::IdentificationTuple;223224 type HandleEquivocation = ();225}226227parameter_types! {228 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;229}230231impl timestamp::Trait for Runtime {232 /// A timestamp: milliseconds since the unix epoch.233 type Moment = u64;234 type OnTimestampSet = Aura;235 type MinimumPeriod = MinimumPeriod;236}237238parameter_types! {239 // pub const ExistentialDeposit: u128 = 500;240 pub const ExistentialDeposit: u128 = 0;241}242243impl balances::Trait for Runtime {244 /// The type for recording an account's balance.245 type Balance = Balance;246 /// The ubiquitous event type.247 type Event = Event;248 type DustRemoval = ();249 type ExistentialDeposit = ExistentialDeposit;250 type AccountStore = System;251}252253pub const MILLICENTS: Balance = 1_000_000_000;254pub const CENTS: Balance = 1_000 * MILLICENTS;255pub const DOLLARS: Balance = 100 * CENTS;256257parameter_types! {258 pub const TombstoneDeposit: Balance = 16 * MILLICENTS;259 pub const RentByteFee: Balance = 4 * MILLICENTS;260 pub const RentDepositOffset: Balance = 1000 * MILLICENTS;261 pub const SurchargeReward: Balance = 150 * MILLICENTS;262}263264impl contracts::Trait for Runtime {265 type Call = Call;266 type Time = Timestamp;267 type Randomness = RandomnessCollectiveFlip;268 type Currency = Balances;269 type Event = Event;270 type DetermineContractAddress = contracts::SimpleAddressDeterminer<Runtime>;271 type TrieIdGenerator = contracts::TrieIdFromParentCounter<Runtime>;272 type RentPayment = ();273 type SignedClaimHandicap = contracts::DefaultSignedClaimHandicap;274 type TombstoneDeposit = TombstoneDeposit;275 type StorageSizeOffset = contracts::DefaultStorageSizeOffset;276 type RentByteFee = RentByteFee;277 type RentDepositOffset = RentDepositOffset;278 type SurchargeReward = SurchargeReward;279 type MaxDepth = contracts::DefaultMaxDepth;280 type MaxValueSize = contracts::DefaultMaxValueSize;281 type WeightPrice = transaction_payment::Module<Self>;282}283284parameter_types! {285 pub const TransactionByteFee: Balance = 1;286}287288impl transaction_payment::Trait for Runtime {289 type Currency = balances::Module<Runtime>;290 type OnTransactionPayment = ();291 type TransactionByteFee = TransactionByteFee;292 type WeightToFee = IdentityFee<Balance>;293 type FeeMultiplierUpdate = ();294}295296impl sudo::Trait for Runtime {297 type Event = Event;298 type Call = Call;299}300301/// Used for the module nft in `./nft.rs`302impl nft::Trait for Runtime {303 type Event = Event;304}305306construct_runtime!(307 pub enum Runtime where308 Block = Block,309 NodeBlock = opaque::Block,310 UncheckedExtrinsic = UncheckedExtrinsic311 {312 System: system::{Module, Call, Config, Storage, Event<T>},313 RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},314 Contracts: contracts::{Module, Call, Config, Storage, Event<T>},315 Timestamp: timestamp::{Module, Call, Storage, Inherent},316 Aura: aura::{Module, Config<T>, Inherent(Timestamp)},317 Grandpa: grandpa::{Module, Call, Storage, Config, Event},318 Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},319 TransactionPayment: transaction_payment::{Module, Storage},320 Sudo: sudo::{Module, Call, Config<T>, Storage, Event<T>},321 Nft: nft::{Module, Call, Storage, Event<T>},322 }323);324325/// The address format for describing accounts.326pub type Address = AccountId;327/// Block header type as expected by this runtime.328pub type Header = generic::Header<BlockNumber, BlakeTwo256>;329/// Block type as expected by this runtime.330pub type Block = generic::Block<Header, UncheckedExtrinsic>;331/// A Block signed with a Justification332pub type SignedBlock = generic::SignedBlock<Block>;333/// BlockId type as expected by this runtime.334pub type BlockId = generic::BlockId<Block>;335/// The SignedExtension to the basic transaction logic.336pub type SignedExtra = (337 system::CheckSpecVersion<Runtime>,338 system::CheckTxVersion<Runtime>,339 system::CheckGenesis<Runtime>,340 system::CheckEra<Runtime>,341 system::CheckNonce<Runtime>,342 system::CheckWeight<Runtime>,343 nft::ChargeTransactionPayment<Runtime>,344);345/// Unchecked extrinsic type as expected by this runtime.346pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;347/// Extrinsic type that has already been checked.348pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;349/// Executive: handles dispatch to the various modules.350pub type Executive =351 frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;352353impl_runtime_apis! {354355 impl contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>356 for Runtime357 {358 fn call(359 origin: AccountId,360 dest: AccountId,361 value: Balance,362 gas_limit: u64,363 input_data: Vec<u8>,364 ) -> ContractExecResult {365 let exec_result =366 Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);367 match exec_result {368 Ok(v) => ContractExecResult::Success {369 status: v.status,370 data: v.data,371 },372 Err(_) => ContractExecResult::Error,373 }374 }375376 fn get_storage(377 address: AccountId,378 key: [u8; 32],379 ) -> contracts_primitives::GetStorageResult {380 Contracts::get_storage(address, key)381 }382383 fn rent_projection(384 address: AccountId,385 ) -> contracts_primitives::RentProjectionResult<BlockNumber> {386 Contracts::rent_projection(address)387 }388 }389390 impl sp_api::Core<Block> for Runtime {391 fn version() -> RuntimeVersion {392 VERSION393 }394395 fn execute_block(block: Block) {396 Executive::execute_block(block)397 }398399 fn initialize_block(header: &<Block as BlockT>::Header) {400 Executive::initialize_block(header)401 }402 }403404 impl sp_api::Metadata<Block> for Runtime {405 fn metadata() -> OpaqueMetadata {406 Runtime::metadata().into()407 }408 }409410 impl sp_block_builder::BlockBuilder<Block> for Runtime {411 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {412 Executive::apply_extrinsic(extrinsic)413 }414415 fn finalize_block() -> <Block as BlockT>::Header {416 Executive::finalize_block()417 }418419 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {420 data.create_extrinsics()421 }422423 fn check_inherents(424 block: Block,425 data: sp_inherents::InherentData,426 ) -> sp_inherents::CheckInherentsResult {427 data.check_extrinsics(&block)428 }429430 fn random_seed() -> <Block as BlockT>::Hash {431 RandomnessCollectiveFlip::random_seed()432 }433 }434435 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {436 fn validate_transaction(437 source: TransactionSource,438 tx: <Block as BlockT>::Extrinsic,439 ) -> TransactionValidity {440 Executive::validate_transaction(source, tx)441 }442 }443444 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {445 fn offchain_worker(header: &<Block as BlockT>::Header) {446 Executive::offchain_worker(header)447 }448 }449450 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {451 fn slot_duration() -> u64 {452 Aura::slot_duration()453 }454455 fn authorities() -> Vec<AuraId> {456 Aura::authorities()457 }458 }459460 impl sp_session::SessionKeys<Block> for Runtime {461 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {462 opaque::SessionKeys::generate(seed)463 }464465 fn decode_session_keys(466 encoded: Vec<u8>,467 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {468 opaque::SessionKeys::decode_into_raw_public_keys(&encoded)469 }470 }471472 impl fg_primitives::GrandpaApi<Block> for Runtime {473 fn grandpa_authorities() -> GrandpaAuthorityList {474 Grandpa::grandpa_authorities()475 }476477 fn submit_report_equivocation_extrinsic(478 _equivocation_proof: fg_primitives::EquivocationProof<479 <Block as BlockT>::Hash,480 NumberFor<Block>,481 >,482 _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,483 ) -> Option<()> {484 None485 }486487 fn generate_key_ownership_proof(488 _set_id: fg_primitives::SetId,489 _authority_id: GrandpaId,490 ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {491 // NOTE: this is the only implementation possible since we've492 // defined our key owner proof type as a bottom type (i.e. a type493 // with no values).494 None495 }496 }497}