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.rsdiffbeforeafterboth1//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.23use nft_runtime::{self, opaque::Block, RuntimeApi};4use sc_client_api::ExecutorProvider;5use sc_consensus::LongestChain;6use sc_executor::native_executor_instance;7pub use sc_executor::NativeExecutor;8use sc_finality_grandpa::{9 FinalityProofProvider as GrandpaFinalityProofProvider, SharedVoterState,10 StorageAndProofProvider,11};12use sc_service::{error::Error as ServiceError, AbstractService, Configuration, ServiceBuilder};13use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;14use sp_inherents::InherentDataProviders;15use std::sync::Arc;16use std::time::Duration;1718// Our native executor instance.19native_executor_instance!(20 pub Executor,21 nft_runtime::api::dispatch,22 nft_runtime::native_version,23);2425/// Starts a `ServiceBuilder` for a full service.26///27/// Use this macro if you don't actually need the full service, but just the builder in order to28/// be able to perform chain operations.29macro_rules! new_full_start {30 ($config:expr) => {{31 use jsonrpc_core::IoHandler;32 use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;33 use std::sync::Arc;3435 let mut import_setup = None;36 let inherent_data_providers = sp_inherents::InherentDataProviders::new();3738 let builder = sc_service::ServiceBuilder::new_full::<39 nft_runtime::opaque::Block,40 nft_runtime::RuntimeApi,41 crate::service::Executor,42 >($config)?43 .with_select_chain(|_config, backend| Ok(sc_consensus::LongestChain::new(backend.clone())))?44 .with_transaction_pool(|builder| {45 let pool_api = sc_transaction_pool::FullChainApi::new(builder.client().clone());46 Ok(sc_transaction_pool::BasicPool::new(47 builder.config().transaction_pool.clone(),48 std::sync::Arc::new(pool_api),49 builder.prometheus_registry(),50 ))51 })?52 .with_import_queue(53 |_config, client, mut select_chain, _transaction_pool, spawn_task_handle, registry| {54 let select_chain = select_chain55 .take()56 .ok_or_else(|| sc_service::Error::SelectChainRequired)?;5758 let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import(59 client.clone(),60 &(client.clone() as Arc<_>),61 select_chain,62 )?;6364 let aura_block_import =65 sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(66 grandpa_block_import.clone(),67 client.clone(),68 );6970 let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _>(71 sc_consensus_aura::slot_duration(&*client)?,72 aura_block_import,73 Some(Box::new(grandpa_block_import.clone())),74 None,75 client,76 inherent_data_providers.clone(),77 spawn_task_handle,78 registry,79 )?;8081 import_setup = Some((grandpa_block_import, grandpa_link));8283 Ok(import_queue)84 },85 )?86 .with_rpc_extensions(|builder| -> Result<IoHandler<sc_rpc::Metadata>, _> {87 let handler = pallet_contracts_rpc::Contracts::new(builder.client().clone());88 let delegate = pallet_contracts_rpc::ContractsApi::to_delegate(handler);8990 let mut io = IoHandler::default();91 io.extend_with(delegate);92 Ok(io)93 })?;9495 (builder, import_setup, inherent_data_providers)96 }};97}9899/// Builds a new service for a full client.100pub fn new_full(config: Configuration) -> Result<impl AbstractService, ServiceError> {101 let role = config.role.clone();102 let force_authoring = config.force_authoring;103 let name = config.network.node_name.clone();104 let disable_grandpa = config.disable_grandpa;105106 let (builder, mut import_setup, inherent_data_providers) = new_full_start!(config);107108 let (block_import, grandpa_link) = import_setup.take().expect(109 "Link Half and Block Import are present for Full Services or setup failed before. qed",110 );111112 let service = builder113 .with_finality_proof_provider(|client, backend| {114 // GenesisAuthoritySetProvider is implemented for StorageAndProofProvider115 let provider = client as Arc<dyn StorageAndProofProvider<_, _>>;116 Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, provider)) as _)117 })?118 .build_full()?;119120 if role.is_authority() {121 let proposer = sc_basic_authorship::ProposerFactory::new(122 service.client(),123 service.transaction_pool(),124 service.prometheus_registry().as_ref(),125 );126127 let client = service.client();128 let select_chain = service129 .select_chain()130 .ok_or(ServiceError::SelectChainRequired)?;131132 let can_author_with =133 sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());134135 let aura = sc_consensus_aura::start_aura::<_, _, _, _, _, AuraPair, _, _, _>(136 sc_consensus_aura::slot_duration(&*client)?,137 client,138 select_chain,139 block_import,140 proposer,141 service.network(),142 inherent_data_providers.clone(),143 force_authoring,144 service.keystore(),145 can_author_with,146 )?;147148 // the AURA authoring task is considered essential, i.e. if it149 // fails we take down the service with it.150 service151 .spawn_essential_task_handle()152 .spawn_blocking("aura", aura);153 }154155 // if the node isn't actively participating in consensus then it doesn't156 // need a keystore, regardless of which protocol we use below.157 let keystore = if role.is_authority() {158 Some(service.keystore() as sp_core::traits::BareCryptoStorePtr)159 } else {160 None161 };162163 let grandpa_config = sc_finality_grandpa::Config {164 // FIXME #1578 make this available through chainspec165 gossip_duration: Duration::from_millis(333),166 justification_period: 512,167 name: Some(name),168 observer_enabled: false,169 keystore,170 is_authority: role.is_network_authority(),171 };172173 let enable_grandpa = !disable_grandpa;174 if enable_grandpa {175 // start the full GRANDPA voter176 // NOTE: non-authorities could run the GRANDPA observer protocol, but at177 // this point the full voter should provide better guarantees of block178 // and vote data availability than the observer. The observer has not179 // been tested extensively yet and having most nodes in a network run it180 // could lead to finality stalls.181 let grandpa_config = sc_finality_grandpa::GrandpaParams {182 config: grandpa_config,183 link: grandpa_link,184 network: service.network(),185 inherent_data_providers: inherent_data_providers.clone(),186 telemetry_on_connect: Some(service.telemetry_on_connect_stream()),187 voting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(),188 prometheus_registry: service.prometheus_registry(),189 shared_voter_state: SharedVoterState::empty(),190 };191 192 // the GRANDPA voter task is considered infallible, i.e.193 // if it fails we take down the service with it.194 service.spawn_essential_task_handle().spawn_blocking(195 "grandpa-voter",196 sc_finality_grandpa::run_grandpa_voter(grandpa_config)?,197 );198 } else {199 sc_finality_grandpa::setup_disabled_grandpa(200 service.client(),201 &inherent_data_providers,202 service.network(),203 )?;204 }205206 Ok(service)207}208209/// Builds a new service for a light client.210pub fn new_light(config: Configuration) -> Result<impl AbstractService, ServiceError> {211 let inherent_data_providers = InherentDataProviders::new();212213 ServiceBuilder::new_light::<Block, RuntimeApi, Executor>(config)?214 .with_select_chain(|_config, backend| Ok(LongestChain::new(backend.clone())))?215 .with_transaction_pool(|builder| {216 let fetcher = builder217 .fetcher()218 .ok_or_else(|| "Trying to start light transaction pool without active fetcher")?;219220 let pool_api =221 sc_transaction_pool::LightChainApi::new(builder.client().clone(), fetcher.clone());222 let pool = sc_transaction_pool::BasicPool::with_revalidation_type(223 builder.config().transaction_pool.clone(),224 Arc::new(pool_api),225 builder.prometheus_registry(),226 sc_transaction_pool::RevalidationType::Light,227 );228 Ok(pool)229 })?230 .with_import_queue_and_fprb(231 |_config,232 client,233 backend,234 fetcher,235 _select_chain,236 _tx_pool,237 spawn_task_handle,238 prometheus_registry| {239 let fetch_checker = fetcher240 .map(|fetcher| fetcher.checker().clone())241 .ok_or_else(|| {242 "Trying to start light import queue without active fetch checker"243 })?;244 let grandpa_block_import = sc_finality_grandpa::light_block_import(245 client.clone(),246 backend,247 &(client.clone() as Arc<_>),248 Arc::new(fetch_checker),249 )?;250 let finality_proof_import = grandpa_block_import.clone();251 let finality_proof_request_builder =252 finality_proof_import.create_finality_proof_request_builder();253254 let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _>(255 sc_consensus_aura::slot_duration(&*client)?,256 grandpa_block_import,257 None,258 Some(Box::new(finality_proof_import)),259 client,260 inherent_data_providers.clone(),261 spawn_task_handle,262 prometheus_registry,263 )?;264265 Ok((import_queue, finality_proof_request_builder))266 },267 )?268 .with_finality_proof_provider(|client, backend| {269 // GenesisAuthoritySetProvider is implemented for StorageAndProofProvider270 let provider = client as Arc<dyn StorageAndProofProvider<_, _>>;271 Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, provider)) as _)272 })?273 .build_light()274}1//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.23use nft_runtime::{self, opaque::Block, RuntimeApi};4use sc_client_api::ExecutorProvider;5use sc_consensus::LongestChain;6use sc_executor::native_executor_instance;7pub use sc_executor::NativeExecutor;8use sc_finality_grandpa::{9 FinalityProofProvider as GrandpaFinalityProofProvider, SharedVoterState,10 StorageAndProofProvider,11};12use sc_service::{error::Error as ServiceError, AbstractService, Configuration, ServiceBuilder};13use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;14use sp_inherents::InherentDataProviders;15use std::sync::Arc;16use std::time::Duration;1718// Our native executor instance.19native_executor_instance!(20 pub Executor,21 nft_runtime::api::dispatch,22 nft_runtime::native_version,23);2425/// Starts a `ServiceBuilder` for a full service.26///27/// Use this macro if you don't actually need the full service, but just the builder in order to28/// be able to perform chain operations.29macro_rules! new_full_start {30 ($config:expr) => {{31 use jsonrpc_core::IoHandler;32 use sp_consensus_aura::sr25519::AuthorityPair as AuraPair;33 use std::sync::Arc;3435 let mut import_setup = None;36 let inherent_data_providers = sp_inherents::InherentDataProviders::new();3738 let builder = sc_service::ServiceBuilder::new_full::<39 nft_runtime::opaque::Block,40 nft_runtime::RuntimeApi,41 crate::service::Executor,42 >($config)?43 .with_select_chain(|_config, backend| Ok(sc_consensus::LongestChain::new(backend.clone())))?44 .with_transaction_pool(|builder| {45 let pool_api = sc_transaction_pool::FullChainApi::new(builder.client().clone());46 Ok(sc_transaction_pool::BasicPool::new(47 builder.config().transaction_pool.clone(),48 std::sync::Arc::new(pool_api),49 builder.prometheus_registry(),50 ))51 })?52 .with_import_queue(53 |_config, client, mut select_chain, _transaction_pool, spawn_task_handle, registry| {54 let select_chain = select_chain55 .take()56 .ok_or_else(|| sc_service::Error::SelectChainRequired)?;5758 let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import(59 client.clone(),60 &(client.clone() as Arc<_>),61 select_chain,62 )?;6364 let aura_block_import =65 sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(66 grandpa_block_import.clone(),67 client.clone(),68 );6970 let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _>(71 sc_consensus_aura::slot_duration(&*client)?,72 aura_block_import,73 Some(Box::new(grandpa_block_import.clone())),74 None,75 client,76 inherent_data_providers.clone(),77 spawn_task_handle,78 registry,79 )?;8081 import_setup = Some((grandpa_block_import, grandpa_link));8283 Ok(import_queue)84 },85 )?86 .with_rpc_extensions(|builder| -> Result<IoHandler<sc_rpc::Metadata>, _> {87 let handler = pallet_contracts_rpc::Contracts::new(builder.client().clone());88 let delegate = pallet_contracts_rpc::ContractsApi::to_delegate(handler);8990 let mut io = IoHandler::default();91 io.extend_with(delegate);92 Ok(io)93 })?;9495 (builder, import_setup, inherent_data_providers)96 }};97}9899/// Builds a new service for a full client.100pub fn new_full(config: Configuration) -> Result<impl AbstractService, ServiceError> {101 let role = config.role.clone();102 let force_authoring = config.force_authoring;103 let name = config.network.node_name.clone();104 let disable_grandpa = config.disable_grandpa;105106 let (builder, mut import_setup, inherent_data_providers) = new_full_start!(config);107108 let (block_import, grandpa_link) = import_setup.take().expect(109 "Link Half and Block Import are present for Full Services or setup failed before. qed",110 );111112 let service = builder113 .with_finality_proof_provider(|client, backend| {114 // GenesisAuthoritySetProvider is implemented for StorageAndProofProvider115 let provider = client as Arc<dyn StorageAndProofProvider<_, _>>;116 Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, provider)) as _)117 })?118 .build_full()?;119120 if role.is_authority() {121 let proposer = sc_basic_authorship::ProposerFactory::new(122 service.client(),123 service.transaction_pool(),124 service.prometheus_registry().as_ref(),125 );126127 let client = service.client();128 let select_chain = service129 .select_chain()130 .ok_or(ServiceError::SelectChainRequired)?;131132 let can_author_with =133 sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());134135 let aura = sc_consensus_aura::start_aura::<_, _, _, _, _, AuraPair, _, _, _>(136 sc_consensus_aura::slot_duration(&*client)?,137 client,138 select_chain,139 block_import,140 proposer,141 service.network(),142 inherent_data_providers.clone(),143 force_authoring,144 service.keystore(),145 can_author_with,146 )?;147148 // the AURA authoring task is considered essential, i.e. if it149 // fails we take down the service with it.150 service151 .spawn_essential_task_handle()152 .spawn_blocking("aura", aura);153 }154155 // if the node isn't actively participating in consensus then it doesn't156 // need a keystore, regardless of which protocol we use below.157 let keystore = if role.is_authority() {158 Some(service.keystore() as sp_core::traits::BareCryptoStorePtr)159 } else {160 None161 };162163 let grandpa_config = sc_finality_grandpa::Config {164 // FIXME #1578 make this available through chainspec165 gossip_duration: Duration::from_millis(333),166 justification_period: 512,167 name: Some(name),168 observer_enabled: false,169 keystore,170 is_authority: role.is_network_authority(),171 };172173 let enable_grandpa = !disable_grandpa;174 if enable_grandpa {175 // start the full GRANDPA voter176 // NOTE: non-authorities could run the GRANDPA observer protocol, but at177 // this point the full voter should provide better guarantees of block178 // and vote data availability than the observer. The observer has not179 // been tested extensively yet and having most nodes in a network run it180 // could lead to finality stalls.181 let grandpa_config = sc_finality_grandpa::GrandpaParams {182 config: grandpa_config,183 link: grandpa_link,184 network: service.network(),185 inherent_data_providers: inherent_data_providers.clone(),186 telemetry_on_connect: Some(service.telemetry_on_connect_stream()),187 voting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(),188 prometheus_registry: service.prometheus_registry(),189 shared_voter_state: SharedVoterState::empty(),190 };191192 // the GRANDPA voter task is considered infallible, i.e.193 // if it fails we take down the service with it.194 service.spawn_essential_task_handle().spawn_blocking(195 "grandpa-voter",196 sc_finality_grandpa::run_grandpa_voter(grandpa_config)?,197 );198 } else {199 sc_finality_grandpa::setup_disabled_grandpa(200 service.client(),201 &inherent_data_providers,202 service.network(),203 )?;204 }205206 Ok(service)207}208209/// Builds a new service for a light client.210pub fn new_light(config: Configuration) -> Result<impl AbstractService, ServiceError> {211 let inherent_data_providers = InherentDataProviders::new();212213 ServiceBuilder::new_light::<Block, RuntimeApi, Executor>(config)?214 .with_select_chain(|_config, backend| Ok(LongestChain::new(backend.clone())))?215 .with_transaction_pool(|builder| {216 let fetcher = builder217 .fetcher()218 .ok_or_else(|| "Trying to start light transaction pool without active fetcher")?;219220 let pool_api =221 sc_transaction_pool::LightChainApi::new(builder.client().clone(), fetcher.clone());222 let pool = sc_transaction_pool::BasicPool::with_revalidation_type(223 builder.config().transaction_pool.clone(),224 Arc::new(pool_api),225 builder.prometheus_registry(),226 sc_transaction_pool::RevalidationType::Light,227 );228 Ok(pool)229 })?230 .with_import_queue_and_fprb(231 |_config,232 client,233 backend,234 fetcher,235 _select_chain,236 _tx_pool,237 spawn_task_handle,238 prometheus_registry| {239 let fetch_checker = fetcher240 .map(|fetcher| fetcher.checker().clone())241 .ok_or_else(|| {242 "Trying to start light import queue without active fetch checker"243 })?;244 let grandpa_block_import = sc_finality_grandpa::light_block_import(245 client.clone(),246 backend,247 &(client.clone() as Arc<_>),248 Arc::new(fetch_checker),249 )?;250 let finality_proof_import = grandpa_block_import.clone();251 let finality_proof_request_builder =252 finality_proof_import.create_finality_proof_request_builder();253254 let import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _>(255 sc_consensus_aura::slot_duration(&*client)?,256 grandpa_block_import,257 None,258 Some(Box::new(finality_proof_import)),259 client,260 inherent_data_providers.clone(),261 spawn_task_handle,262 prometheus_registry,263 )?;264265 Ok((import_queue, finality_proof_request_builder))266 },267 )?268 .with_finality_proof_provider(|client, backend| {269 // GenesisAuthoritySetProvider is implemented for StorageAndProofProvider270 let provider = client as Arc<dyn StorageAndProofProvider<_, _>>;271 Ok(Arc::new(GrandpaFinalityProofProvider::new(backend, provider)) as _)272 })?273 .build_light()274}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.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 @@
}
}
}
-