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.rsdiffbeforeafterboth1// Tests to be written here2use crate::mock::*;3use crate::{CollectionMode, Ownership, ApprovePermissions};4use frame_support::{assert_noop, assert_ok};56#[test]7fn create_nft_item() {8 new_test_ext().execute_with(|| {9 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();10 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();11 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();12 let mode: CollectionMode = CollectionMode::NFT(2000);1314 let origin1 = Origin::signed(1);15 assert_ok!(TemplateModule::create_collection(16 origin1.clone(),17 col_name1.clone(),18 col_desc1.clone(),19 token_prefix1.clone(),20 mode21 ));22 assert_eq!(TemplateModule::collection(1).owner, 1);232425 assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));26 assert_eq!(TemplateModule::nft_item_id(1,1).data, [1,2,3].to_vec());27 });28}2930#[test]31fn create_refungible_item() {32 new_test_ext().execute_with(|| {33 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();34 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();35 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();36 let mode: CollectionMode = CollectionMode::ReFungible(2000, 3);3738 let origin1 = Origin::signed(1);39 assert_ok!(TemplateModule::create_collection(40 origin1.clone(),41 col_name1.clone(),42 col_desc1.clone(),43 token_prefix1.clone(),44 mode45 ));46 assert_eq!(TemplateModule::collection(1).owner, 1);474849 assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));50 assert_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());51 assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 1, fraction: 1000 });52 });53}5455#[test]56fn create_fungible_item() {57 new_test_ext().execute_with(|| {58 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();59 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();60 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();61 let mode: CollectionMode = CollectionMode::Fungible(3);6263 let origin1 = Origin::signed(1);64 assert_ok!(TemplateModule::create_collection(65 origin1.clone(),66 col_name1.clone(),67 col_desc1.clone(),68 token_prefix1.clone(),69 mode70 ));71 assert_eq!(TemplateModule::collection(1).owner, 1);7273 assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [].to_vec(), 1));74 assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 1);75 assert_eq!(TemplateModule::balance_count(1,1), 1000);76 assert_eq!(TemplateModule::address_tokens(1,1), [1]);77 });78}7980#[test]81fn transfer_fungible_item() {82 new_test_ext().execute_with(|| {83 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();84 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();85 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();86 let mode: CollectionMode = CollectionMode::Fungible(3);8788 let origin1 = Origin::signed(1);89 let origin2 = Origin::signed(2);90 assert_ok!(TemplateModule::create_collection(91 origin1.clone(),92 col_name1.clone(),93 col_desc1.clone(),94 token_prefix1.clone(),95 mode96 ));97 assert_eq!(TemplateModule::collection(1).owner, 1);9899 assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [].to_vec(), 1));100 assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 1);101 assert_eq!(TemplateModule::balance_count(1,1), 1000);102 assert_eq!(TemplateModule::address_tokens(1,1), [1]);103104 // change owner scenario105 assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1000));106 assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 2);107 assert_eq!(TemplateModule::fungible_item_id(1,1).value, 1000);108 assert_eq!(TemplateModule::balance_count(1,1), 0);109 assert_eq!(TemplateModule::balance_count(1,2), 1000);110 assert_eq!(TemplateModule::address_tokens(1,1), []);111 assert_eq!(TemplateModule::address_tokens(1,2), [1]);112113 // split item scenario114 assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 500));115 assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 2);116 assert_eq!(TemplateModule::fungible_item_id(1,2).owner, 3);117 assert_eq!(TemplateModule::balance_count(1,2), 500);118 assert_eq!(TemplateModule::balance_count(1,3), 500);119 assert_eq!(TemplateModule::address_tokens(1,2), [1]);120 assert_eq!(TemplateModule::address_tokens(1,3), [2]);121122 // split item and new owner has account scenario123 assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 200));124 assert_eq!(TemplateModule::fungible_item_id(1,1).value, 300);125 assert_eq!(TemplateModule::fungible_item_id(1,2).value, 700);126 assert_eq!(TemplateModule::balance_count(1,2), 300);127 assert_eq!(TemplateModule::balance_count(1,3), 700);128 assert_eq!(TemplateModule::address_tokens(1,2), [1]);129 assert_eq!(TemplateModule::address_tokens(1,3), [2]);130 });131}132133#[test]134fn transfer_refungible_item() {135 new_test_ext().execute_with(|| {136 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();137 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();138 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();139 let mode: CollectionMode = CollectionMode::ReFungible(2000, 3);140141 let origin1 = Origin::signed(1);142 let origin2 = Origin::signed(2);143 assert_ok!(TemplateModule::create_collection(144 origin1.clone(),145 col_name1.clone(),146 col_desc1.clone(),147 token_prefix1.clone(),148 mode149 ));150 assert_eq!(TemplateModule::collection(1).owner, 1);151152 assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));153 assert_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());154 assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 1, fraction: 1000 });155 assert_eq!(TemplateModule::balance_count(1,1), 1000);156 assert_eq!(TemplateModule::address_tokens(1,1), [1]);157158 // change owner scenario159 assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1000));160 assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 2, fraction: 1000 });161 assert_eq!(TemplateModule::balance_count(1,1), 0);162 assert_eq!(TemplateModule::balance_count(1,2), 1000);163 assert_eq!(TemplateModule::address_tokens(1,1), []);164 assert_eq!(TemplateModule::address_tokens(1,2), [1]);165166 // split item scenario167 assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 500));168 assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 2, fraction: 500 });169 assert_eq!(TemplateModule::refungible_item_id(1,1).owner[1], Ownership { owner: 3, fraction: 500 });170 assert_eq!(TemplateModule::balance_count(1,2), 500);171 assert_eq!(TemplateModule::balance_count(1,3), 500);172 assert_eq!(TemplateModule::address_tokens(1,2), [1]);173 assert_eq!(TemplateModule::address_tokens(1,3), [1]);174175 // split item and new owner has account scenario176 assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 200));177 assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 2, fraction: 300 });178 assert_eq!(TemplateModule::refungible_item_id(1,1).owner[1], Ownership { owner: 3, fraction: 700 });179 assert_eq!(TemplateModule::balance_count(1,2), 300);180 assert_eq!(TemplateModule::balance_count(1,3), 700);181 assert_eq!(TemplateModule::address_tokens(1,2), [1]);182 assert_eq!(TemplateModule::address_tokens(1,3), [1]);183 });184}185186#[test]187fn transfer_nft_item() {188 new_test_ext().execute_with(|| {189 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();190 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();191 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();192 let mode: CollectionMode = CollectionMode::NFT(2000);193194 let origin1 = Origin::signed(1);195 assert_ok!(TemplateModule::create_collection(196 origin1.clone(),197 col_name1.clone(),198 col_desc1.clone(),199 token_prefix1.clone(),200 mode201 ));202 assert_eq!(TemplateModule::collection(1).owner, 1);203204205 assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));206 assert_eq!(TemplateModule::nft_item_id(1,1).data, [1,2,3].to_vec());207 assert_eq!(TemplateModule::balance_count(1,1), 1);208 assert_eq!(TemplateModule::address_tokens(1,1), [1]);209210 // default scenario211 assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1000));212 assert_eq!(TemplateModule::nft_item_id(1,1).owner, 2);213 assert_eq!(TemplateModule::balance_count(1,1), 0);214 assert_eq!(TemplateModule::balance_count(1,2), 1);215 assert_eq!(TemplateModule::address_tokens(1,1), []);216 assert_eq!(TemplateModule::address_tokens(1,2), [1]); 217 });218}219220#[test]221fn nft_approve_and_transfer_from() {222 new_test_ext().execute_with(|| {223 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();224 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();225 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();226 let mode: CollectionMode = CollectionMode::NFT(2000);227228 let origin1 = Origin::signed(1);229 let origin2 = Origin::signed(2);230 assert_ok!(TemplateModule::create_collection(231 origin1.clone(),232 col_name1.clone(),233 col_desc1.clone(),234 token_prefix1.clone(),235 mode236 ));237 assert_eq!(TemplateModule::collection(1).owner, 1);238239240 assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));241 assert_eq!(TemplateModule::nft_item_id(1,1).data, [1,2,3].to_vec());242 assert_eq!(TemplateModule::balance_count(1,1), 1);243 assert_eq!(TemplateModule::address_tokens(1,1), [1]);244245 assert_noop!(246 TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),247 "You do not have permissions to modify this collection"248 );249250 // do approve251 assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));252 assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);253 assert_ok!(TemplateModule::approve(origin1.clone(), 10, 1, 1));254 assert_eq!(TemplateModule::approved(1,(1,1)).len(), 2);255 assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 2, amount: 100000000});256257 assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1));258 assert_eq!(TemplateModule::approved(1,(1,1)).len(), 0);259 });260}261262#[test]263fn refungible_approve_and_transfer_from() {264 new_test_ext().execute_with(|| {265 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();266 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();267 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();268 let mode: CollectionMode = CollectionMode::ReFungible(2000, 3);269270 let origin1 = Origin::signed(1);271 let origin2 = Origin::signed(2);272 assert_ok!(TemplateModule::create_collection(273 origin1.clone(),274 col_name1.clone(),275 col_desc1.clone(),276 token_prefix1.clone(),277 mode278 ));279 assert_eq!(TemplateModule::collection(1).owner, 1);280281 assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [1,2,3].to_vec(), 1));282 assert_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());283 assert_eq!(TemplateModule::refungible_item_id(1,1).owner[0], Ownership { owner: 1, fraction: 1000 });284 assert_eq!(TemplateModule::balance_count(1,1), 1000);285 assert_eq!(TemplateModule::address_tokens(1,1), [1]);286287 assert_noop!(288 TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),289 "You do not have permissions to modify this collection"290 );291292 // do approve293 assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));294 assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);295 assert_ok!(TemplateModule::approve(origin1.clone(), 10, 1, 1));296 assert_eq!(TemplateModule::approved(1,(1,1)).len(), 2);297 assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 2, amount: 100000000});298299 assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 100));300 assert_eq!(TemplateModule::balance_count(1,1), 900);301 assert_eq!(TemplateModule::balance_count(1,3), 100);302 assert_eq!(TemplateModule::address_tokens(1,1), [1]);303 assert_eq!(TemplateModule::address_tokens(1,3), [1]);304305 assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);306 assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 10, amount: 100000000});307 });308}309310#[test]311fn fungible_approve_and_transfer_from() {312 new_test_ext().execute_with(|| {313 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();314 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();315 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();316 let mode: CollectionMode = CollectionMode::Fungible(3);317318 let origin1 = Origin::signed(1);319 let origin2 = Origin::signed(2);320 assert_ok!(TemplateModule::create_collection(321 origin1.clone(),322 col_name1.clone(),323 col_desc1.clone(),324 token_prefix1.clone(),325 mode326 ));327 assert_eq!(TemplateModule::collection(1).owner, 1);328329 assert_ok!(TemplateModule::create_item(origin1.clone(), 1, [].to_vec(), 1));330 assert_eq!(TemplateModule::fungible_item_id(1,1).owner, 1);331 assert_eq!(TemplateModule::balance_count(1,1), 1000);332 assert_eq!(TemplateModule::address_tokens(1,1), [1]);333334 assert_noop!(335 TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 1),336 "You do not have permissions to modify this collection"337 );338339 // do approve340 assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));341 assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);342 assert_ok!(TemplateModule::approve(origin1.clone(), 10, 1, 1));343 assert_eq!(TemplateModule::approved(1,(1,1)).len(), 2);344 assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 2, amount: 100000000});345346 assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 100));347 assert_eq!(TemplateModule::balance_count(1,1), 900);348 assert_eq!(TemplateModule::balance_count(1,3), 100);349 assert_eq!(TemplateModule::address_tokens(1,1), [1]);350 assert_eq!(TemplateModule::address_tokens(1,3), [2]);351352 assert_eq!(TemplateModule::approved(1,(1,1)).len(), 1);353 assert_eq!(TemplateModule::approved(1,(1,1))[0], ApprovePermissions { approved: 10, amount: 100000000});354355 assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));356 assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 3, 1, 1, 900));357 assert_eq!(TemplateModule::balance_count(1,1), 0);358 assert_eq!(TemplateModule::balance_count(1,3), 1000);359 assert_eq!(TemplateModule::address_tokens(1,1), []);360 assert_eq!(TemplateModule::address_tokens(1,3), [2]);361362 assert_eq!(TemplateModule::approved(1,(1,1)).len(), 0);363 });364}365366#[test]367fn change_collection_owner() {368 new_test_ext().execute_with(|| {369 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();370 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();371 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();372 let mode: CollectionMode = CollectionMode::NFT(2000);373374 let origin1 = Origin::signed(1);375 assert_ok!(TemplateModule::create_collection(376 origin1.clone(),377 col_name1.clone(),378 col_desc1.clone(),379 token_prefix1.clone(),380 mode381 ));382 assert_ok!(TemplateModule::change_collection_owner(383 origin1.clone(),384 1,385 2386 ));387 assert_eq!(TemplateModule::collection(1).owner, 2);388 });389}390391#[test]392fn destroy_collection() {393 new_test_ext().execute_with(|| {394 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();395 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();396 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();397 let mode: CollectionMode = CollectionMode::NFT(2000);398399 let origin1 = Origin::signed(1);400 assert_ok!(TemplateModule::create_collection(401 origin1.clone(),402 col_name1.clone(),403 col_desc1.clone(),404 token_prefix1.clone(),405 mode406 ));407 assert_ok!(TemplateModule::destroy_collection(origin1.clone(), 1));408 });409}410411#[test]412fn burn_nft_item() {413 new_test_ext().execute_with(|| {414 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();415 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();416 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();417 let mode: CollectionMode = CollectionMode::NFT(2000);418419 let origin1 = Origin::signed(1);420 let origin2 = Origin::signed(2);421 assert_ok!(TemplateModule::create_collection(422 origin1.clone(),423 col_name1.clone(),424 col_desc1.clone(),425 token_prefix1.clone(),426 mode427 ));428 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));429 assert_ok!(TemplateModule::create_item(430 origin2.clone(),431 1,432 [1, 2, 3].to_vec(),433 1434 ));435436 assert_eq!(TemplateModule::nft_item_id(1,1).data, [1,2,3].to_vec());437438 // check balance (collection with id = 1, user id = 1)439 assert_eq!(TemplateModule::balance_count(1, 1), 1);440441 // burn item442 assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1));443 assert_noop!(444 TemplateModule::burn_item(origin1.clone(), 1, 1),445 "Item does not exists"446 );447448 assert_eq!(TemplateModule::balance_count(1, 1), 0);449 });450}451452#[test]453fn burn_fungible_item() {454 new_test_ext().execute_with(|| {455 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();456 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();457 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();458 let mode: CollectionMode = CollectionMode::Fungible(3);459460 let origin1 = Origin::signed(1);461 let origin2 = Origin::signed(2);462 assert_ok!(TemplateModule::create_collection(463 origin1.clone(),464 col_name1.clone(),465 col_desc1.clone(),466 token_prefix1.clone(),467 mode468 ));469 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));470 assert_ok!(TemplateModule::create_item(471 origin2.clone(),472 1,473 [].to_vec(),474 1475 ));476477 // check balance (collection with id = 1, user id = 1)478 assert_eq!(TemplateModule::balance_count(1, 1), 1000);479480 // burn item481 assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1));482 assert_noop!(483 TemplateModule::burn_item(origin1.clone(), 1, 1),484 "Item does not exists"485 );486487 assert_eq!(TemplateModule::balance_count(1, 1), 0);488 });489}490491#[test]492fn burn_refungible_item() {493 new_test_ext().execute_with(|| {494 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();495 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();496 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();497 let mode: CollectionMode = CollectionMode::ReFungible(200, 3);498499 let origin1 = Origin::signed(1);500 let origin2 = Origin::signed(2);501 assert_ok!(TemplateModule::create_collection(502 origin1.clone(),503 col_name1.clone(),504 col_desc1.clone(),505 token_prefix1.clone(),506 mode507 ));508 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));509 assert_ok!(TemplateModule::create_item(510 origin2.clone(),511 1,512 [1,2,3].to_vec(),513 1514 ));515516 assert_eq!(TemplateModule::refungible_item_id(1,1).data, [1,2,3].to_vec());517518 // check balance (collection with id = 1, user id = 2)519 assert_eq!(TemplateModule::balance_count(1, 1), 1000);520521 // burn item522 assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1));523 assert_noop!(524 TemplateModule::burn_item(origin1.clone(), 1, 1),525 "Item does not exists"526 );527528 assert_eq!(TemplateModule::balance_count(1, 1), 0);529 });530}531532#[test]533fn add_collection_admin() {534 new_test_ext().execute_with(|| {535 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();536 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();537 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();538 let mode: CollectionMode = CollectionMode::NFT(2000);539540 let origin1 = Origin::signed(1);541 let origin2 = Origin::signed(2);542 let origin3 = Origin::signed(3);543 assert_ok!(TemplateModule::create_collection(544 origin1.clone(),545 col_name1.clone(),546 col_desc1.clone(),547 token_prefix1.clone(),548 mode.clone()549 ));550 assert_ok!(TemplateModule::create_collection(551 origin2.clone(),552 col_name1.clone(),553 col_desc1.clone(),554 token_prefix1.clone(),555 mode.clone()556 ));557 assert_ok!(TemplateModule::create_collection(558 origin3.clone(),559 col_name1.clone(),560 col_desc1.clone(),561 token_prefix1.clone(),562 mode.clone()563 ));564565 assert_eq!(TemplateModule::collection(1).owner, 1);566 assert_eq!(TemplateModule::collection(2).owner, 2);567 assert_eq!(TemplateModule::collection(3).owner, 3);568569 // collection admin570 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));571 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 3));572573 assert_eq!(TemplateModule::admin_list_collection(1).contains(&2), true);574 assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), true);575 });576}577578#[test]579fn remove_collection_admin() {580 new_test_ext().execute_with(|| {581 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();582 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();583 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();584 let mode: CollectionMode = CollectionMode::NFT(2000);585586 let origin1 = Origin::signed(1);587 let origin2 = Origin::signed(2);588 let origin3 = Origin::signed(3);589590 assert_ok!(TemplateModule::create_collection(591 origin1.clone(),592 col_name1.clone(),593 col_desc1.clone(),594 token_prefix1.clone(),595 mode.clone()596 ));597 assert_ok!(TemplateModule::create_collection(598 origin2.clone(),599 col_name1.clone(),600 col_desc1.clone(),601 token_prefix1.clone(),602 mode.clone()603 ));604 assert_ok!(TemplateModule::create_collection(605 origin3.clone(),606 col_name1.clone(),607 col_desc1.clone(),608 token_prefix1.clone(),609 mode.clone()610 ));611612 assert_eq!(TemplateModule::collection(1).owner, 1);613 assert_eq!(TemplateModule::collection(2).owner, 2);614 assert_eq!(TemplateModule::collection(3).owner, 3);615616 // collection admin617 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));618 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 3));619620 assert_eq!(TemplateModule::admin_list_collection(1).contains(&2), true);621 assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), true);622623 // remove admin624 assert_ok!(TemplateModule::remove_collection_admin(625 origin2.clone(),626 1,627 3628 ));629 assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), false);630 });631}632633#[test]634fn balance_of() {635 new_test_ext().execute_with(|| {636 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();637 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();638 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();639 let nft_mode: CollectionMode = CollectionMode::NFT(2000);640 let furg_mode: CollectionMode = CollectionMode::Fungible(3);641 let refung_mode: CollectionMode = CollectionMode::ReFungible(2000, 3);642643 let origin1 = Origin::signed(1);644645 assert_ok!(TemplateModule::create_collection(646 origin1.clone(),647 col_name1.clone(),648 col_desc1.clone(),649 token_prefix1.clone(),650 nft_mode.clone()651 ));652 assert_ok!(TemplateModule::create_collection(653 origin1.clone(),654 col_name1.clone(),655 col_desc1.clone(),656 token_prefix1.clone(),657 furg_mode.clone()658 ));659 assert_ok!(TemplateModule::create_collection(660 origin1.clone(),661 col_name1.clone(),662 col_desc1.clone(),663 token_prefix1.clone(),664 refung_mode.clone()665 ));666667 assert_eq!(TemplateModule::collection(1).owner, 1);668 assert_eq!(TemplateModule::collection(2).owner, 1);669 assert_eq!(TemplateModule::collection(3).owner, 1);670671 // check balance before672 assert_eq!(TemplateModule::balance_count(1, 1), 0);673 assert_eq!(TemplateModule::balance_count(2, 1), 0);674 assert_eq!(TemplateModule::balance_count(3, 1), 0);675676 // create item677 assert_ok!(TemplateModule::create_item(678 origin1.clone(),679 1,680 [1, 1, 1].to_vec(),681 1682 ));683684 assert_ok!(TemplateModule::create_item(685 origin1.clone(),686 2,687 [].to_vec(),688 1689 ));690691 assert_ok!(TemplateModule::create_item(692 origin1.clone(),693 3,694 [1, 1, 1].to_vec(),695 1696 ));697698 // check balance (collection with id = 1, user id = 1)699 assert_eq!(TemplateModule::balance_count(1, 1), 1);700 assert_eq!(TemplateModule::balance_count(2, 1), 1000);701 assert_eq!(TemplateModule::balance_count(3, 1), 1000);702 assert_eq!(TemplateModule::nft_item_id(1, 1).owner, 1);703 assert_eq!(TemplateModule::fungible_item_id(2, 1).owner, 1);704 assert_eq!(TemplateModule::refungible_item_id(3, 1).owner[0].owner, 1);705 });706}707708#[test]709fn approve() {710 new_test_ext().execute_with(|| {711 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();712 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();713 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();714 let nft_mode: CollectionMode = CollectionMode::NFT(2000);715 let origin1 = Origin::signed(1);716717 assert_ok!(TemplateModule::create_collection(718 origin1.clone(),719 col_name1.clone(),720 col_desc1.clone(),721 token_prefix1.clone(),722 nft_mode.clone()723 ));724725 assert_eq!(TemplateModule::collection(1).owner, 1);726727 // create item728 assert_ok!(TemplateModule::create_item(729 origin1.clone(),730 1,731 [1, 1, 1].to_vec(),732 1733 ));734735 // approve736 assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));737 assert_eq!(TemplateModule::approved(1, (1, 1))[0].approved, 2);738 });739}740741#[test]742fn transfer_from() {743 new_test_ext().execute_with(|| {744 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();745 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();746 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();747 let mode: CollectionMode = CollectionMode::NFT(2000);748 let origin1 = Origin::signed(1);749 let origin2 = Origin::signed(2);750751 assert_ok!(TemplateModule::create_collection(752 origin1.clone(),753 col_name1.clone(),754 col_desc1.clone(),755 token_prefix1.clone(),756 mode757 ));758759 assert_eq!(TemplateModule::collection(1).owner, 1);760761 // create item762 assert_ok!(TemplateModule::create_item(763 origin1.clone(),764 1,765 [1, 1, 1].to_vec(),766 1767 ));768769 // approve770 assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1));771 assert_eq!(TemplateModule::approved(1, (1, 1))[0].approved, 2);772 assert_ok!(TemplateModule::transfer_from(origin2.clone(), 1, 2, 1, 1, 1));773774 // after transfer775 assert_eq!(TemplateModule::balance_count(1, 1), 0);776 assert_eq!(TemplateModule::balance_count(1, 2), 1);777 });778}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.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -16,11 +16,12 @@
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
+ traits::{
+ BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating,
+ Verify,
+ },
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, MultiSignature,
- traits::{
- BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating, Verify,
- },
};
use sp_std::prelude::*;
#[cfg(feature = "std")]
@@ -31,22 +32,24 @@
pub use balances::Call as BalancesCall;
pub use contracts::Schedule as ContractsSchedule;
pub use frame_support::{
- construct_runtime, parameter_types,
- traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason},
+ construct_runtime,
+ dispatch::DispatchResult,
+ parameter_types,
+ traits::{
+ Currency, ExistenceRequirement, Get, 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,
};
-use system::{self as system};
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
-use sp_runtime::{
- Perbill,
-};
-
+use sp_runtime::Perbill;
+use system::{self as system};
pub use timestamp::Call as TimestampCall;
@@ -492,4 +495,3 @@
}
}
}
-