difftreelog
Merge pull request #153 from usetech-llc/feature/NFTPAR-536_code_style
in: master
Enforce codestyle
117 files changed
.devcontainer/devcontainer.jsondiffbeforeafterboth12 }12 }13 },13 },14 "extensions": [14 "extensions": [15 "matklad.rust-analyzer"15 "matklad.rust-analyzer",16 "dbaeumer.vscode-eslint"16 ],17 ],17 "remoteUser": "vscode"18 "remoteUser": "vscode"18}19}.github/workflows/codestyle.ymldiffbeforeafterbothno changes
.github/workflows/tests_codestyle.ymldiffbeforeafterbothno changes
.rustfmt.tomldiffbeforeafterbothno changes
.vscode/extensions.jsondiffbeforeafterbothno changes
.vscode/settings.jsondiffbeforeafterbothno changes
Cargo.lockdiffbeforeafterboth5993 "sp-std",5993 "sp-std",5994]5994]59955996[[package]]5997name = "pallet-scheduler"5998version = "3.0.0"5999source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.3#c94e0cdfe5556680dca1996004751eeb114755d7"6000dependencies = [6001 "frame-benchmarking",6002 "frame-support",6003 "frame-system",6004 "log",6005 "parity-scale-codec 2.1.3",6006 "sp-io",6007 "sp-runtime",6008 "sp-std",6009]601059956011[[package]]5996[[package]]6012name = "pallet-scheduler"5997name = "pallet-scheduler"6026 "up-sponsorship",6011 "up-sponsorship",6027]6012]60136014[[package]]6015name = "pallet-scheduler"6016version = "3.0.0"6017source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.3#c94e0cdfe5556680dca1996004751eeb114755d7"6018dependencies = [6019 "frame-benchmarking",6020 "frame-support",6021 "frame-system",6022 "log",6023 "parity-scale-codec 2.1.3",6024 "sp-io",6025 "sp-runtime",6026 "sp-std",6027]602860286029[[package]]6029[[package]]6030name = "pallet-session"6030name = "pallet-session"README.mddiffbeforeafterboth228## Running Integration Tests228## Running Integration Tests229229230See [tests/README.md](./tests/README.md).230See [tests/README.md](./tests/README.md).231231232## Code Formatting233234### Get formatter and linter settings into your branch (if you forked before they were introduced)235```bash236git cherry-pick -n 8ff77c21b0d30b2a4648fa35dbf61dfa9d3948a7237```238239### Apply formatting and clippy fixes240```bash241cargo clippy242cargo fmt243```244245### Format tests246```bash247pushd tests && yarn fix ; popd248```249250### Check code style in tests251```bash252cd tests && yarn eslint --ext .ts,.js src/253```crates/evm-coder-macros/src/lib.rsdiffbeforeafterboth1#![allow(dead_code)]21use darling::FromMeta;3use darling::FromMeta;2use inflector::cases;4use inflector::cases;crates/evm-coder-macros/src/solidity_interface.rsdiffbeforeafterboth1#![allow(dead_code)]21use quote::quote;3use quote::quote;2use darling::FromMeta;4use darling::FromMeta;262 ReturnType::Type(_, ty) => ty,264 ReturnType::Type(_, ty) => ty,263 _ => return Err(syn::Error::new(value.sig.output.span(), "interface method should return Result<value>\nif there is no value to return - specify void (which is alias to unit)")),265 _ => return Err(syn::Error::new(value.sig.output.span(), "interface method should return Result<value>\nif there is no value to return - specify void (which is alias to unit)")),264 };266 };265 let result = parse_result_ok(&result)?;267 let result = parse_result_ok(result)?;266268267 let camel_name = info269 let camel_name = info268 .rename_selector270 .rename_selector283 Ok(Self {285 Ok(Self {284 name: ident.clone(),286 name: ident.clone(),285 camel_name,287 camel_name,286 pascal_name: snake_ident_to_pascal(&ident),288 pascal_name: snake_ident_to_pascal(ident),287 screaming_name: snake_ident_to_screaming(&ident),289 screaming_name: snake_ident_to_screaming(ident),288 selector_str,290 selector_str,289 selector,291 selector,290 args,292 args,431 found_error = true;433 found_error = true;432 }434 }433 }435 }434 TraitItem::Method(method) => methods.push(Method::try_from(&method)?),436 TraitItem::Method(method) => methods.push(Method::try_from(method)?),435 _ => {}437 _ => {}436 }438 }437 }439 }545 #(547 #(546 #call_inner548 #call_inner547 )*549 )*550 #[allow(unreachable_code)] // In case of no inner calls548 fn call(&mut self, c: Msg<#call_name>) -> ::core::result::Result<::evm_coder::abi::AbiWriter, Self::Error> {551 fn call(&mut self, c: Msg<#call_name>) -> ::core::result::Result<::evm_coder::abi::AbiWriter, Self::Error> {549 use ::evm_coder::abi::AbiWrite;552 use ::evm_coder::abi::AbiWrite;550 type InternalCall = #call_name;553 type InternalCall = #call_name;crates/evm-coder-macros/src/to_log.rsdiffbeforeafterboth41impl Event {41impl Event {42 fn try_from(variant: &Variant) -> syn::Result<Self> {42 fn try_from(variant: &Variant) -> syn::Result<Self> {43 let name = &variant.ident;43 let name = &variant.ident;44 let name_screaming = snake_ident_to_screaming(&name);44 let name_screaming = snake_ident_to_screaming(name);454546 let named = match &variant.fields {46 let named = match &variant.fields {47 Fields::Named(named) => named,47 Fields::Named(named) => named,54 };54 };55 let mut fields = Vec::new();55 let mut fields = Vec::new();56 for field in &named.named {56 for field in &named.named {57 fields.push(EventField::try_from(&field)?);57 fields.push(EventField::try_from(field)?);58 }58 }59 let mut selector_str = format!("{}(", name);59 let mut selector_str = format!("{}(", name);60 for (i, arg) in fields.iter().enumerate() {60 for (i, arg) in fields.iter().enumerate() {crates/evm-coder/src/abi.rsdiffbeforeafterboth104 fn subresult(&mut self) -> Result<AbiReader<'i>> {104 fn subresult(&mut self) -> Result<AbiReader<'i>> {105 let offset = self.read_usize()?;105 let offset = self.read_usize()?;106 Ok(AbiReader {106 Ok(AbiReader {107 buf: &self.buf,107 buf: self.buf,108 offset: offset + self.offset,108 offset: offset + self.offset,109 })109 })110 }110 }252impl_abi_writeable!(&str, string);252impl_abi_writeable!(&str, string);253impl AbiWrite for &string {253impl AbiWrite for &string {254 fn abi_write(&self, writer: &mut AbiWriter) {254 fn abi_write(&self, writer: &mut AbiWriter) {255 writer.string(&self)255 writer.string(self)256 }256 }257}257}258258crates/evm-coder/tests/a.rsdiffbeforeafterboth1#![allow(dead_code)] // This test only checks that macros is not panicking21use evm_coder::{solidity_interface, types::*, ToLog};3use evm_coder::{solidity_interface, types::*, ToLog};2use evm_coder_macros::solidity;4use evm_coder_macros::solidity;node/cli/Cargo.tomldiffbeforeafterboth334[build-dependencies.substrate-build-script-utils]4[build-dependencies.substrate-build-script-utils]5git = 'https://github.com/paritytech/substrate.git'5git = 'https://github.com/paritytech/substrate.git'6branch = 'polkadot-v0.9.3'6branch = 'polkadot-v0.9.7'7version = '3.0.0'7version = '3.0.0'889################################################################################9################################################################################171718[dependencies.frame-benchmarking]18[dependencies.frame-benchmarking]19git = 'https://github.com/paritytech/substrate.git'19git = 'https://github.com/paritytech/substrate.git'20branch = 'polkadot-v0.9.3'20branch = 'polkadot-v0.9.7'21version = '3.0.0'21version = '3.0.0'222223[dependencies.frame-benchmarking-cli]23[dependencies.frame-benchmarking-cli]24git = 'https://github.com/paritytech/substrate.git'24git = 'https://github.com/paritytech/substrate.git'25branch = 'polkadot-v0.9.3'25branch = 'polkadot-v0.9.7'26version = '3.0.0'26version = '3.0.0'272728[dependencies.pallet-transaction-payment-rpc]28[dependencies.pallet-transaction-payment-rpc]29git = 'https://github.com/paritytech/substrate.git'29git = 'https://github.com/paritytech/substrate.git'30branch = 'polkadot-v0.9.3'30branch = 'polkadot-v0.9.7'31version = '3.0.0'31version = '3.0.0'323233[dependencies.substrate-prometheus-endpoint]33[dependencies.substrate-prometheus-endpoint]34git = 'https://github.com/paritytech/substrate.git'34git = 'https://github.com/paritytech/substrate.git'35branch = 'polkadot-v0.9.3'35branch = 'polkadot-v0.9.7'36version = '0.9.0'36version = '0.9.0'373738[dependencies.sc-basic-authorship]38[dependencies.sc-basic-authorship]39git = 'https://github.com/paritytech/substrate.git'39git = 'https://github.com/paritytech/substrate.git'40branch = 'polkadot-v0.9.3'40branch = 'polkadot-v0.9.7'41version = '0.9.0'41version = '0.9.0'424243[dependencies.sc-chain-spec]43[dependencies.sc-chain-spec]44git = 'https://github.com/paritytech/substrate.git'44git = 'https://github.com/paritytech/substrate.git'45branch = 'polkadot-v0.9.3'45branch = 'polkadot-v0.9.7'46version = '3.0.0'46version = '3.0.0'474748[dependencies.sc-cli]48[dependencies.sc-cli]49features = ['wasmtime']49features = ['wasmtime']50git = 'https://github.com/paritytech/substrate.git'50git = 'https://github.com/paritytech/substrate.git'51branch = 'polkadot-v0.9.3'51branch = 'polkadot-v0.9.7'52version = '0.9.0'52version = '0.9.0'535354[dependencies.sc-client-api]54[dependencies.sc-client-api]55git = 'https://github.com/paritytech/substrate.git'55git = 'https://github.com/paritytech/substrate.git'56branch = 'polkadot-v0.9.3'56branch = 'polkadot-v0.9.7'57version = '3.0.0'57version = '3.0.0'585859[dependencies.sc-consensus]59[dependencies.sc-consensus]60git = 'https://github.com/paritytech/substrate.git'60git = 'https://github.com/paritytech/substrate.git'61branch = 'polkadot-v0.9.3'61branch = 'polkadot-v0.9.7'62version = '0.9.0'62version = '0.9.0'636364[dependencies.sc-consensus-aura]64[dependencies.sc-consensus-aura]65git = 'https://github.com/paritytech/substrate.git'65git = 'https://github.com/paritytech/substrate.git'66branch = 'polkadot-v0.9.3'66branch = 'polkadot-v0.9.7'67version = '0.9.0'67version = '0.9.0'686869[dependencies.sc-executor]69[dependencies.sc-executor]70features = ['wasmtime']70features = ['wasmtime']71git = 'https://github.com/paritytech/substrate.git'71git = 'https://github.com/paritytech/substrate.git'72branch = 'polkadot-v0.9.3'72branch = 'polkadot-v0.9.7'73version = '0.9.0'73version = '0.9.0'747475[dependencies.sc-finality-grandpa]75[dependencies.sc-finality-grandpa]76git = 'https://github.com/paritytech/substrate.git'76git = 'https://github.com/paritytech/substrate.git'77branch = 'polkadot-v0.9.3'77branch = 'polkadot-v0.9.7'78version = '0.9.0'78version = '0.9.0'797980[dependencies.sc-keystore]80[dependencies.sc-keystore]81git = 'https://github.com/paritytech/substrate.git'81git = 'https://github.com/paritytech/substrate.git'82branch = 'polkadot-v0.9.3'82branch = 'polkadot-v0.9.7'83version = '3.0.0'83version = '3.0.0'848485[dependencies.sc-rpc]85[dependencies.sc-rpc]86git = 'https://github.com/paritytech/substrate.git'86git = 'https://github.com/paritytech/substrate.git'87branch = 'polkadot-v0.9.3'87branch = 'polkadot-v0.9.7'88version = '3.0.0'88version = '3.0.0'898990[dependencies.sc-rpc-api]90[dependencies.sc-rpc-api]91git = 'https://github.com/paritytech/substrate.git'91git = 'https://github.com/paritytech/substrate.git'92branch = 'polkadot-v0.9.3'92branch = 'polkadot-v0.9.7'93version = '0.9.0'93version = '0.9.0'949495[dependencies.sc-service]95[dependencies.sc-service]96features = ['wasmtime']96features = ['wasmtime']97git = 'https://github.com/paritytech/substrate.git'97git = 'https://github.com/paritytech/substrate.git'98branch = 'polkadot-v0.9.3'98branch = 'polkadot-v0.9.7'99version = '0.9.0'99version = '0.9.0'100100101[dependencies.sc-telemetry]101[dependencies.sc-telemetry]102git = 'https://github.com/paritytech/substrate.git'102git = 'https://github.com/paritytech/substrate.git'103branch = 'polkadot-v0.9.3'103branch = 'polkadot-v0.9.7'104version = '3.0.0'104version = '3.0.0'105105106[dependencies.sc-transaction-pool]106[dependencies.sc-transaction-pool]107git = 'https://github.com/paritytech/substrate.git'107git = 'https://github.com/paritytech/substrate.git'108branch = 'polkadot-v0.9.3'108branch = 'polkadot-v0.9.7'109version = '3.0.0'109version = '3.0.0'110110111[dependencies.sc-tracing]111[dependencies.sc-tracing]112git = 'https://github.com/paritytech/substrate.git'112git = 'https://github.com/paritytech/substrate.git'113branch = 'polkadot-v0.9.3'113branch = 'polkadot-v0.9.7'114version = '3.0.0'114version = '3.0.0'115115116[dependencies.sp-block-builder]116[dependencies.sp-block-builder]117git = 'https://github.com/paritytech/substrate.git'117git = 'https://github.com/paritytech/substrate.git'118branch = 'polkadot-v0.9.3'118branch = 'polkadot-v0.9.7'119version = '3.0.0'119version = '3.0.0'120120121[dependencies.sp-api]121[dependencies.sp-api]122git = 'https://github.com/paritytech/substrate.git'122git = 'https://github.com/paritytech/substrate.git'123branch = 'polkadot-v0.9.3'123branch = 'polkadot-v0.9.7'124version = '3.0.0'124version = '3.0.0'125125126[dependencies.sp-blockchain]126[dependencies.sp-blockchain]127git = 'https://github.com/paritytech/substrate.git'127git = 'https://github.com/paritytech/substrate.git'128branch = 'polkadot-v0.9.3'128branch = 'polkadot-v0.9.7'129version = '3.0.0'129version = '3.0.0'130130131[dependencies.sp-consensus]131[dependencies.sp-consensus]132git = 'https://github.com/paritytech/substrate.git'132git = 'https://github.com/paritytech/substrate.git'133branch = 'polkadot-v0.9.3'133branch = 'polkadot-v0.9.7'134version = '0.9.0'134version = '0.9.0'135135136[dependencies.sp-consensus-aura]136[dependencies.sp-consensus-aura]137git = 'https://github.com/paritytech/substrate.git'137git = 'https://github.com/paritytech/substrate.git'138branch = 'polkadot-v0.9.3'138branch = 'polkadot-v0.9.7'139version = '0.9.0'139version = '0.9.0'140140141[dependencies.sp-core]141[dependencies.sp-core]142git = 'https://github.com/paritytech/substrate.git'142git = 'https://github.com/paritytech/substrate.git'143branch = 'polkadot-v0.9.3'143branch = 'polkadot-v0.9.7'144version = '3.0.0'144version = '3.0.0'145145146[dependencies.sp-finality-grandpa]146[dependencies.sp-finality-grandpa]147git = 'https://github.com/paritytech/substrate.git'147git = 'https://github.com/paritytech/substrate.git'148branch = 'polkadot-v0.9.3'148branch = 'polkadot-v0.9.7'149version = '3.0.0'149version = '3.0.0'150150151[dependencies.sp-inherents]151[dependencies.sp-inherents]152git = 'https://github.com/paritytech/substrate.git'152git = 'https://github.com/paritytech/substrate.git'153branch = 'polkadot-v0.9.3'153branch = 'polkadot-v0.9.7'154version = '3.0.0'154version = '3.0.0'155155156[dependencies.sp-keystore]156[dependencies.sp-keystore]157git = 'https://github.com/paritytech/substrate.git'157git = 'https://github.com/paritytech/substrate.git'158branch = 'polkadot-v0.9.3'158branch = 'polkadot-v0.9.7'159version = '0.9.0'159version = '0.9.0'160160161[dependencies.sp-offchain]161[dependencies.sp-offchain]162git = 'https://github.com/paritytech/substrate.git'162git = 'https://github.com/paritytech/substrate.git'163branch = 'polkadot-v0.9.3'163branch = 'polkadot-v0.9.7'164version = '3.0.0'164version = '3.0.0'165165166[dependencies.sp-runtime]166[dependencies.sp-runtime]167git = 'https://github.com/paritytech/substrate.git'167git = 'https://github.com/paritytech/substrate.git'168branch = 'polkadot-v0.9.3'168branch = 'polkadot-v0.9.7'169version = '3.0.0'169version = '3.0.0'170170171[dependencies.sp-session]171[dependencies.sp-session]172git = 'https://github.com/paritytech/substrate.git'172git = 'https://github.com/paritytech/substrate.git'173branch = 'polkadot-v0.9.3'173branch = 'polkadot-v0.9.7'174version = '3.0.0'174version = '3.0.0'175175176[dependencies.sp-timestamp]176[dependencies.sp-timestamp]177git = 'https://github.com/paritytech/substrate.git'177git = 'https://github.com/paritytech/substrate.git'178branch = 'polkadot-v0.9.3'178branch = 'polkadot-v0.9.7'179version = '3.0.0'179version = '3.0.0'180180181[dependencies.sp-transaction-pool]181[dependencies.sp-transaction-pool]182git = 'https://github.com/paritytech/substrate.git'182git = 'https://github.com/paritytech/substrate.git'183branch = 'polkadot-v0.9.3'183branch = 'polkadot-v0.9.7'184version = '3.0.0'184version = '3.0.0'185185186[dependencies.sp-trie]186[dependencies.sp-trie]187git = 'https://github.com/paritytech/substrate.git'187git = 'https://github.com/paritytech/substrate.git'188branch = 'polkadot-v0.9.3'188branch = 'polkadot-v0.9.7'189version = '3.0.0'189version = '3.0.0'190190191[dependencies.substrate-frame-rpc-system]191[dependencies.substrate-frame-rpc-system]192git = 'https://github.com/paritytech/substrate.git'192git = 'https://github.com/paritytech/substrate.git'193branch = 'polkadot-v0.9.3'193branch = 'polkadot-v0.9.7'194version = '3.0.0'194version = '3.0.0'195195196[dependencies.pallet-contracts]196[dependencies.pallet-contracts]197git = 'https://github.com/paritytech/substrate.git'197git = 'https://github.com/paritytech/substrate.git'198branch = 'polkadot-v0.9.3'198branch = 'polkadot-v0.9.7'199version = '3.0.0'199version = '3.0.0'200200201[dependencies.pallet-contracts-rpc]201[dependencies.pallet-contracts-rpc]202git = 'https://github.com/paritytech/substrate.git'202git = 'https://github.com/paritytech/substrate.git'203branch = 'polkadot-v0.9.3'203branch = 'polkadot-v0.9.7'204version = '3.0.0'204version = '3.0.0'205205206206207[dependencies.sc-network]207[dependencies.sc-network]208git = 'https://github.com/paritytech/substrate.git'208git = 'https://github.com/paritytech/substrate.git'209branch = 'polkadot-v0.9.3'209branch = 'polkadot-v0.9.7'210version = '0.9.0'210version = '0.9.0'211211212[dependencies.serde]212[dependencies.serde]222222223[dependencies.cumulus-client-consensus-aura]223[dependencies.cumulus-client-consensus-aura]224git = 'https://github.com/paritytech/cumulus.git'224git = 'https://github.com/paritytech/cumulus.git'225branch = 'polkadot-v0.9.3'225branch = 'polkadot-v0.9.7'226226227[dependencies.cumulus-client-consensus-common]227[dependencies.cumulus-client-consensus-common]228git = 'https://github.com/paritytech/cumulus.git'228git = 'https://github.com/paritytech/cumulus.git'229branch = 'polkadot-v0.9.3'229branch = 'polkadot-v0.9.7'230230231[dependencies.cumulus-client-collator]231[dependencies.cumulus-client-collator]232git = 'https://github.com/paritytech/cumulus.git'232git = 'https://github.com/paritytech/cumulus.git'233branch = 'polkadot-v0.9.3'233branch = 'polkadot-v0.9.7'234234235[dependencies.cumulus-client-cli]235[dependencies.cumulus-client-cli]236git = 'https://github.com/paritytech/cumulus.git'236git = 'https://github.com/paritytech/cumulus.git'237branch = 'polkadot-v0.9.3'237branch = 'polkadot-v0.9.7'238238239[dependencies.cumulus-client-network]239[dependencies.cumulus-client-network]240git = 'https://github.com/paritytech/cumulus.git'240git = 'https://github.com/paritytech/cumulus.git'241branch = 'polkadot-v0.9.3'241branch = 'polkadot-v0.9.7'242242243[dependencies.cumulus-primitives-core]243[dependencies.cumulus-primitives-core]244git = 'https://github.com/paritytech/cumulus.git'244git = 'https://github.com/paritytech/cumulus.git'245branch = 'polkadot-v0.9.3'245branch = 'polkadot-v0.9.7'246246247[dependencies.cumulus-primitives-parachain-inherent]247[dependencies.cumulus-primitives-parachain-inherent]248git = 'https://github.com/paritytech/cumulus.git'248git = 'https://github.com/paritytech/cumulus.git'249branch = 'polkadot-v0.9.3'249branch = 'polkadot-v0.9.7'250250251[dependencies.cumulus-client-service]251[dependencies.cumulus-client-service]252git = 'https://github.com/paritytech/cumulus.git'252git = 'https://github.com/paritytech/cumulus.git'253branch = 'polkadot-v0.9.3'253branch = 'polkadot-v0.9.7'254254255255256################################################################################256################################################################################257# Polkadot dependencies257# Polkadot dependencies258[dependencies.polkadot-primitives]258[dependencies.polkadot-primitives]259git = "https://github.com/paritytech/polkadot"259git = "https://github.com/paritytech/polkadot"260branch = 'release-v0.9.3'260branch = 'release-v0.9.7'261261262[dependencies.polkadot-service]262[dependencies.polkadot-service]263git = "https://github.com/paritytech/polkadot"263git = "https://github.com/paritytech/polkadot"264branch = 'release-v0.9.3'264branch = 'release-v0.9.7'265265266[dependencies.polkadot-cli]266[dependencies.polkadot-cli]267git = "https://github.com/paritytech/polkadot"267git = "https://github.com/paritytech/polkadot"268branch = 'release-v0.9.3'268branch = 'release-v0.9.7'269269270[dependencies.polkadot-test-service]270[dependencies.polkadot-test-service]271git = "https://github.com/paritytech/polkadot"271git = "https://github.com/paritytech/polkadot"272branch = 'release-v0.9.3'272branch = 'release-v0.9.7'273273274[dependencies.polkadot-parachain]274[dependencies.polkadot-parachain]275git = "https://github.com/paritytech/polkadot"275git = "https://github.com/paritytech/polkadot"276branch = 'release-v0.9.3'276branch = 'release-v0.9.7'277277278278279################################################################################279################################################################################322fc-rpc = { version = "2.0.0-dev", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }322fc-rpc = { version = "2.0.0-dev", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }323fc-db = { version = "1.0.0", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }323fc-db = { version = "1.0.0", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }324fp-rpc = { version = "2.0.0", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }324fp-rpc = { version = "2.0.0", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }325pallet-ethereum = { version = "2.0.0-dev", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }325pallet-ethereum = { version = "3.0.0-dev", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }326326327nft-rpc = { path = "../rpc" }327nft-rpc = { path = "../rpc" }328328node/cli/build.rsdiffbeforeafterbothno syntactic changes
node/cli/src/chain_spec.rsdiffbeforeafterboth64 // ID64 // ID65 "dev",65 "dev",66 ChainType::Local,66 ChainType::Local,67 move || testnet_genesis(67 move || {68 testnet_genesis(68 // Sudo account69 // Sudo account69 get_account_id_from_seed::<sr25519::Public>("Alice"),70 get_account_id_from_seed::<sr25519::Public>("Alice"),78 ],79 ],79 id,80 id,80 ),81 )82 },81 // Bootnodes83 // Bootnodes82 vec![],84 vec![],83 // Telemetry85 // Telemetry101 // ID103 // ID102 "local_testnet",104 "local_testnet",103 ChainType::Local,105 ChainType::Local,104 move || testnet_genesis(106 move || {107 testnet_genesis(105 // Sudo account108 // Sudo account106 get_account_id_from_seed::<sr25519::Public>("Alice"),109 get_account_id_from_seed::<sr25519::Public>("Alice"),125 ],128 ],126 id,129 id,127 ),130 )131 },128 // Bootnodes132 // Bootnodes129 vec![],133 vec![],130 // Telemetry134 // Telemetry159 .to_vec(),160 .to_vec(),160 changes_trie_config: Default::default(),161 changes_trie_config: Default::default(),161 },162 },162 pallet_balances: BalancesConfig {163 balances: BalancesConfig {163 balances: endowed_accounts164 balances: endowed_accounts164 .iter()165 .iter()165 .cloned()166 .cloned()166 .map(|k| (k, 1 << 70))167 .map(|k| (k, 1 << 70))167 .collect(),168 .collect(),168 },169 },169 pallet_treasury: Default::default(),170 treasury: Default::default(),170 pallet_sudo: SudoConfig { key: root_key },171 sudo: SudoConfig { key: root_key },171 pallet_vesting: VestingConfig {172 vesting: VestingConfig {172 vesting: vested_accounts173 vesting: vested_accounts173 .iter()174 .iter()174 .cloned()175 .cloned()175 .map(|k| (k, 1000, 100, 1 << 98))176 .map(|k| (k, 1000, 100, 1 << 98))176 .collect(),177 .collect(),177 },178 },178 pallet_nft: NftConfig {179 nft: NftConfig {179 collection_id: vec![(180 collection_id: vec![(180 1,181 1,181 Collection {182 Collection {190 offchain_schema: vec![],191 offchain_schema: vec![],191 schema_version: SchemaVersion::default(),192 schema_version: SchemaVersion::default(),192 sponsorship: SponsorshipState::Confirmed(get_account_id_from_seed::<sr25519::Public>("Alice")),193 sponsorship: SponsorshipState::Confirmed(get_account_id_from_seed::<194 sr25519::Public,195 >("Alice")),193 const_on_chain_schema: vec![],196 const_on_chain_schema: vec![],194 variable_on_chain_schema: vec![],197 variable_on_chain_schema: vec![],195 limits: CollectionLimits::default()198 limits: CollectionLimits::default(),196 },199 },197 )],200 )],198 nft_item_id: vec![],201 nft_item_id: vec![],212 },215 },213 },216 },214 parachain_info: nft_runtime::ParachainInfoConfig { parachain_id: id },217 parachain_info: nft_runtime::ParachainInfoConfig { parachain_id: id },215 pallet_aura: nft_runtime::AuraConfig {218 aura: nft_runtime::AuraConfig {216 authorities: initial_authorities,219 authorities: initial_authorities,217 },220 },218 cumulus_pallet_aura_ext: Default::default(),221 aura_ext: Default::default(),219 pallet_evm: EVMConfig {222 evm: EVMConfig {220 accounts: BTreeMap::new(),223 accounts: BTreeMap::new(),221 },224 },222 pallet_ethereum: EthereumConfig {},225 ethereum: EthereumConfig {},223 }226 }224}227}225228node/cli/src/cli.rsdiffbeforeafterboth1use crate::chain_spec;1use crate::chain_spec;2use cumulus_client_cli;3use sc_cli;4use std::path::PathBuf;2use std::path::PathBuf;5use structopt::StructOpt;3use structopt::StructOpt;64node/cli/src/command.rsdiffbeforeafterboth18use crate::{18use crate::{19 chain_spec,19 chain_spec,20 cli::{Cli, RelayChainCli, Subcommand},20 cli::{Cli, RelayChainCli, Subcommand},21 service::{new_partial, ParachainRuntimeExecutor}21 service::{new_partial, ParachainRuntimeExecutor},22};22};23use codec::Encode;23use codec::Encode;24use cumulus_primitives_core::ParaId;24use cumulus_primitives_core::ParaId;31 NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli,31 NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli,32};32};33use sc_service::{33use sc_service::{34 config::{BasePath, PrometheusConfig}34 config::{BasePath, PrometheusConfig},35};35};36use sp_core::hexdisplay::HexDisplay;36use sp_core::hexdisplay::HexDisplay;37use sp_runtime::traits::Block as BlockT;37use sp_runtime::traits::Block as BlockT;120 }120 }121121122 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {122 fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {123 polkadot_cli::Cli::from_iter([RelayChainCli::executable_name().to_string()].iter())123 polkadot_cli::Cli::from_iter([RelayChainCli::executable_name()].iter()).load_spec(id)124 .load_spec(id)125 }124 }126125129 }128 }130}129}131130131#[allow(clippy::borrowed_box)]132fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {132fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> {133 let mut storage = chain_spec.build_storage()?;133 let mut storage = chain_spec.build_storage()?;134134189 runner.sync_run(|config| {189 runner.sync_run(|config| {190 let polkadot_cli = RelayChainCli::new(190 let polkadot_cli = RelayChainCli::new(191 &config,191 &config,192 [RelayChainCli::executable_name().to_string()]192 [RelayChainCli::executable_name()]193 .iter()193 .iter()194 .chain(cli.relaychain_args.iter()),194 .chain(cli.relaychain_args.iter()),195 );195 );251 }251 }252252253 Ok(())253 Ok(())254 },254 }255 Some(Subcommand::Benchmark(cmd)) => {255 Some(Subcommand::Benchmark(cmd)) => {256 if cfg!(feature = "runtime-benchmarks") {256 if cfg!(feature = "runtime-benchmarks") {257 let runner = cli.create_runner(cmd)?;257 let runner = cli.create_runner(cmd)?;262 You can enable it with `--features runtime-benchmarks`.".into())262 You can enable it with `--features runtime-benchmarks`."263 .into())263 }264 }264 },265 }265 None => {266 None => {266 let runner = cli.create_runner(&cli.run.normalize())?;267 let runner = cli.create_runner(&cli.run.normalize())?;267268268 runner.run_node_until_exit(|config| async move {269 runner.run_node_until_exit(|config| async move {269 // TODO270 let key = sp_core::Pair::generate().0;271272 let para_id =270 let para_id =273 chain_spec::Extensions::try_get(&*config.chain_spec).map(|e| e.para_id);271 chain_spec::Extensions::try_get(&*config.chain_spec).map(|e| e.para_id);274272275 let polkadot_cli = RelayChainCli::new(273 let polkadot_cli = RelayChainCli::new(276 &config,274 &config,277 [RelayChainCli::executable_name().to_string()]275 [RelayChainCli::executable_name()]278 .iter()276 .iter()279 .chain(cli.relaychain_args.iter()),277 .chain(cli.relaychain_args.iter()),280 );278 );308 }303 }309 );304 );310305311 crate::service::start_node(config, key, polkadot_config, id)306 crate::service::start_node(config, polkadot_config, id)312 .await307 .await313 .map(|r| r.0)308 .map(|r| r.0)314 .map_err(Into::into)309 .map_err(Into::into)node/cli/src/service.rsdiffbeforeafterboth161617// Cumulus Imports17// Cumulus Imports18use cumulus_client_consensus_aura::{18use cumulus_client_consensus_aura::{build_aura_consensus, BuildAuraConsensusParams, SlotProportion};19 build_aura_consensus, BuildAuraConsensusParams, SlotProportion,20};21use cumulus_client_consensus_common::ParachainConsensus;19use cumulus_client_consensus_common::ParachainConsensus;22use cumulus_client_network::build_block_announce_validator;20use cumulus_client_network::build_block_announce_validator;25};23};26use cumulus_primitives_core::ParaId;24use cumulus_primitives_core::ParaId;2728// Polkadot Imports29use polkadot_primitives::v1::CollatorPair;302531// Substrate Imports26// Substrate Imports32use sc_client_api::ExecutorProvider;27use sc_client_api::ExecutorProvider;71 source: fc_db::DatabaseSettingsSrc::RocksDb {68 source: fc_db::DatabaseSettingsSrc::RocksDb {72 path: database_dir,69 path: database_dir,73 cache_size: 0,70 cache_size: 0,74 }71 },75 })?))72 },73 )?))76}74}777585///83///86/// Use this macro if you don't actually need the full service, but just the builder in order to84/// Use this macro if you don't actually need the full service, but just the builder in order to87/// be able to perform chain operations.85/// be able to perform chain operations.86#[allow(clippy::type_complexity)]88pub fn new_partial<BIQ>(87pub fn new_partial<BIQ>(89 config: &Configuration,88 config: &Configuration,90 build_import_queue: BIQ,89 build_import_queue: BIQ,99 PendingTransactions,100 Option<FilterPool>,101 Arc<fc_db::Backend<Block>>,102 Option<TelemetryWorkerHandle>,103 ),99 >,104 >,100 sc_service::Error,105 sc_service::Error,109 &TaskManager,114 &TaskManager,110 ) -> Result<115 ) -> Result<sp_consensus::DefaultImportQueue<Block, FullClient>, sc_service::Error>,111 sp_consensus::DefaultImportQueue<Block, FullClient>,112 sc_service::Error,113 >,114{116{115 let telemetry = config117 let _telemetry = config116 .telemetry_endpoints118 .telemetry_endpoints117 .clone()119 .clone()118 .filter(|x| !x.is_empty())120 .filter(|x| !x.is_empty())134138135 let (client, backend, keystore_container, task_manager) =139 let (client, backend, keystore_container, task_manager) =136 sc_service::new_full_parts::<Block, RuntimeApi, Executor>(140 sc_service::new_full_parts::<Block, RuntimeApi, Executor>(137 &config,141 config,138 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),142 telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),139 )?;143 )?;140 let client = Arc::new(client);144 let client = Arc::new(client);152 config.transaction_pool.clone(),156 config.transaction_pool.clone(),153 config.role.is_authority().into(),157 config.role.is_authority().into(),154 config.prometheus_registry(),158 config.prometheus_registry(),155 task_manager.spawn_handle(),159 task_manager.spawn_essential_handle(),156 client.clone(),160 client.clone(),157 );161 );158162186 pending_transactions,187 filter_pool,188 frontier_backend,189 telemetry_worker_handle,190 ),182 };191 };183192190#[sc_tracing::logging::prefix_logs_with("Parachain")]199#[sc_tracing::logging::prefix_logs_with("Parachain")]191async fn start_node_impl<BIQ, BIC>(200async fn start_node_impl<BIQ, BIC>(192 parachain_config: Configuration,201 parachain_config: Configuration,193 collator_key: CollatorPair,194 polkadot_config: Configuration,202 polkadot_config: Configuration,195 id: ParaId,203 id: ParaId,196 build_import_queue: BIQ,204 build_import_queue: BIQ,206 &TaskManager,214 &TaskManager,207 ) -> Result<215 ) -> Result<sp_consensus::DefaultImportQueue<Block, FullClient>, sc_service::Error>,208 sp_consensus::DefaultImportQueue<Block, FullClient>,209 sc_service::Error,210 >,211 BIC: FnOnce(216 BIC: FnOnce(212 Arc<FullClient>,217 Arc<FullClient>,237 pending_transactions,238 filter_pool,239 frontier_backend,240 telemetry_worker_handle,241 ) = params.other;231242232 let relay_chain_full_node = cumulus_client_service::build_polkadot_full_node(243 let relay_chain_full_node =233 polkadot_config,244 cumulus_client_service::build_polkadot_full_node(polkadot_config, telemetry_worker_handle)234 collator_key.clone(),235 telemetry_worker_handle,236 )237 .map_err(|e| match e {245 .map_err(|e| match e {238 polkadot_service::Error::Sub(x) => x,246 polkadot_service::Error::Sub(x) => x,254 let transaction_pool = params.transaction_pool.clone();262 let transaction_pool = params.transaction_pool.clone();255 let mut task_manager = params.task_manager;263 let mut task_manager = params.task_manager;256 let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);264 let import_queue = cumulus_client_service::SharedImportQueue::new(params.import_queue);257 let (network, network_status_sinks, system_rpc_tx, start_network) =265 let (network, system_rpc_tx, start_network) =258 sc_service::build_network(sc_service::BuildNetworkParams {266 sc_service::build_network(sc_service::BuildNetworkParams {259 config: ¶chain_config,267 config: ¶chain_config,260 client: client.clone(),268 client: client.clone(),283 network: rpc_network.clone(),291 network: rpc_network.clone(),284 pending_transactions: pending_transactions.clone(),292 pending_transactions: pending_transactions.clone(),285 select_chain: select_chain.clone(),293 select_chain: select_chain.clone(),286 is_authority: is_authority.clone(),294 is_authority,287 // TODO: Unhardcode295 // TODO: Unhardcode288 max_past_logs: 10000,296 max_past_logs: 10000,289 };297 };302 keystore: params.keystore_container.sync_keystore(),310 keystore: params.keystore_container.sync_keystore(),303 backend: backend.clone(),311 backend: backend.clone(),304 network: network.clone(),312 network: network.clone(),305 network_status_sinks,306 system_rpc_tx,313 system_rpc_tx,307 telemetry: telemetry.as_mut(),314 telemetry: telemetry.as_mut(),308 })?;315 })?;333 announce_block,340 announce_block,334 client: client.clone(),341 client: client.clone(),335 task_manager: &mut task_manager,342 task_manager: &mut task_manager,336 collator_key,337 relay_chain_full_node,343 relay_chain_full_node,338 spawner,344 spawner,339 parachain_consensus,345 parachain_consensus,367) -> Result<373) -> Result<sp_consensus::DefaultImportQueue<Block, FullClient>, sc_service::Error> {368 sp_consensus::DefaultImportQueue<369 Block,370 FullClient,371 >,372 sc_service::Error,373> {374 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;374 let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;375396395397 Ok((time, slot))396 Ok((time, slot))398 },397 },399 registry: config.prometheus_registry().clone(),398 registry: config.prometheus_registry(),400 can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),399 can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),401 spawner: &task_manager.spawn_essential_handle(),400 spawner: &task_manager.spawn_essential_handle(),402 telemetry,401 telemetry,407/// Start a normal parachain node.406/// Start a normal parachain node.408pub async fn start_node(407pub async fn start_node(409 parachain_config: Configuration,408 parachain_config: Configuration,410 collator_key: CollatorPair,411 polkadot_config: Configuration,409 polkadot_config: Configuration,412 id: ParaId,410 id: ParaId,413) -> sc_service::error::Result<(TaskManager, Arc<FullClient>)> {411) -> sc_service::error::Result<(TaskManager, Arc<FullClient>)> {414 start_node_impl::<_, _>(412 start_node_impl::<_, _>(415 parachain_config,413 parachain_config,416 collator_key,417 polkadot_config,414 polkadot_config,418 id,415 id,419 parachain_build_import_queue,416 parachain_build_import_queue,432 task_manager.spawn_handle(),429 task_manager.spawn_handle(),433 client.clone(),430 client.clone(),434 transaction_pool,431 transaction_pool,435 prometheus_registry.clone(),432 prometheus_registry,436 telemetry.clone(),433 telemetry.clone(),437 );434 );438435480 block_import: client.clone(),477 block_import: client.clone(),481 relay_chain_client: relay_chain_node.client.clone(),478 relay_chain_client: relay_chain_node.client.clone(),482 relay_chain_backend: relay_chain_node.backend.clone(),479 relay_chain_backend: relay_chain_node.backend.clone(),483 para_client: client.clone(),480 para_client: client,484 backoff_authoring_blocks: Option::<()>::None,481 backoff_authoring_blocks: Option::<()>::None,485 sync_oracle,482 sync_oracle,486 keystore,483 keystore,node/rpc/Cargo.tomldiffbeforeafterboth13futures = { version = "0.3.1", features = ["compat"] }13futures = { version = "0.3.1", features = ["compat"] }14jsonrpc-core = "15.0.0"14jsonrpc-core = "15.0.0"15jsonrpc-pubsub = "15.0.0"15jsonrpc-pubsub = "15.0.0"16pallet-contracts-rpc = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }16pallet-contracts-rpc = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }17pallet-transaction-payment-rpc = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }17pallet-transaction-payment-rpc = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }18pallet-transaction-payment-rpc-runtime-api = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }18pallet-transaction-payment-rpc-runtime-api = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }19sc-client-api = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }19sc-client-api = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }20sc-consensus-aura = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }20sc-consensus-aura = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }21sc-consensus-epochs = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }21sc-consensus-epochs = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }22sc-finality-grandpa = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }22sc-finality-grandpa = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }23sc-finality-grandpa-rpc = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }23sc-finality-grandpa-rpc = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }24sc-keystore = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }24sc-keystore = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }25sc-network = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }25sc-network = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }26sc-rpc-api = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }26sc-rpc-api = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }27sc-rpc = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }27sc-rpc = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }28sc-service = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }28sc-service = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }29sp-api = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }29sp-api = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }30sp-block-builder = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }30sp-block-builder = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }31sp-blockchain = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }31sp-blockchain = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }32sp-consensus = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }32sp-consensus = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }33sp-consensus-aura = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }33sp-consensus-aura = { version = "0.9", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }34sp-core = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }34sp-core = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }35sp-offchain = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }35sp-offchain = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }36sp-runtime = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }36sp-runtime = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }37sp-storage = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }37sp-storage = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }38sp-session = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }38sp-session = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }39sp-transaction-pool = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }39sp-transaction-pool = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }40sc-transaction-pool = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }40sc-transaction-pool = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }41sc-transaction-graph = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }41sc-transaction-graph = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }42substrate-frame-rpc-system = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }42substrate-frame-rpc-system = { version = "3.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }43tokio = { version = "0.2.13", features = ["macros", "sync"] }43tokio = { version = "0.2.13", features = ["macros", "sync"] }444445pallet-ethereum = { git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }45pallet-ethereum = { git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }node/rpc/src/lib.rsdiffbeforeafterboth189 pool.clone(),189 pool.clone(),190 nft_runtime::TransactionConverter,190 nft_runtime::TransactionConverter,191 network.clone(),191 network.clone(),192 pending_transactions.clone(),192 pending_transactions,193 signers,193 signers,194 overrides.clone(),194 overrides.clone(),195 backend,195 backend,200 if let Some(filter_pool) = filter_pool {200 if let Some(filter_pool) = filter_pool {201 io.extend_with(EthFilterApiServer::to_delegate(EthFilterApi::new(201 io.extend_with(EthFilterApiServer::to_delegate(EthFilterApi::new(202 client.clone(),202 client.clone(),203 filter_pool.clone(),203 filter_pool,204 500 as usize, // max stored filters204 500_usize, // max stored filters205 overrides.clone(),205 overrides.clone(),206 max_past_logs,206 max_past_logs,207 )));207 )));217 io.extend_with(Web3ApiServer::to_delegate(Web3Api::new(client.clone())));217 io.extend_with(Web3ApiServer::to_delegate(Web3Api::new(client.clone())));218218219 io.extend_with(EthPubSubApiServer::to_delegate(EthPubSubApi::new(219 io.extend_with(EthPubSubApiServer::to_delegate(EthPubSubApi::new(220 pool.clone(),220 pool,221 client.clone(),221 client,222 network.clone(),222 network,223 SubscriptionManager::<HexEncodedIdProvider>::with_id_provider(223 SubscriptionManager::<HexEncodedIdProvider>::with_id_provider(224 HexEncodedIdProvider::default(),224 HexEncodedIdProvider::default(),225 Arc::new(subscription_task_executor),225 Arc::new(subscription_task_executor),pallets/contract-helpers/Cargo.tomldiffbeforeafterboth15version = '0.1.0'15version = '0.1.0'161617[dependencies]17[dependencies]18frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }18frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }19frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }19frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }20pallet-contracts = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }20pallet-contracts = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }21sp-runtime = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }21sp-runtime = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }22sp-std = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }22sp-std = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }232324[features]24[features]25default = ["std"]25default = ["std"]pallets/contract-helpers/src/lib.rsdiffbeforeafterboth75 #[pallet::call]75 #[pallet::call]76 impl<T: Config> Pallet<T> {76 impl<T: Config> Pallet<T> {77 #[pallet::weight(0)]77 #[pallet::weight(0)]78 fn toggle_sponsoring(78 pub fn toggle_sponsoring(79 origin: OriginFor<T>,79 origin: OriginFor<T>,80 contract: T::AccountId,80 contract: T::AccountId,81 sponsoring: bool,81 sponsoring: bool,92 }95 }939694 #[pallet::weight(0)]97 #[pallet::weight(0)]95 fn toggle_allowlist(98 pub fn toggle_allowlist(96 origin: OriginFor<T>,99 origin: OriginFor<T>,97 contract: T::AccountId,100 contract: T::AccountId,98 enabled: bool,101 enabled: bool,109 }115 }110116111 #[pallet::weight(0)]117 #[pallet::weight(0)]112 fn toggle_allowed(118 pub fn toggle_allowed(113 origin: OriginFor<T>,119 origin: OriginFor<T>,114 contract: T::AccountId,120 contract: T::AccountId,115 user: T::AccountId,121 user: T::AccountId,127 }136 }128137129 #[pallet::weight(0)]138 #[pallet::weight(0)]130 fn set_sponsoring_rate_limit(139 pub fn set_sponsoring_rate_limit(131 origin: OriginFor<T>,140 origin: OriginFor<T>,132 contract: T::AccountId,141 contract: T::AccountId,133 rate_limit: T::BlockNumber,142 rate_limit: T::BlockNumber,174 _info: &DispatchInfoOf<Self::Call>,186 _info: &DispatchInfoOf<Self::Call>,175 _len: usize,187 _len: usize,176 ) -> transaction_validity::TransactionValidity {188 ) -> transaction_validity::TransactionValidity {177 match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {178 Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {189 if let Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) =190 IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call)191 {179 let called_contract: T::AccountId =192 let called_contract: T::AccountId =180 T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());193 T::Lookup::lookup((*dest).clone()).unwrap_or_default();181 if <AllowlistEnabled<T>>::get(&called_contract) {194 if <AllowlistEnabled<T>>::get(&called_contract)182 if !<Allowlist<T>>::get(&called_contract, who)195 && !<Allowlist<T>>::get(&called_contract, who)183 && &<Owner<T>>::get(&called_contract) != who196 && &<Owner<T>>::get(&called_contract) != who184 {197 {185 return Err(transaction_validity::InvalidTransaction::Call.into());198 return Err(transaction_validity::InvalidTransaction::Call.into());186 }199 }187 }188 }200 }189 _ => {}190 }191 Ok(transaction_validity::ValidTransaction::default())201 Ok(transaction_validity::ValidTransaction::default())192 }202 }193203200 ) -> Result<Self::Pre, TransactionValidityError> {210 ) -> Result<Self::Pre, TransactionValidityError> {201 match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {211 match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {202 Some(pallet_contracts::Call::instantiate(_, _, code_hash, _, salt)) => {212 Some(pallet_contracts::Call::instantiate(_, _, code_hash, _, salt)) => {203 Ok(Some((who.clone(), code_hash.clone(), salt.clone())))213 Ok(Some((who.clone(), *code_hash, salt.clone())))204 }214 }205 Some(pallet_contracts::Call::instantiate_with_code(_, _, code, _, salt)) => {215 Some(pallet_contracts::Call::instantiate_with_code(_, _, code, _, salt)) => {206 let code_hash = &T::Hashing::hash(&code);216 let code_hash = &T::Hashing::hash(code);207 Ok(Some((who.clone(), code_hash.clone(), salt.clone())))217 Ok(Some((who.clone(), *code_hash, salt.clone())))208 }218 }209 _ => Ok(None),219 _ => Ok(None),210 }220 }236 T::AccountId: AsRef<[u8]>,246 T::AccountId: AsRef<[u8]>,237 {247 {238 fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {248 fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {239 match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {240 Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {249 if let Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) =250 IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call)251 {241 let called_contract: T::AccountId =252 let called_contract: T::AccountId =253 }263 }254 }264 }255 }265 }256 _ => {}257 }258 None266 None259 }267 }260 }268 }pallets/inflation/Cargo.tomldiffbeforeafterboth43default-features = false43default-features = false44optional = true44optional = true45git = 'https://github.com/paritytech/substrate.git'45git = 'https://github.com/paritytech/substrate.git'46branch = 'polkadot-v0.9.3'46branch = 'polkadot-v0.9.7'47version = '3.0.0'47version = '3.0.0'484849[dependencies.frame-support]49[dependencies.frame-support]50default-features = false50default-features = false51git = 'https://github.com/paritytech/substrate.git'51git = 'https://github.com/paritytech/substrate.git'52branch = 'polkadot-v0.9.3'52branch = 'polkadot-v0.9.7'53version = '3.0.0'53version = '3.0.0'545455[dependencies.frame-system]55[dependencies.frame-system]56default-features = false56default-features = false57git = 'https://github.com/paritytech/substrate.git'57git = 'https://github.com/paritytech/substrate.git'58branch = 'polkadot-v0.9.3'58branch = 'polkadot-v0.9.7'59version = '3.0.0'59version = '3.0.0'606061[dependencies.pallet-balances]61[dependencies.pallet-balances]62default-features = false62default-features = false63git = 'https://github.com/paritytech/substrate.git'63git = 'https://github.com/paritytech/substrate.git'64branch = 'polkadot-v0.9.3'64branch = 'polkadot-v0.9.7'65version = '3.0.0'65version = '3.0.0'666667[dependencies.pallet-timestamp]67[dependencies.pallet-timestamp]68default-features = false68default-features = false69git = 'https://github.com/paritytech/substrate.git'69git = 'https://github.com/paritytech/substrate.git'70branch = 'polkadot-v0.9.3'70branch = 'polkadot-v0.9.7'71version = '3.0.0'71version = '3.0.0'727273[dependencies.pallet-randomness-collective-flip]73[dependencies.pallet-randomness-collective-flip]74default-features = false74default-features = false75git = 'https://github.com/paritytech/substrate.git'75git = 'https://github.com/paritytech/substrate.git'76branch = 'polkadot-v0.9.3'76branch = 'polkadot-v0.9.7'77version = '3.0.0'77version = '3.0.0'787879[dependencies.sp-std]79[dependencies.sp-std]80default-features = false80default-features = false81git = 'https://github.com/paritytech/substrate.git'81git = 'https://github.com/paritytech/substrate.git'82branch = 'polkadot-v0.9.3'82branch = 'polkadot-v0.9.7'83version = '3.0.0'83version = '3.0.0'848485[dependencies.serde]85[dependencies.serde]90[dependencies.sp-runtime]90[dependencies.sp-runtime]91default-features = false91default-features = false92git = 'https://github.com/paritytech/substrate.git'92git = 'https://github.com/paritytech/substrate.git'93branch = 'polkadot-v0.9.3'93branch = 'polkadot-v0.9.7'94version = '3.0.0'94version = '3.0.0'959596[dependencies.sp-core]96[dependencies.sp-core]97default-features = false97default-features = false98git = 'https://github.com/paritytech/substrate.git'98git = 'https://github.com/paritytech/substrate.git'99branch = 'polkadot-v0.9.3'99branch = 'polkadot-v0.9.7'100version = '3.0.0'100version = '3.0.0'101101102[dependencies.sp-io]102[dependencies.sp-io]103default-features = false103default-features = false104git = 'https://github.com/paritytech/substrate.git'104git = 'https://github.com/paritytech/substrate.git'105branch = 'polkadot-v0.9.3'105branch = 'polkadot-v0.9.7'106version = '3.0.0'106version = '3.0.0'107107108108pallets/inflation/src/benchmarking.rsdiffbeforeafterbothno syntactic changes
pallets/inflation/src/lib.rsdiffbeforeafterboth393640use sp_runtime::{37use sp_runtime::{41 Perbill,38 Perbill,42 traits::{Zero}39 traits::{Zero},43};40};44use sp_std::convert::TryInto;41use sp_std::convert::TryInto;4542pallets/inflation/src/tests.rsdiffbeforeafterboth1#[cfg(test)]1#![cfg(test)]2mod tests {2#![allow(clippy::from_over_into)]3 use crate as pallet_inflation;3use crate as pallet_inflation;445 use frame_system;5use frame_support::{6 use frame_support::{traits::{Currency}, parameter_types};6 traits::{Currency},7 use frame_support::{traits::OnInitialize};7 parameter_types,8 use sp_core::H256;8};9 use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::Header};9use frame_support::{traits::OnInitialize};1010use sp_core::H256;11 type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;11use sp_runtime::{12 type Block = frame_system::mocking::MockBlock<Test>;12 traits::{BlakeTwo256, IdentityLookup},1313 testing::Header,14 const YEAR: u64 = 5_259_600;14};151516 parameter_types! {16type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;17 pub const ExistentialDeposit: u64 = 1;17type Block = frame_system::mocking::MockBlock<Test>;18 pub const MaxLocks: u32 = 50;1819 }19const YEAR: u64 = 5_259_600;20 2021 impl pallet_balances::Config for Test {21parameter_types! {22 type AccountStore = System;22 pub const ExistentialDeposit: u64 = 1;23 type Balance = u64;23 pub const MaxLocks: u32 = 50;24 type DustRemoval = ();24}25 type Event = ();2526 type ExistentialDeposit = ExistentialDeposit;26impl pallet_balances::Config for Test {27 type WeightInfo = ();27 type AccountStore = System;28 type MaxLocks = MaxLocks;28 type Balance = u64;29 }29 type DustRemoval = ();30 30 type Event = ();31 frame_support::construct_runtime!(31 type ExistentialDeposit = ExistentialDeposit;32 pub enum Test where32 type WeightInfo = ();33 Block = Block,33 type MaxLocks = MaxLocks;34 NodeBlock = Block,34}35 UncheckedExtrinsic = UncheckedExtrinsic,3536 {36frame_support::construct_runtime!(37 Balances: pallet_balances::{Module, Call, Storage},37 pub enum Test where38 System: frame_system::{Module, Call, Config, Storage, Event<T>},38 Block = Block,39 Inflation: pallet_inflation::{Module, Call, Storage},39 NodeBlock = Block,40 }40 UncheckedExtrinsic = UncheckedExtrinsic,41 );41 {4242 Balances: pallet_balances::{Pallet, Call, Storage},43 parameter_types! {43 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},44 pub const BlockHashCount: u64 = 250;44 Inflation: pallet_inflation::{Pallet, Call, Storage},45 pub BlockWeights: frame_system::limits::BlockWeights =45 }46 frame_system::limits::BlockWeights::simple_max(1024);46);47 pub const SS58Prefix: u8 = 42;4748 }48parameter_types! {4949 pub const BlockHashCount: u64 = 250;50 impl frame_system::Config for Test {50 pub BlockWeights: frame_system::limits::BlockWeights =51 type BaseCallFilter = ();51 frame_system::limits::BlockWeights::simple_max(1024);52 type BlockWeights = ();52 pub const SS58Prefix: u8 = 42;53 type BlockLength = ();53}54 type DbWeight = ();5455 type Origin = Origin;55impl frame_system::Config for Test {56 type Call = Call;56 type BaseCallFilter = ();57 type Index = u64;57 type BlockWeights = ();58 type BlockNumber = u64;58 type BlockLength = ();59 type Hash = H256;59 type DbWeight = ();60 type Hashing = BlakeTwo256;60 type Origin = Origin;61 type AccountId = u64;61 type Call = Call;62 type Lookup = IdentityLookup<Self::AccountId>;62 type Index = u64;63 type Header = Header;63 type BlockNumber = u64;64 type Event = ();64 type Hash = H256;65 type BlockHashCount = BlockHashCount;65 type Hashing = BlakeTwo256;66 type Version = ();66 type AccountId = u64;67 type PalletInfo = PalletInfo;67 type Lookup = IdentityLookup<Self::AccountId>;68 type AccountData = pallet_balances::AccountData<u64>;68 type Header = Header;69 type OnNewAccount = ();69 type Event = ();70 type OnKilledAccount = ();70 type BlockHashCount = BlockHashCount;71 type SystemWeightInfo = ();71 type Version = ();72 type SS58Prefix = SS58Prefix;72 type PalletInfo = PalletInfo;73 }73 type AccountData = pallet_balances::AccountData<u64>;7474 type OnNewAccount = ();75 parameter_types! {75 type OnKilledAccount = ();76 pub TreasuryAccountId: u64 = 1234;76 type SystemWeightInfo = ();77 pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied77 type SS58Prefix = SS58Prefix;78 }78 type OnSetCode = ();79 79}80 impl pallet_inflation::Config for Test {8081 type Currency = Balances;81parameter_types! {82 type TreasuryAccountId = TreasuryAccountId;82 pub TreasuryAccountId: u64 = 1234;83 type InflationBlockInterval = InflationBlockInterval;83 pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied84 }84}858586 // Build genesis storage according to the mock runtime.86impl pallet_inflation::Config for Test {87 pub fn new_test_ext() -> sp_io::TestExternalities {87 type Currency = Balances;88 frame_system::GenesisConfig::default().build_storage::<Test>().unwrap().into()88 type TreasuryAccountId = TreasuryAccountId;89 }89 type InflationBlockInterval = InflationBlockInterval;90}9192// Build genesis storage according to the mock runtime.93pub fn new_test_ext() -> sp_io::TestExternalities {94 frame_system::GenesisConfig::default()95 .build_storage::<Test>()96 .unwrap()97 .into()98}99100#[test]101fn inflation_works() {102 new_test_ext().execute_with(|| {103 // Total issuance = 1_000_000_000104 let initial_issuance: u64 = 1_000_000_000;105 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);106 assert_eq!(Balances::free_balance(1234), initial_issuance);107108 // BlockInflation should be set after 1st block and109 // first inflation deposit should be equal to BlockInflation110 Inflation::on_initialize(1);111 assert!(Inflation::block_inflation() > 0);112 assert_eq!(113 Balances::free_balance(1234) - initial_issuance,114 Inflation::block_inflation()115 );116 });117}118119#[test]120fn inflation_second_deposit() {121 new_test_ext().execute_with(|| {122 // Total issuance = 1_000_000_000123 let initial_issuance: u64 = 1_000_000_000;124 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);125 assert_eq!(Balances::free_balance(1234), initial_issuance);126 Inflation::on_initialize(1);127128 // Next inflation deposit happens when block is multiple of InflationBlockInterval129 let mut block: u32 = 2;130 let balance_before: u64 = Balances::free_balance(1234);131 while block % InflationBlockInterval::get() != 0 {132 Inflation::on_initialize(block as u64);133 block += 1;134 }135 let balance_just_before: u64 = Balances::free_balance(1234);136 assert_eq!(balance_before, balance_just_before);137138 // The block with inflation139 Inflation::on_initialize(block as u64);140 let balance_after: u64 = Balances::free_balance(1234);141 assert_eq!(142 balance_after - balance_just_before,143 Inflation::block_inflation()144 );145 });146}147148#[test]149fn inflation_in_1_year() {150 new_test_ext().execute_with(|| {151 // Total issuance = 1_000_000_000152 let initial_issuance: u64 = 1_000_000_000;153 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);154 assert_eq!(Balances::free_balance(1234), initial_issuance);155 Inflation::on_initialize(1);156 let block_inflation_year_0 = Inflation::block_inflation();157158 Inflation::on_initialize(YEAR);159 let block_inflation_year_1 = Inflation::block_inflation();160161 // Assert that year 1 inflation is less than year 0162 assert!(block_inflation_year_0 > block_inflation_year_1);163 });164}165166#[test]167fn inflation_in_1_to_9_years() {168 new_test_ext().execute_with(|| {169 // Total issuance = 1_000_000_000170 let initial_issuance: u64 = 1_000_000_000;171 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);172 assert_eq!(Balances::free_balance(1234), initial_issuance);173 Inflation::on_initialize(1);174175 for year in 1..=9 {176 let block_inflation_year_before = Inflation::block_inflation();177 Inflation::on_initialize(YEAR * year);178 let block_inflation_year_after = Inflation::block_inflation();179180 // Assert that next year inflation is less than previous year inflation181 assert!(block_inflation_year_before > block_inflation_year_after);182 }183 });184}185186#[test]187fn inflation_after_year_10_is_flat() {188 new_test_ext().execute_with(|| {189 // Total issuance = 1_000_000_000190 let initial_issuance: u64 = 1_000_000_000;191 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);192 assert_eq!(Balances::free_balance(1234), initial_issuance);193 Inflation::on_initialize(YEAR * 9);194195 for year in 10..=20 {196 let block_inflation_year_before = Inflation::block_inflation();197 Inflation::on_initialize(YEAR * year);198 let block_inflation_year_after = Inflation::block_inflation();199200 // Assert that next year inflation is equal to previous year inflation201 assert_eq!(block_inflation_year_before, block_inflation_year_after);202 }203 });204}9020591 #[test]206#[test]92 fn inflation_works() {207fn inflation_rate_by_year() {93 new_test_ext().execute_with(|| {94 // Total issuance = 1_000_000_00095 let initial_issuance: u64 = 1_000_000_000;96 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);97 assert_eq!(Balances::free_balance(1234), initial_issuance);9899 // BlockInflation should be set after 1st block and 100 // first inflation deposit should be equal to BlockInflation101 Inflation::on_initialize(1);102 assert!(Inflation::block_inflation() > 0);103 assert_eq!(Balances::free_balance(1234) - initial_issuance, Inflation::block_inflation());104 });105 }106107 #[test]108 fn inflation_second_deposit() {109 new_test_ext().execute_with(|| {110 // Total issuance = 1_000_000_000111 let initial_issuance: u64 = 1_000_000_000;112 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);113 assert_eq!(Balances::free_balance(1234), initial_issuance);114 Inflation::on_initialize(1);115116 // Next inflation deposit happens when block is multiple of InflationBlockInterval117 let mut block: u32 = 2;118 let balance_before: u64 = Balances::free_balance(1234);119 while block % InflationBlockInterval::get() != 0 {120 Inflation::on_initialize(block as u64);121 block += 1;122 }123 let balance_just_before: u64 = Balances::free_balance(1234);124 assert_eq!(balance_before, balance_just_before);125126 // The block with inflation127 Inflation::on_initialize(block as u64);128 let balance_after: u64 = Balances::free_balance(1234);129 assert_eq!(balance_after - balance_just_before, Inflation::block_inflation());130 });131 }132133 #[test]134 fn inflation_in_1_year() {135 new_test_ext().execute_with(|| {136 // Total issuance = 1_000_000_000137 let initial_issuance: u64 = 1_000_000_000;138 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);139 assert_eq!(Balances::free_balance(1234), initial_issuance);140 Inflation::on_initialize(1);141 let block_inflation_year_0 = Inflation::block_inflation();142143 Inflation::on_initialize(YEAR);144 let block_inflation_year_1 = Inflation::block_inflation();145146 // Assert that year 1 inflation is less than year 0147 assert!(block_inflation_year_0 > block_inflation_year_1);148 });149 }150151 #[test]152 fn inflation_in_1_to_9_years() {153 new_test_ext().execute_with(|| {154 // Total issuance = 1_000_000_000155 let initial_issuance: u64 = 1_000_000_000;156 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);157 assert_eq!(Balances::free_balance(1234), initial_issuance);158 Inflation::on_initialize(1);159160 for year in 1..=9 {161 let block_inflation_year_before = Inflation::block_inflation();162 Inflation::on_initialize(YEAR * year);163 let block_inflation_year_after = Inflation::block_inflation();164165 // Assert that next year inflation is less than previous year inflation166 assert!(block_inflation_year_before > block_inflation_year_after);167 }168169 });170 }171172 #[test]173 fn inflation_after_year_10_is_flat() {174 new_test_ext().execute_with(|| {175 // Total issuance = 1_000_000_000176 let initial_issuance: u64 = 1_000_000_000;177 let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);178 assert_eq!(Balances::free_balance(1234), initial_issuance);179 Inflation::on_initialize(YEAR * 9);180181 for year in 10..=20 {182 let block_inflation_year_before = Inflation::block_inflation();183 Inflation::on_initialize(YEAR * year);184 let block_inflation_year_after = Inflation::block_inflation();185186 // Assert that next year inflation is equal to previous year inflation187 assert_eq!(block_inflation_year_before, block_inflation_year_after);188 }189 });190 }191192 #[test]193 fn inflation_rate_by_year() {194 new_test_ext().execute_with(|| {208 new_test_ext().execute_with(|| {195 let payouts: u64 = YEAR / InflationBlockInterval::get() as u64;209 let payouts: u64 = YEAR / InflationBlockInterval::get() as u64;196210197 // Inflation starts at 10% and does down by 2/3% every year until year 9 (included), 211 // Inflation starts at 10% and does down by 2/3% every year until year 9 (included),198 // then it is flat.212 // then it is flat.199 let payout_by_year: [u64; 11] = [213 let payout_by_year: [u64; 11] = [1000, 933, 867, 800, 733, 667, 600, 533, 467, 400, 400];200 1000,238 }240 }239 });241 });240 }242}241}242243pallets/nft-charge-transaction/Cargo.tomldiffbeforeafterboth202021[dependencies]21[dependencies]22serde = { version = "1.0.119", default-features = false }22serde = { version = "1.0.119", default-features = false }23frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }23frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }24frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }24frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }25pallet-balances = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }25pallet-balances = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }26pallet-transaction-payment = { default-features = false, version = "3.0.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }26pallet-transaction-payment = { default-features = false, version = "3.0.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }27sp-std = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }27sp-std = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }28frame-benchmarking = { default-features = false, version = "3.0.0", optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }28frame-benchmarking = { default-features = false, version = "3.0.0", optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }29sp-core = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }29sp-core = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }30sp-io = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }30sp-io = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }31sp-runtime = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }31sp-runtime = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }323233pallet-nft-transaction-payment = { default-features = false, path="../nft-transaction-payment" }33pallet-nft-transaction-payment = { default-features = false, path="../nft-transaction-payment" }3434pallets/nft-charge-transaction/src/lib.rsdiffbeforeafterboth11#[cfg(feature = "std")]11#[cfg(feature = "std")]12pub use serde::*;12pub use serde::*;1314#[cfg(feature = "runtime-benchmarks")]15mod benchmarking;161317use codec::{Decode, Encode};14use codec::{Decode, Encode};18use frame_support::traits::Get;15use frame_support::traits::Get;19use frame_support::{16use frame_support::{20 decl_module, decl_storage,17 decl_module, decl_storage,21 weights::{18 weights::{DispatchInfo, PostDispatchInfo, DispatchClass},22 DispatchInfo, PostDispatchInfo, DispatchClass23 }24};19};29 transaction_validity::{ 25 transaction_validity::{30 TransactionPriority, TransactionValidity, TransactionValidityError, ValidTransaction,26 TransactionPriority, TransactionValidity, TransactionValidityError, ValidTransaction,31 },27 },32 FixedPointOperand, DispatchResult28 FixedPointOperand, DispatchResult,33};29};34use pallet_transaction_payment::OnChargeTransaction;30use pallet_transaction_payment::OnChargeTransaction;35use sp_std::prelude::*;31use sp_std::prelude::*;102 .saturated_into::<TransactionPriority>()95 .saturated_into::<TransactionPriority>()103 }96 }1049798 #[allow(clippy::type_complexity)]105 fn withdraw_fee(99 fn withdraw_fee(106 &self,100 &self,107 who: &T::AccountId,101 who: &T::AccountId,126 }120 }127121128 // Determine who is paying transaction fee based on ecnomic model122 // Determine who is paying transaction fee based on ecnomic model129 // Parse call to extract collection ID and access collection sponsor 123 // Parse call to extract collection ID and access collection sponsor130 let sponsor = <pallet_nft_transaction_payment::Module<T>>::withdraw_type(who, call);124 let sponsor = <pallet_nft_transaction_payment::Module<T>>::withdraw_type(who, call);131125132 let who_pays_fee = sponsor.unwrap_or_else(|| who.clone());126 let who_pays_fee = sponsor.unwrap_or_else(|| who.clone());pallets/nft-transaction-payment/Cargo.tomldiffbeforeafterboth202021[dependencies]21[dependencies]22serde = { version = "1.0.119", default-features = false }22serde = { version = "1.0.119", default-features = false }23frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }23frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }24frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }24frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }25pallet-transaction-payment = { default-features = false, version = "3.0.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }25pallet-transaction-payment = { default-features = false, version = "3.0.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }26sp-std = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }26sp-std = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }27frame-benchmarking = { default-features = false, version = "3.0.0", optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }27frame-benchmarking = { default-features = false, version = "3.0.0", optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }28sp-core = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }28sp-core = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }29sp-io = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }29sp-io = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }30sp-runtime = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }30sp-runtime = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }313132up-sponsorship = { default-features = false, path = "../../primitives/sponsorship", version = "0.1.0" }32up-sponsorship = { default-features = false, path = "../../primitives/sponsorship", version = "0.1.0" }3333pallets/nft-transaction-payment/src/benchmarking.rsdiffbeforeafterbothno syntactic changes
pallets/nft-transaction-payment/src/lib.rsdiffbeforeafterbothno syntactic changes
pallets/nft/Cargo.tomldiffbeforeafterboth56default-features = false56default-features = false57optional = true57optional = true58git = 'https://github.com/paritytech/substrate.git'58git = 'https://github.com/paritytech/substrate.git'59branch = 'polkadot-v0.9.3'59branch = 'polkadot-v0.9.7'60version = '3.0.0'60version = '3.0.0'616162[dependencies.frame-support]62[dependencies.frame-support]63default-features = false63default-features = false64git = 'https://github.com/paritytech/substrate.git'64git = 'https://github.com/paritytech/substrate.git'65branch = 'polkadot-v0.9.3'65branch = 'polkadot-v0.9.7'66version = '3.0.0'66version = '3.0.0'676768[dependencies.frame-system]68[dependencies.frame-system]69default-features = false69default-features = false70git = 'https://github.com/paritytech/substrate.git'70git = 'https://github.com/paritytech/substrate.git'71branch = 'polkadot-v0.9.3'71branch = 'polkadot-v0.9.7'72version = '3.0.0'72version = '3.0.0'737374[dependencies.pallet-balances]74[dependencies.pallet-balances]75default-features = false75default-features = false76git = 'https://github.com/paritytech/substrate.git'76git = 'https://github.com/paritytech/substrate.git'77branch = 'polkadot-v0.9.3'77branch = 'polkadot-v0.9.7'78version = '3.0.0'78version = '3.0.0'797980[dependencies.pallet-timestamp]80[dependencies.pallet-timestamp]81default-features = false81default-features = false82git = 'https://github.com/paritytech/substrate.git'82git = 'https://github.com/paritytech/substrate.git'83branch = 'polkadot-v0.9.3'83branch = 'polkadot-v0.9.7'84version = '3.0.0'84version = '3.0.0'858586[dependencies.pallet-randomness-collective-flip]86[dependencies.pallet-randomness-collective-flip]87default-features = false87default-features = false88git = 'https://github.com/paritytech/substrate.git'88git = 'https://github.com/paritytech/substrate.git'89branch = 'polkadot-v0.9.3'89branch = 'polkadot-v0.9.7'90version = '3.0.0'90version = '3.0.0'919192[dependencies.sp-std]92[dependencies.sp-std]93default-features = false93default-features = false94git = 'https://github.com/paritytech/substrate.git'94git = 'https://github.com/paritytech/substrate.git'95branch = 'polkadot-v0.9.3'95branch = 'polkadot-v0.9.7'96version = '3.0.0'96version = '3.0.0'979798[dependencies.pallet-contracts]98[dependencies.pallet-contracts]99default-features = false99default-features = false100git = 'https://github.com/paritytech/substrate.git'100git = 'https://github.com/paritytech/substrate.git'101branch = 'polkadot-v0.9.3'101branch = 'polkadot-v0.9.7'102version = '3.0.0'102version = '3.0.0'103103104[dependencies.pallet-transaction-payment]104[dependencies.pallet-transaction-payment]105default-features = false105default-features = false106git = 'https://github.com/paritytech/substrate.git'106git = 'https://github.com/paritytech/substrate.git'107branch = 'polkadot-v0.9.3'107branch = 'polkadot-v0.9.7'108version = '3.0.0'108version = '3.0.0'109109110[dependencies.serde]110[dependencies.serde]115[dependencies.sp-runtime]115[dependencies.sp-runtime]116default-features = false116default-features = false117git = 'https://github.com/paritytech/substrate.git'117git = 'https://github.com/paritytech/substrate.git'118branch = 'polkadot-v0.9.3'118branch = 'polkadot-v0.9.7'119version = '3.0.0'119version = '3.0.0'120120121[dependencies.sp-core]121[dependencies.sp-core]122default-features = false122default-features = false123git = 'https://github.com/paritytech/substrate.git'123git = 'https://github.com/paritytech/substrate.git'124branch = 'polkadot-v0.9.3'124branch = 'polkadot-v0.9.7'125version = '3.0.0'125version = '3.0.0'126126127[dependencies.sp-io]127[dependencies.sp-io]128default-features = false128default-features = false129git = 'https://github.com/paritytech/substrate.git'129git = 'https://github.com/paritytech/substrate.git'130branch = 'polkadot-v0.9.3'130branch = 'polkadot-v0.9.7'131version = '3.0.0'131version = '3.0.0'132132133133149ethereum-tx-sign = { version = "3.0.4", optional = true }149ethereum-tx-sign = { version = "3.0.4", optional = true }150ethereum = { default-features = false, version = "0.7.1" }150ethereum = { default-features = false, version = "0.7.1" }151rlp = { default-features = false, version = "0.5.0" }151rlp = { default-features = false, version = "0.5.0" }152sp-api = { default-features = false, version = '3.0.0', git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.3" }152sp-api = { default-features = false, version = '3.0.0', git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.7" }153153154evm-coder = { default-features = false, path = "../../crates/evm-coder" }154evm-coder = { default-features = false, path = "../../crates/evm-coder" }155primitive-types = { version = "0.9.0", default-features = false, features = ["serde_no_std"] }155primitive-types = { version = "0.9.0", default-features = false, features = ["serde_no_std"] }156156157pallet-evm = { default-features = false, version = "4.0.0-dev", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }157pallet-evm = { default-features = false, version = "5.0.0-dev", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }158pallet-ethereum = { default-features = false, version = "2.0.0-dev", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }158pallet-ethereum = { default-features = false, version = "3.0.0-dev", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }159fp-evm = { default-features = false, version = '2.0.0', git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }159fp-evm = { default-features = false, version = '2.0.0', git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }160hex-literal = "0.3.1"160hex-literal = "0.3.1"pallets/nft/src/benchmarking.rsdiffbeforeafterboth556use sp_std::prelude::*;6use sp_std::prelude::*;7use frame_system::RawOrigin;7use frame_system::RawOrigin;8use frame_benchmarking::{benchmarks, account, whitelisted_caller}; // , TrackedStorageKey, 8use frame_benchmarking::{benchmarks, account, whitelisted_caller}; // , TrackedStorageKey,9910const SEED: u32 = 1;10const SEED: u32 = 1;11/*11/*31 let mode: CollectionMode = CollectionMode::NFT;31 let mode: CollectionMode = CollectionMode::NFT;32 let caller: T::AccountId = account("caller", 0, SEED);32 let caller: T::AccountId = account("caller", 0, SEED);33 }: _(RawOrigin::Signed(caller.clone()), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode)33 }: _(RawOrigin::Signed(caller.clone()), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode)34/*34/*35 verify {35 verify {36 assert_eq!(Nft::<T>::collection_id(2).owner, caller);36 assert_eq!(Nft::<T>::collection_id(2).owner, caller);37 }37 }38 destroy_collection {38 destroy_collection {39 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();39 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();40 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();40 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();41 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();41 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();42 let mode: CollectionMode = CollectionMode::NFT;42 let mode: CollectionMode = CollectionMode::NFT;43 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());43 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());44 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;44 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;45 }: _(RawOrigin::Signed(caller.clone()), 2)45 }: _(RawOrigin::Signed(caller.clone()), 2)464647 add_to_white_list {47 add_to_white_list {48 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();48 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();49 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();49 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();50 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();50 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();51 let mode: CollectionMode = CollectionMode::NFT;51 let mode: CollectionMode = CollectionMode::NFT;52 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());52 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());53 let whitelist_account: T::AccountId = account("admin", 0, SEED);53 let whitelist_account: T::AccountId = account("admin", 0, SEED);54 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;54 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;55 }: add_to_white_list(RawOrigin::Signed(caller.clone()), 2, whitelist_account)55 }: add_to_white_list(RawOrigin::Signed(caller.clone()), 2, whitelist_account)565657 remove_from_white_list {57 remove_from_white_list {58 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();58 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();59 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();59 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();60 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();60 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();61 let mode: CollectionMode = CollectionMode::NFT;61 let mode: CollectionMode = CollectionMode::NFT;62 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());62 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());63 let whitelist_account: T::AccountId = account("admin", 0, SEED);63 let whitelist_account: T::AccountId = account("admin", 0, SEED);64 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;64 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;65 Nft::<T>::add_to_white_list(RawOrigin::Signed(caller.clone()).into(), 2, whitelist_account.clone())?;65 Nft::<T>::add_to_white_list(RawOrigin::Signed(caller.clone()).into(), 2, whitelist_account.clone())?;66 }: remove_from_white_list(RawOrigin::Signed(caller.clone()), 2, whitelist_account)66 }: remove_from_white_list(RawOrigin::Signed(caller.clone()), 2, whitelist_account)676768 set_public_access_mode {68 set_public_access_mode {69 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();69 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();70 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();70 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();71 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();71 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();72 let mode: CollectionMode = CollectionMode::NFT;72 let mode: CollectionMode = CollectionMode::NFT;73 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());73 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());74 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;74 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;75 }: set_public_access_mode(RawOrigin::Signed(caller.clone()), 2, AccessMode::WhiteList)75 }: set_public_access_mode(RawOrigin::Signed(caller.clone()), 2, AccessMode::WhiteList)767677 set_mint_permission {77 set_mint_permission {78 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();78 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();79 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();79 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();80 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();80 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();81 let mode: CollectionMode = CollectionMode::NFT;81 let mode: CollectionMode = CollectionMode::NFT;82 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());82 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());83 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;83 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;84 }: set_mint_permission(RawOrigin::Signed(caller.clone()), 2, true)84 }: set_mint_permission(RawOrigin::Signed(caller.clone()), 2, true)858586 change_collection_owner {86 change_collection_owner {87 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();87 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();88 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();88 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();89 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();89 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();90 let mode: CollectionMode = CollectionMode::NFT;90 let mode: CollectionMode = CollectionMode::NFT;91 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());91 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());92 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;92 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;93 let new_owner: T::AccountId = account("admin", 0, SEED);93 let new_owner: T::AccountId = account("admin", 0, SEED);94 }: change_collection_owner(RawOrigin::Signed(caller.clone()), 2, new_owner)94 }: change_collection_owner(RawOrigin::Signed(caller.clone()), 2, new_owner)959596 add_collection_admin {96 add_collection_admin {97 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();97 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();98 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();98 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();99 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();99 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();100 let mode: CollectionMode = CollectionMode::NFT;100 let mode: CollectionMode = CollectionMode::NFT;101 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());101 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());102 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;102 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;103 let new_admin: T::AccountId = account("admin", 0, SEED);103 let new_admin: T::AccountId = account("admin", 0, SEED);104 }: add_collection_admin(RawOrigin::Signed(caller.clone()), 2, new_admin)104 }: add_collection_admin(RawOrigin::Signed(caller.clone()), 2, new_admin)105105106 remove_collection_admin {106 remove_collection_admin {107 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();107 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();108 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();108 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();109 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();109 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();110 let mode: CollectionMode = CollectionMode::NFT;110 let mode: CollectionMode = CollectionMode::NFT;111 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());111 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());112 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;112 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;113 let new_admin: T::AccountId = account("admin", 0, SEED);113 let new_admin: T::AccountId = account("admin", 0, SEED);114 Nft::<T>::add_collection_admin(RawOrigin::Signed(caller.clone()).into(), 2, new_admin.clone())?;114 Nft::<T>::add_collection_admin(RawOrigin::Signed(caller.clone()).into(), 2, new_admin.clone())?;115 }: remove_collection_admin(RawOrigin::Signed(caller.clone()), 2, new_admin)115 }: remove_collection_admin(RawOrigin::Signed(caller.clone()), 2, new_admin)116116117 set_collection_sponsor {117 set_collection_sponsor {118 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();118 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();119 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();119 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();120 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();120 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();121 let mode: CollectionMode = CollectionMode::NFT;121 let mode: CollectionMode = CollectionMode::NFT;122 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());122 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());123 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;123 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;124 }: set_collection_sponsor(RawOrigin::Signed(caller.clone()), 2, caller.clone())124 }: set_collection_sponsor(RawOrigin::Signed(caller.clone()), 2, caller.clone())125125126 confirm_sponsorship {126 confirm_sponsorship {127 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();127 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();128 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();128 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();129 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();129 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();130 let mode: CollectionMode = CollectionMode::NFT;130 let mode: CollectionMode = CollectionMode::NFT;131 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());131 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());132 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;132 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;133 Nft::<T>::set_collection_sponsor(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone())?;133 Nft::<T>::set_collection_sponsor(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone())?;134 }: confirm_sponsorship(RawOrigin::Signed(caller.clone()), 2)134 }: confirm_sponsorship(RawOrigin::Signed(caller.clone()), 2)135135136 remove_collection_sponsor {136 remove_collection_sponsor {137 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();137 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();138 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();138 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();139 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();139 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();140 let mode: CollectionMode = CollectionMode::NFT;140 let mode: CollectionMode = CollectionMode::NFT;141 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());141 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());142 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;142 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;143 Nft::<T>::set_collection_sponsor(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone())?;143 Nft::<T>::set_collection_sponsor(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone())?;144 Nft::<T>::confirm_sponsorship(RawOrigin::Signed(caller.clone()).into(), 2)?;144 Nft::<T>::confirm_sponsorship(RawOrigin::Signed(caller.clone()).into(), 2)?;145 }: remove_collection_sponsor(RawOrigin::Signed(caller.clone()), 2)145 }: remove_collection_sponsor(RawOrigin::Signed(caller.clone()), 2)146146147 // nft item147 // nft item148 create_item_nft {148 create_item_nft {149 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();149 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();150 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();150 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();151 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();151 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();152 let mode: CollectionMode = CollectionMode::NFT;152 let mode: CollectionMode = CollectionMode::NFT;153 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());153 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());154 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;154 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;155 let data = default_nft_data();155 let data = default_nft_data();156 156157 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)157 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)158158159 #[extra]159 #[extra]160 create_item_nft_large {160 create_item_nft_large {161 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();161 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();162 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();162 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();163 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();163 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();164 let mode: CollectionMode = CollectionMode::NFT;164 let mode: CollectionMode = CollectionMode::NFT;165 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());165 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());166 let mut nft_data = CreateNftData {166 let mut nft_data = CreateNftData {167 const_data: vec![],167 const_data: vec![],168 variable_data: vec![]168 variable_data: vec![]169 };169 };170 for i in 0..1998 {170 for i in 0..1998 {171 nft_data.const_data.push(10);171 nft_data.const_data.push(10);172 nft_data.variable_data.push(10);172 nft_data.variable_data.push(10);173 }173 }174 let data = CreateItemData::NFT(nft_data);174 let data = CreateItemData::NFT(nft_data);175 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;175 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;176176177 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)177 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)178178179 // fungible item179 // fungible item180 create_item_fungible {180 create_item_fungible {181 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();181 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();182 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();182 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();183 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();183 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();184 let mode: CollectionMode = CollectionMode::Fungible(3);184 let mode: CollectionMode = CollectionMode::Fungible(3);185 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());185 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());186 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;186 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;187 let data = default_fungible_data();187 let data = default_fungible_data();188188189 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)189 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)190190191 // refungible item191 // refungible item192 create_item_refungible {192 create_item_refungible {193 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();193 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();194 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();194 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();195 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();195 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();196 let mode: CollectionMode = CollectionMode::ReFungible(3);196 let mode: CollectionMode = CollectionMode::ReFungible(3);197 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());197 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());198 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;198 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;199 let data = default_re_fungible_data();199 let data = default_re_fungible_data();200200201 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)201 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)202202203 burn_item {203 burn_item {204 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();204 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();205 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();205 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();206 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();206 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();207 let mode: CollectionMode = CollectionMode::NFT;207 let mode: CollectionMode = CollectionMode::NFT;208 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());208 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());209 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;209 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;210 let data = default_nft_data();210 let data = default_nft_data();211 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;211 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;212212213 }: burn_item(RawOrigin::Signed(caller.clone()), 2, 1)213 }: burn_item(RawOrigin::Signed(caller.clone()), 2, 1)214214215 transfer_nft {215 transfer_nft {216 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();216 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();217 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();217 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();218 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();218 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();219 let mode: CollectionMode = CollectionMode::NFT;219 let mode: CollectionMode = CollectionMode::NFT;220 let recipient: T::AccountId = account("recipient", 0, SEED);220 let recipient: T::AccountId = account("recipient", 0, SEED);221 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());221 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());222 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;222 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;223 let data = default_nft_data();223 let data = default_nft_data();224 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;224 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;225225226 }: transfer(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1, 1)226 }: transfer(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1, 1)227 227228 transfer_fungible {228 transfer_fungible {229 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();229 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();230 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();230 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();231 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();231 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();232 let mode: CollectionMode = CollectionMode::Fungible(3);232 let mode: CollectionMode = CollectionMode::Fungible(3);233 let recipient: T::AccountId = account("recipient", 0, SEED);233 let recipient: T::AccountId = account("recipient", 0, SEED);234 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());234 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());235 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;235 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;236 let data = default_fungible_data();236 let data = default_fungible_data();237 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;237 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;238238239 }: transfer(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1, 1)239 }: transfer(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1, 1)240240241 transfer_refungible {241 transfer_refungible {242 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();242 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();243 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();243 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();244 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();244 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();245 let mode: CollectionMode = CollectionMode::ReFungible(3);245 let mode: CollectionMode = CollectionMode::ReFungible(3);246 let recipient: T::AccountId = account("recipient", 0, SEED);246 let recipient: T::AccountId = account("recipient", 0, SEED);247 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());247 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());248 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;248 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;249 let data = default_re_fungible_data();249 let data = default_re_fungible_data();250 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;250 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;251251252 }: transfer(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1, 1)252 }: transfer(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1, 1)253253254 approve {254 approve {255 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();255 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();256 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();256 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();257 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();257 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();258 let mode: CollectionMode = CollectionMode::ReFungible(3);258 let mode: CollectionMode = CollectionMode::ReFungible(3);259 let recipient: T::AccountId = account("recipient", 0, SEED);259 let recipient: T::AccountId = account("recipient", 0, SEED);260 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());260 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());261 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;261 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;262 let data = default_re_fungible_data();262 let data = default_re_fungible_data();263 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;263 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;264264265 }: approve(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1)265 }: approve(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1)266266267 // Nft267 // Nft268 transfer_from_nft {268 transfer_from_nft {269 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();269 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();270 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();270 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();271 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();271 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();272 let mode: CollectionMode = CollectionMode::NFT;272 let mode: CollectionMode = CollectionMode::NFT;273 let recipient: T::AccountId = account("recipient", 0, SEED);273 let recipient: T::AccountId = account("recipient", 0, SEED);274 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());274 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());275 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;275 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;276 let data = default_nft_data();276 let data = default_nft_data();277 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;277 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;278 Nft::<T>::approve(RawOrigin::Signed(caller.clone()).into(), recipient.clone(), 2, 1)?;278 Nft::<T>::approve(RawOrigin::Signed(caller.clone()).into(), recipient.clone(), 2, 1)?;279279280 }: transfer_from(RawOrigin::Signed(caller.clone()), caller.clone(), recipient.clone(), 2, 1, 1)280 }: transfer_from(RawOrigin::Signed(caller.clone()), caller.clone(), recipient.clone(), 2, 1, 1)281281282 // Fungible282 // Fungible283 transfer_from_fungible {283 transfer_from_fungible {284 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();284 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();285 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();285 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();286 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();286 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();287 let mode: CollectionMode = CollectionMode::Fungible(3);287 let mode: CollectionMode = CollectionMode::Fungible(3);288 let recipient: T::AccountId = account("recipient", 0, SEED);288 let recipient: T::AccountId = account("recipient", 0, SEED);289 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());289 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());290 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;290 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;291 let data = default_fungible_data();291 let data = default_fungible_data();292 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;292 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;293 Nft::<T>::approve(RawOrigin::Signed(caller.clone()).into(), recipient.clone(), 2, 1)?;293 Nft::<T>::approve(RawOrigin::Signed(caller.clone()).into(), recipient.clone(), 2, 1)?;294294295 }: transfer_from(RawOrigin::Signed(caller.clone()), caller.clone(), recipient.clone(), 2, 1, 1)295 }: transfer_from(RawOrigin::Signed(caller.clone()), caller.clone(), recipient.clone(), 2, 1, 1)296296297 // ReFungible297 // ReFungible298 transfer_from_refungible {298 transfer_from_refungible {299 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();299 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();300 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();300 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();301 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();301 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();302 let mode: CollectionMode = CollectionMode::ReFungible(3);302 let mode: CollectionMode = CollectionMode::ReFungible(3);303 let recipient: T::AccountId = account("recipient", 0, SEED);303 let recipient: T::AccountId = account("recipient", 0, SEED);304 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());304 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());305 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;305 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;306 let data = default_re_fungible_data();306 let data = default_re_fungible_data();307 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;307 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;308 Nft::<T>::approve(RawOrigin::Signed(caller.clone()).into(), recipient.clone(), 2, 1)?;308 Nft::<T>::approve(RawOrigin::Signed(caller.clone()).into(), recipient.clone(), 2, 1)?;309309310 }: transfer_from(RawOrigin::Signed(caller.clone()), caller.clone(), recipient.clone(), 2, 1, 1)310 }: transfer_from(RawOrigin::Signed(caller.clone()), caller.clone(), recipient.clone(), 2, 1, 1)311311312 enable_contract_sponsoring {312 enable_contract_sponsoring {313 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());313 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());314314315 }: enable_contract_sponsoring(RawOrigin::Signed(caller.clone()), caller.clone(), true)315 }: enable_contract_sponsoring(RawOrigin::Signed(caller.clone()), caller.clone(), true)316316317 set_offchain_schema {317 set_offchain_schema {318 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();318 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();319 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();319 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();320 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();320 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();321 let mode: CollectionMode = CollectionMode::ReFungible(3);321 let mode: CollectionMode = CollectionMode::ReFungible(3);322 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());322 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());323 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;323 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;324324325 }: set_offchain_schema(RawOrigin::Signed(caller.clone()), 2, [1,2,3].to_vec())325 }: set_offchain_schema(RawOrigin::Signed(caller.clone()), 2, [1,2,3].to_vec())326326327 set_const_on_chain_schema {327 set_const_on_chain_schema {328 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();328 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();329 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();329 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();330 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();330 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();331 let mode: CollectionMode = CollectionMode::ReFungible(3);331 let mode: CollectionMode = CollectionMode::ReFungible(3);332 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());332 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());333 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;333 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;334 }: set_const_on_chain_schema(RawOrigin::Signed(caller.clone()), 2, [1,2,3].to_vec())334 }: set_const_on_chain_schema(RawOrigin::Signed(caller.clone()), 2, [1,2,3].to_vec())335 335336 set_variable_on_chain_schema {336 set_variable_on_chain_schema {337 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();337 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();338 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();338 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();339 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();339 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();340 let mode: CollectionMode = CollectionMode::ReFungible(3);340 let mode: CollectionMode = CollectionMode::ReFungible(3);341 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());341 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());342 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;342 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;343 }: set_variable_on_chain_schema(RawOrigin::Signed(caller.clone()), 2, [1,2,3].to_vec())343 }: set_variable_on_chain_schema(RawOrigin::Signed(caller.clone()), 2, [1,2,3].to_vec())344344345 set_variable_meta_data {345 set_variable_meta_data {346 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();346 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();347 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();347 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();348 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();348 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();349 let mode: CollectionMode = CollectionMode::NFT;349 let mode: CollectionMode = CollectionMode::NFT;350 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());350 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());351 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;351 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;352 let data = default_nft_data();352 let data = default_nft_data();353 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;353 Nft::<T>::create_item(RawOrigin::Signed(caller.clone()).into(), 2, caller.clone(), data)?;354354355 }: set_variable_meta_data(RawOrigin::Signed(caller.clone()), 2, 1, [1, 2, 3].to_vec())355 }: set_variable_meta_data(RawOrigin::Signed(caller.clone()), 2, 1, [1, 2, 3].to_vec())356356357 set_schema_version {357 set_schema_version {358 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();358 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();359 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();359 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();360 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();360 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();361 let mode: CollectionMode = CollectionMode::NFT;361 let mode: CollectionMode = CollectionMode::NFT;362 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());362 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());363 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;363 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;364 }: set_schema_version(RawOrigin::Signed(caller.clone()), 2, SchemaVersion::Unique)364 }: set_schema_version(RawOrigin::Signed(caller.clone()), 2, SchemaVersion::Unique)365365366 set_chain_limits {366 set_chain_limits {367 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());367 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());368 let limits = ChainLimits { 368 let limits = ChainLimits {369 collection_numbers_limit: 0,369 collection_numbers_limit: 0,370 account_token_ownership_limit: 0,370 account_token_ownership_limit: 0,371 collections_admins_limit: 0,371 collections_admins_limit: 0,372 custom_data_limit: 0,372 custom_data_limit: 0,373 nft_sponsor_transfer_timeout: 0,373 nft_sponsor_transfer_timeout: 0,374 fungible_sponsor_transfer_timeout: 0,374 fungible_sponsor_transfer_timeout: 0,375 refungible_sponsor_transfer_timeout: 0375 refungible_sponsor_transfer_timeout: 0376 };376 };377 }: set_chain_limits(RawOrigin::Signed(caller.clone()), limits)377 }: set_chain_limits(RawOrigin::Signed(caller.clone()), limits)378378379 set_contract_sponsoring_rate_limit {379 set_contract_sponsoring_rate_limit {380 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();380 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();381 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();381 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();382 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();382 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();383 let mode: CollectionMode = CollectionMode::NFT;383 let mode: CollectionMode = CollectionMode::NFT;384 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());384 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());385 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;385 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;386 let block_number: T::BlockNumber = 0.into(); 386 let block_number: T::BlockNumber = 0.into();387 }: set_contract_sponsoring_rate_limit(RawOrigin::Signed(caller.clone()), caller.clone(), block_number)387 }: set_contract_sponsoring_rate_limit(RawOrigin::Signed(caller.clone()), caller.clone(), block_number)388388389 set_collection_limits{389 set_collection_limits{390 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();390 let col_name1: Vec<u16> = "Test1".encode_utf16().collect::<Vec<u16>>();391 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();391 let col_desc1: Vec<u16> = "TestDescription1".encode_utf16().collect::<Vec<u16>>();392 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();392 let token_prefix1: Vec<u8> = b"token_prefix1".to_vec();393 let mode: CollectionMode = CollectionMode::NFT;393 let mode: CollectionMode = CollectionMode::NFT;394 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());394 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());395 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;395 Nft::<T>::create_collection(RawOrigin::Signed(caller.clone()).into(), col_name1.clone(), col_desc1.clone(), token_prefix1.clone(), mode.clone())?;396 396397 let cl = CollectionLimits {397 let cl = CollectionLimits {398 account_token_ownership_limit: 0,398 account_token_ownership_limit: 0,399 sponsored_data_size: 0,399 sponsored_data_size: 0,400 token_limit: 0,400 token_limit: 0,401 sponsor_transfer_timeout: 0401 sponsor_transfer_timeout: 0402 };402 };403403404 }: set_collection_limits(RawOrigin::Signed(caller.clone()), 2, cl)404 }: set_collection_limits(RawOrigin::Signed(caller.clone()), 2, cl)405405406 add_to_contract_white_list{406 add_to_contract_white_list{407 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());407 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());408 }: add_to_contract_white_list(RawOrigin::Signed(caller.clone()), caller.clone(), caller.clone())408 }: add_to_contract_white_list(RawOrigin::Signed(caller.clone()), caller.clone(), caller.clone())409409410 remove_from_contract_white_list{410 remove_from_contract_white_list{411 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());411 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());412 Nft::<T>::add_to_contract_white_list(RawOrigin::Signed(caller.clone()).into(), caller.clone(), caller.clone())?;412 Nft::<T>::add_to_contract_white_list(RawOrigin::Signed(caller.clone()).into(), caller.clone(), caller.clone())?;413 }: remove_from_contract_white_list(RawOrigin::Signed(caller.clone()), caller.clone(), caller.clone())413 }: remove_from_contract_white_list(RawOrigin::Signed(caller.clone()), caller.clone(), caller.clone())414414415 toggle_contract_white_list{415 toggle_contract_white_list{416 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());416 let caller: T::AccountId = T::AccountId::from(whitelisted_caller());417 }: toggle_contract_white_list(RawOrigin::Signed(caller.clone()), caller.clone(), true)417 }: toggle_contract_white_list(RawOrigin::Signed(caller.clone()), caller.clone(), true)418*/418*/419}419}420420pallets/nft/src/default_weights.rsdiffbeforeafterboth223impl crate::WeightInfo for () {3impl crate::WeightInfo for () {4 fn create_collection() -> Weight {4 fn create_collection() -> Weight {5 (70_000_000 as Weight)5 70_000_000_u646 .saturating_add(DbWeight::get().reads(7 as Weight))6 .saturating_add(DbWeight::get().reads(7_u64))7 .saturating_add(DbWeight::get().writes(5 as Weight))7 .saturating_add(DbWeight::get().writes(5_u64))8 }8 }9 fn destroy_collection() -> Weight {9 fn destroy_collection() -> Weight {10 (90_000_000 as Weight)10 90_000_000_u6411 .saturating_add(DbWeight::get().reads(2 as Weight))11 .saturating_add(DbWeight::get().reads(2_u64))12 .saturating_add(DbWeight::get().writes(5 as Weight))12 .saturating_add(DbWeight::get().writes(5_u64))13 }13 }14 fn add_to_white_list() -> Weight {14 fn add_to_white_list() -> Weight {15 (30_000_000 as Weight)15 30_000_000_u6416 .saturating_add(DbWeight::get().reads(3 as Weight))16 .saturating_add(DbWeight::get().reads(3_u64))17 .saturating_add(DbWeight::get().writes(1 as Weight))17 .saturating_add(DbWeight::get().writes(1_u64))18 }18 }19 fn remove_from_white_list() -> Weight {19 fn remove_from_white_list() -> Weight {20 (35_000_000 as Weight)20 35_000_000_u6421 .saturating_add(DbWeight::get().reads(3 as Weight))21 .saturating_add(DbWeight::get().reads(3_u64))22 .saturating_add(DbWeight::get().writes(1 as Weight))22 .saturating_add(DbWeight::get().writes(1_u64))23 }23 }24 fn set_public_access_mode() -> Weight {24 fn set_public_access_mode() -> Weight {25 (27_000_000 as Weight)25 27_000_000_u6426 .saturating_add(DbWeight::get().reads(1 as Weight))26 .saturating_add(DbWeight::get().reads(1_u64))27 .saturating_add(DbWeight::get().writes(1 as Weight))27 .saturating_add(DbWeight::get().writes(1_u64))28 }28 }29 fn set_mint_permission() -> Weight {29 fn set_mint_permission() -> Weight {30 (27_000_000 as Weight)30 27_000_000_u6431 .saturating_add(DbWeight::get().reads(1 as Weight))31 .saturating_add(DbWeight::get().reads(1_u64))32 .saturating_add(DbWeight::get().writes(1 as Weight))32 .saturating_add(DbWeight::get().writes(1_u64))33 }33 }34 fn change_collection_owner() -> Weight {34 fn change_collection_owner() -> Weight {35 (27_000_000 as Weight)35 27_000_000_u6436 .saturating_add(DbWeight::get().reads(1 as Weight))36 .saturating_add(DbWeight::get().reads(1_u64))37 .saturating_add(DbWeight::get().writes(1 as Weight))37 .saturating_add(DbWeight::get().writes(1_u64))38 }38 }39 fn add_collection_admin() -> Weight {39 fn add_collection_admin() -> Weight {40 (32_000_000 as Weight)40 32_000_000_u6441 .saturating_add(DbWeight::get().reads(3 as Weight))41 .saturating_add(DbWeight::get().reads(3_u64))42 .saturating_add(DbWeight::get().writes(1 as Weight))42 .saturating_add(DbWeight::get().writes(1_u64))43 }43 }44 fn remove_collection_admin() -> Weight {44 fn remove_collection_admin() -> Weight {45 (50_000_000 as Weight)45 50_000_000_u6446 .saturating_add(DbWeight::get().reads(2 as Weight))46 .saturating_add(DbWeight::get().reads(2_u64))47 .saturating_add(DbWeight::get().writes(1 as Weight))47 .saturating_add(DbWeight::get().writes(1_u64))48 }48 }49 fn set_collection_sponsor() -> Weight {49 fn set_collection_sponsor() -> Weight {50 (32_000_000 as Weight)50 32_000_000_u6451 .saturating_add(DbWeight::get().reads(2 as Weight))51 .saturating_add(DbWeight::get().reads(2_u64))52 .saturating_add(DbWeight::get().writes(1 as Weight))52 .saturating_add(DbWeight::get().writes(1_u64))53 } 53 }54 fn confirm_sponsorship() -> Weight {54 fn confirm_sponsorship() -> Weight {55 (22_000_000 as Weight)55 22_000_000_u6456 .saturating_add(DbWeight::get().reads(1 as Weight))56 .saturating_add(DbWeight::get().reads(1_u64))57 .saturating_add(DbWeight::get().writes(1 as Weight))57 .saturating_add(DbWeight::get().writes(1_u64))58 } 58 }59 fn remove_collection_sponsor() -> Weight {59 fn remove_collection_sponsor() -> Weight {60 (24_000_000 as Weight)60 24_000_000_u6461 .saturating_add(DbWeight::get().reads(1 as Weight))61 .saturating_add(DbWeight::get().reads(1_u64))62 .saturating_add(DbWeight::get().writes(1 as Weight))62 .saturating_add(DbWeight::get().writes(1_u64))63 } 63 }64 fn create_item(s: usize, ) -> Weight {64 fn create_item(s: usize) -> Weight {65 (130_000_000 as Weight)65 130_000_000_u6466 .saturating_add((2135 as Weight).saturating_mul(s as Weight).saturating_mul(500 as Weight)) // 500 is temporary multiplier, fee for storage66 .saturating_add(2135_u64.saturating_mul(s as Weight).saturating_mul(500_u64)) // 500 is temporary multiplier, fee for storage67 .saturating_add(DbWeight::get().reads(10 as Weight))67 .saturating_add(DbWeight::get().reads(10_u64))68 .saturating_add(DbWeight::get().writes(8 as Weight))68 .saturating_add(DbWeight::get().writes(8_u64))69 } 69 }70 fn burn_item() -> Weight {70 fn burn_item() -> Weight {71 (170_000_000 as Weight)71 170_000_000_u6472 .saturating_add(DbWeight::get().reads(9 as Weight))72 .saturating_add(DbWeight::get().reads(9_u64))73 .saturating_add(DbWeight::get().writes(7 as Weight))73 .saturating_add(DbWeight::get().writes(7_u64))74 } 74 }75 fn transfer() -> Weight {75 fn transfer() -> Weight {76 (125_000_000 as Weight)76 125_000_000_u6477 .saturating_add(DbWeight::get().reads(7 as Weight))77 .saturating_add(DbWeight::get().reads(7_u64))78 .saturating_add(DbWeight::get().writes(7 as Weight))78 .saturating_add(DbWeight::get().writes(7_u64))79 } 79 }80 fn approve() -> Weight {80 fn approve() -> Weight {81 (45_000_000 as Weight)81 45_000_000_u6482 .saturating_add(DbWeight::get().reads(3 as Weight))82 .saturating_add(DbWeight::get().reads(3_u64))83 .saturating_add(DbWeight::get().writes(1 as Weight))83 .saturating_add(DbWeight::get().writes(1_u64))84 }84 }85 fn transfer_from() -> Weight {85 fn transfer_from() -> Weight {86 (150_000_000 as Weight)86 150_000_000_u6487 .saturating_add(DbWeight::get().reads(9 as Weight))87 .saturating_add(DbWeight::get().reads(9_u64))88 .saturating_add(DbWeight::get().writes(8 as Weight))88 .saturating_add(DbWeight::get().writes(8_u64))89 }89 }90 fn set_offchain_schema() -> Weight {90 fn set_offchain_schema() -> Weight {91 (33_000_000 as Weight)91 33_000_000_u6492 .saturating_add(DbWeight::get().reads(2 as Weight))92 .saturating_add(DbWeight::get().reads(2_u64))93 .saturating_add(DbWeight::get().writes(1 as Weight))93 .saturating_add(DbWeight::get().writes(1_u64))94 }94 }95 fn set_const_on_chain_schema() -> Weight {95 fn set_const_on_chain_schema() -> Weight {96 (11_100_000 as Weight)96 11_100_000_u6497 .saturating_add(DbWeight::get().reads(2 as Weight))97 .saturating_add(DbWeight::get().reads(2_u64))98 .saturating_add(DbWeight::get().writes(1 as Weight))98 .saturating_add(DbWeight::get().writes(1_u64))99 }99 }100 fn set_variable_on_chain_schema() -> Weight {100 fn set_variable_on_chain_schema() -> Weight {101 (11_100_000 as Weight)101 11_100_000_u64102 .saturating_add(DbWeight::get().reads(2 as Weight))102 .saturating_add(DbWeight::get().reads(2_u64))103 .saturating_add(DbWeight::get().writes(1 as Weight))103 .saturating_add(DbWeight::get().writes(1_u64))104 }104 }105 fn set_variable_meta_data() -> Weight {105 fn set_variable_meta_data() -> Weight {106 (17_500_000 as Weight)106 17_500_000_u64107 .saturating_add(DbWeight::get().reads(2 as Weight))107 .saturating_add(DbWeight::get().reads(2_u64))108 .saturating_add(DbWeight::get().writes(1 as Weight))108 .saturating_add(DbWeight::get().writes(1_u64))109 }109 }110 fn enable_contract_sponsoring() -> Weight {110 fn enable_contract_sponsoring() -> Weight {111 (13_000_000 as Weight)111 13_000_000_u64112 .saturating_add(DbWeight::get().reads(1 as Weight))112 .saturating_add(DbWeight::get().reads(1_u64))113 .saturating_add(DbWeight::get().writes(1 as Weight))113 .saturating_add(DbWeight::get().writes(1_u64))114 }114 }115 fn set_schema_version() -> Weight {115 fn set_schema_version() -> Weight {116 (8_500_000 as Weight)116 8_500_000_u64117 .saturating_add(DbWeight::get().reads(2 as Weight))117 .saturating_add(DbWeight::get().reads(2_u64))118 .saturating_add(DbWeight::get().writes(1 as Weight))118 .saturating_add(DbWeight::get().writes(1_u64))119 }119 }120 fn set_chain_limits() -> Weight {120 fn set_chain_limits() -> Weight {121 (1_300_000 as Weight)121 1_300_000_u64122 .saturating_add(DbWeight::get().reads(0 as Weight))122 .saturating_add(DbWeight::get().reads(0_u64))123 .saturating_add(DbWeight::get().writes(1 as Weight))123 .saturating_add(DbWeight::get().writes(1_u64))124 }124 }125 fn set_contract_sponsoring_rate_limit() -> Weight {125 fn set_contract_sponsoring_rate_limit() -> Weight {126 (3_500_000 as Weight)126 3_500_000_u64127 .saturating_add(DbWeight::get().reads(0 as Weight))127 .saturating_add(DbWeight::get().reads(0_u64))128 .saturating_add(DbWeight::get().writes(2 as Weight))128 .saturating_add(DbWeight::get().writes(2_u64))129 } 129 }130 fn set_variable_meta_data_sponsoring_rate_limit() -> Weight {130 fn set_variable_meta_data_sponsoring_rate_limit() -> Weight {131 (3_500_000 as Weight)131 3_500_000_u64132 .saturating_add(DbWeight::get().reads(2 as Weight))132 .saturating_add(DbWeight::get().reads(2_u64))133 .saturating_add(DbWeight::get().writes(1 as Weight))133 .saturating_add(DbWeight::get().writes(1_u64))134 }134 }135 fn toggle_contract_white_list() -> Weight {135 fn toggle_contract_white_list() -> Weight {136 (3_000_000 as Weight)136 3_000_000_u64137 .saturating_add(DbWeight::get().reads(0 as Weight))137 .saturating_add(DbWeight::get().reads(0_u64))138 .saturating_add(DbWeight::get().writes(2 as Weight))138 .saturating_add(DbWeight::get().writes(2_u64))139 } 139 }140 fn add_to_contract_white_list() -> Weight {140 fn add_to_contract_white_list() -> Weight {141 (3_000_000 as Weight)141 3_000_000_u64142 .saturating_add(DbWeight::get().reads(0 as Weight))142 .saturating_add(DbWeight::get().reads(0_u64))143 .saturating_add(DbWeight::get().writes(2 as Weight))143 .saturating_add(DbWeight::get().writes(2_u64))144 } 144 }145 fn remove_from_contract_white_list() -> Weight {145 fn remove_from_contract_white_list() -> Weight {146 (3_200_000 as Weight)146 3_200_000_u64147 .saturating_add(DbWeight::get().reads(0 as Weight))147 .saturating_add(DbWeight::get().reads(0_u64))148 .saturating_add(DbWeight::get().writes(2 as Weight))148 .saturating_add(DbWeight::get().writes(2_u64))149 }149 }150 fn set_collection_limits() -> Weight {150 fn set_collection_limits() -> Weight {151 (8_900_000 as Weight)151 8_900_000_u64152 .saturating_add(DbWeight::get().reads(2 as Weight))152 .saturating_add(DbWeight::get().reads(2_u64))153 .saturating_add(DbWeight::get().writes(1 as Weight))153 .saturating_add(DbWeight::get().writes(1_u64))154 }154 }155}155}156156pallets/nft/src/eth/account.rsdiffbeforeafterboth101011pub trait CrossAccountId<AccountId>: 11pub trait CrossAccountId<AccountId>:12 Encode + EncodeLike + Decode + 12 Encode + EncodeLike + Decode + Clone + PartialEq + Ord + core::fmt::Debug13 Clone + PartialEq + Ord + core::fmt::Debug // + 13// +14 // Serialize + Deserialize<'static> 14// Serialize + Deserialize<'static>15{15{16 fn as_sub(&self) -> &AccountId;16 fn as_sub(&self) -> &AccountId;17 fn as_eth(&self) -> &H160;17 fn as_eth(&self) -> &H160;20 fn from_eth(account: H160) -> Self;20 fn from_eth(account: H160) -> Self;21}21}222223#[derive(Eq)]23#[derive(Eq, Serialize, Deserialize)]24#[derive(Serialize, Deserialize)]25pub struct BasicCrossAccountId<T: Config> {24pub struct BasicCrossAccountId<T: Config> {26 /// If true - then ethereum is canonical encoding25 /// If true - then ethereum is canonical encoding27 from_ethereum: bool,26 from_ethereum: bool,90impl<T: Config> Decode for BasicCrossAccountId<T> {90impl<T: Config> Decode for BasicCrossAccountId<T> {91 fn decode<I>(input: &mut I) -> Result<Self, codec::Error>91 fn decode<I>(input: &mut I) -> Result<Self, codec::Error>92 where I: codec::Input92 where93 I: codec::Input,93 {94 {94 Ok(match <Result<T::AccountId, H160>>::decode(input)? {95 Ok(match <Result<T::AccountId, H160>>::decode(input)? {95 Ok(s) => Self::from_sub(s),96 Ok(s) => Self::from_sub(s),pallets/nft/src/eth/erc.rsdiffbeforeafterboth58 #[indexed] operator: address,68 #[indexed]69 operator: address,59 approved: bool,70 approved: bool,60 }71 },61}72}627363#[solidity_interface(is(ERC165), events(ERC721Events))]74#[solidity_interface(is(ERC165), events(ERC721Events))]103 #[indexed] spender: address,164 #[indexed]165 spender: address,104 value: uint256,166 value: uint256,105 }167 },106}168}107169108#[solidity_interface(inline_is(InlineNameSymbol, InlineTotalSupply), events(ERC20Events))]170#[solidity_interface(inline_is(InlineNameSymbol, InlineTotalSupply), events(ERC20Events))]122 type Error;200 type Error;123}201}124202125/// Runtime metadata like helpers for evm126#[solidity_interface]127trait UniqueHelpers {128 type Error;129130 /// Returns interface for NFT collections131 fn nft_interface(&self) -> Result<string, Self::Error>;132 /// Returns interface for Fungible collections133 fn fungible_interface(&self) -> Result<string, Self::Error>;134}pallets/nft/src/eth/erc_impl.rsdiffbeforeafterboth56 Ok(index)56 Ok(index)57 }57 }585859 fn token_of_owner_by_index(&self, owner: address, index: uint256) -> Result<uint256> {59 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {60 // TODO: Not implemetable60 // TODO: Not implemetable61 Err("not implemented".into())61 Err("not implemented".into())62 }62 }77 fn owner_of(&self, token_id: uint256) -> Result<address> {77 fn owner_of(&self, token_id: uint256) -> Result<address> {78 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;78 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;79 let token = <NftItemList<T>>::get(self.id, token_id).ok_or("unknown token")?;79 let token = <NftItemList<T>>::get(self.id, token_id).ok_or("unknown token")?;80 Ok(token.owner.as_eth().clone())80 Ok(*token.owner.as_eth())81 }81 }82 fn safe_transfer_from_with_data(82 fn safe_transfer_from_with_data(83 &mut self,83 &mut self,114 let to = T::CrossAccountId::from_eth(to);114 let to = T::CrossAccountId::from_eth(to);115 let token_id = token_id.try_into().map_err(|_| "token_id overflow")?;115 let token_id = token_id.try_into().map_err(|_| "token_id overflow")?;116116117 <Module<T>>::transfer_from_internal(&caller, &from, &to, &self, token_id, 1)117 <Module<T>>::transfer_from_internal(&caller, &from, &to, self, token_id, 1)118 .map_err(|_| "transferFrom error")?;118 .map_err(|_| "transferFrom error")?;119 Ok(())119 Ok(())120 }120 }130 let approved = T::CrossAccountId::from_eth(approved);130 let approved = T::CrossAccountId::from_eth(approved);131 let token_id = token_id.try_into().map_err(|_| "token_id overflow")?;131 let token_id = token_id.try_into().map_err(|_| "token_id overflow")?;132132133 <Module<T>>::approve_internal(&caller, &approved, &self, token_id, 1)133 <Module<T>>::approve_internal(&caller, &approved, self, token_id, 1)134 .map_err(|_| "approve internal")?;134 .map_err(|_| "approve internal")?;135 Ok(())135 Ok(())136 }136 }170 caller: caller,170 caller: caller,171 to: address,171 to: address,172 token_id: uint256,172 token_id: uint256,173 value: value,173 _value: value,174 ) -> Result<void> {174 ) -> Result<void> {175 let caller = T::CrossAccountId::from_eth(caller);175 let caller = T::CrossAccountId::from_eth(caller);176 let to = T::CrossAccountId::from_eth(to);176 let to = T::CrossAccountId::from_eth(to);177 let token_id = token_id.try_into().map_err(|_| "amount overflow")?;177 let token_id = token_id.try_into().map_err(|_| "amount overflow")?;178178179 <Module<T>>::transfer_internal(&caller, &to, &self, token_id, 1)179 <Module<T>>::transfer_internal(&caller, &to, self, token_id, 1)180 .map_err(|_| "transfer error")?;180 .map_err(|_| "transfer error")?;181 Ok(())181 Ok(())182 }182 }226 let to = T::CrossAccountId::from_eth(to);226 let to = T::CrossAccountId::from_eth(to);227 let amount = amount.try_into().map_err(|_| "amount overflow")?;227 let amount = amount.try_into().map_err(|_| "amount overflow")?;228228229 <Module<T>>::transfer_internal(&caller, &to, &self, 1, amount)229 <Module<T>>::transfer_internal(&caller, &to, self, 1, amount)230 .map_err(|_| "transfer error")?;230 .map_err(|_| "transfer error")?;231 Ok(true)231 Ok(true)232 }232 }242 let to = T::CrossAccountId::from_eth(to);242 let to = T::CrossAccountId::from_eth(to);243 let amount = amount.try_into().map_err(|_| "amount overflow")?;243 let amount = amount.try_into().map_err(|_| "amount overflow")?;244244245 <Module<T>>::transfer_from_internal(&caller, &from, &to, &self, 1, amount)245 <Module<T>>::transfer_from_internal(&caller, &from, &to, self, 1, amount)246 .map_err(|_| "transferFrom error")?;246 .map_err(|_| "transferFrom error")?;247 Ok(true)247 Ok(true)248 }248 }251 let spender = T::CrossAccountId::from_eth(spender);251 let spender = T::CrossAccountId::from_eth(spender);252 let amount = amount.try_into().map_err(|_| "amount overflow")?;252 let amount = amount.try_into().map_err(|_| "amount overflow")?;253253254 <Module<T>>::approve_internal(&caller, &spender, &self, 1, amount)254 <Module<T>>::approve_internal(&caller, &spender, self, 1, amount)255 .map_err(|_| "approve internal")?;255 .map_err(|_| "approve internal")?;256 Ok(true)256 Ok(true)257 }257 }pallets/nft/src/eth/log.rsdiffbeforeafterboth1use sp_std::cell::RefCell;1use sp_std::cell::RefCell;2use sp_std::vec::Vec;2use sp_std::vec::Vec;3use sp_core::{H160, H256};34use ethereum::Log;4use ethereum::Log;556#[derive(Default)]6#[derive(Default)]pallets/nft/src/eth/mod.rsdiffbeforeafterboth28];28];292930fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {30fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {31 if ð[0..16] != ETH_ACCOUNT_PREFIX {31 if eth[0..16] != ETH_ACCOUNT_PREFIX {32 return None;32 return None;33 }33 }34 let mut id_bytes = [0; 4];34 let mut id_bytes = [0; 4];92 },92 },93 )?))93 )?))94 }94 }95 _ => {95 _ => Err(StringError::from(96 return Err(StringError::from(97 "erc calls only supported to fungible and nft collections for now",96 "erc calls only supported to fungible and nft collections for now",98 )97 )),99 .into())100 }101 }98 }102}99}103100111 .unwrap_or(false)108 .unwrap_or(false)112 }109 }113 fn get_code(target: &H160) -> Option<Vec<u8>> {110 fn get_code(target: &H160) -> Option<Vec<u8>> {114 map_eth_to_id(&target)111 map_eth_to_id(target)115 .and_then(<CollectionById<T>>::get)112 .and_then(<CollectionById<T>>::get)116 .map(|collection| {113 .map(|collection| {117 match collection.mode {114 match collection.mode {130 input: &[u8],127 input: &[u8],131 value: U256,128 value: U256,132 ) -> Option<PrecompileOutput> {129 ) -> Option<PrecompileOutput> {133 let mut collection = map_eth_to_id(&target)130 let mut collection = map_eth_to_id(target)134 .and_then(|id| <CollectionHandle<T>>::get_with_gas_limit(id, gas_limit))?;131 .and_then(|id| <CollectionHandle<T>>::get_with_gas_limit(id, gas_limit))?;135 let (method_id, input) = AbiReader::new_call(input).unwrap();132 let (method_id, input) = AbiReader::new_call(input).unwrap();136 let result = call_internal(&mut collection, *source, method_id, input, value);133 let result = call_internal(&mut collection, *source, method_id, input, value);156153157// TODO: This function is slow, and output can be memoized154// TODO: This function is slow, and output can be memoized158pub fn generate_transaction(collection_id: u32, chain_id: u64) -> ethereum::Transaction {155pub fn generate_transaction(collection_id: u32, chain_id: u64) -> ethereum::Transaction {159 let contract = collection_id_to_address(collection_id);160161 // FIXME: Can be done on wasm runtime with https://github.com/paritytech/substrate/pull/8728156 // FIXME: Can be done on wasm runtime with https://github.com/paritytech/substrate/pull/8728162 #[cfg(feature = "std")]157 #[cfg(feature = "std")]163 {158 {159 let contract = collection_id_to_address(collection_id);164 let signed = ethereum_tx_sign::RawTransaction {160 let signed = ethereum_tx_sign::RawTransaction {165 nonce: 0.into(),161 nonce: 0.into(),166 to: Some(contract.0.into()),162 to: Some(contract.0.into()),183 }179 }184 #[cfg(not(feature = "std"))]180 #[cfg(not(feature = "std"))]185 {181 {186 panic!("transaction generation not yet supported by wasm runtime")182 panic!("transaction generation not yet supported by wasm runtime while generating transaction for collection_id {}, chain_id {}", collection_id, chain_id)187 }183 }188}184}189185pallets/nft/src/eth/sponsoring.rsdiffbeforeafterboth223use crate::{Collection, ChainLimit, CollectionById, Config, NftTransferBasket, FungibleTransferBasket, eth::account::EvmBackwardsAddressMapping};3use crate::{4 Collection, ChainLimit, CollectionById, Config, NftTransferBasket, FungibleTransferBasket,5 eth::account::EvmBackwardsAddressMapping,6};4use evm_coder::abi::AbiReader;7use evm_coder::abi::AbiReader;5use frame_support::{storage::{StorageMap, StorageDoubleMap, StorageValue}, traits::Currency};8use frame_support::{9 storage::{StorageMap, StorageDoubleMap, StorageValue},10 traits::Currency,11};6use pallet_evm::{EVMCurrencyAdapter, WithdrawReason};12use pallet_evm::{EVMCurrencyAdapter, WithdrawReason};7use sp_core::{H160, U256};13use sp_core::{H160, U256};8use sp_std::prelude::*;14use sp_std::prelude::*;9use super::{account::CrossAccountId, erc::{UniqueFungibleCall, UniqueNFTCall, ERC721Call, ERC20Call, ERC721UniqueExtensionsCall}};15use super::{16 account::CrossAccountId,17 erc::{UniqueFungibleCall, UniqueNFTCall, ERC721Call, ERC20Call, ERC721UniqueExtensionsCall},18};10use core::convert::TryInto;19use core::convert::TryInto;112052 })53 | UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, .. }) => {34 let token_id: u32 = token_id.try_into().map_err(|_| AnyError)?;54 let token_id: u32 = token_id.try_into().map_err(|_| AnyError)?;35 let block_number = <frame_system::Module<T>>::block_number() as T::BlockNumber;55 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;36 let collection_limits = &collection.limits;56 let collection_limits = &collection.limits;37 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {57 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {38 collection_limits.sponsor_transfer_timeout58 collection_limits.sponsor_transfer_timeout50 }70 }51 if sponsor {71 if sponsor {52 <NftTransferBasket<T>>::insert(collection_id, token_id, block_number);72 <NftTransferBasket<T>>::insert(collection_id, token_id, block_number);53 return Ok(())73 return Ok(());54 }74 }55 },75 }56 _ => {},76 _ => {}57 }77 }58 },78 }59 crate::CollectionMode::Fungible(_) => {79 crate::CollectionMode::Fungible(_) => {60 let call: UniqueFungibleCall = UniqueFungibleCall::parse(method_id, &mut reader).map_err(|_| AnyError)?.ok_or(AnyError)?;80 let call: UniqueFungibleCall = UniqueFungibleCall::parse(method_id, &mut reader)81 .map_err(|_| AnyError)?82 .ok_or(AnyError)?;83 #[allow(clippy::single_match)]61 match call {84 match call {62 UniqueFungibleCall::ERC20(ERC20Call::Transfer {..}) => {85 UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {63 let who = T::CrossAccountId::from_eth(caller.clone());86 let who = T::CrossAccountId::from_eth(*caller);64 let collection_limits = &collection.limits;87 let collection_limits = &collection.limits;65 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {88 let limit: u32 = if collection_limits.sponsor_transfer_timeout > 0 {66 collection_limits.sponsor_transfer_timeout89 collection_limits.sponsor_transfer_timeout67 } else {90 } else {68 ChainLimit::get().fungible_sponsor_transfer_timeout91 ChainLimit::get().fungible_sponsor_transfer_timeout69 };92 };709371 let block_number = <frame_system::Module<T>>::block_number() as T::BlockNumber;94 let block_number = <frame_system::Pallet<T>>::block_number() as T::BlockNumber;72 let mut sponsored = true;95 let mut sponsored = true;73 if <FungibleTransferBasket<T>>::contains_key(collection_id, who.as_sub()) {96 if <FungibleTransferBasket<T>>::contains_key(collection_id, who.as_sub()) {74 let last_tx_block = <FungibleTransferBasket<T>>::get(collection_id, who.as_sub());97 let last_tx_block =107 who.as_sub(),108 block_number,109 );82 return Ok(())110 return Ok(());83 }111 }84 },112 }85 _ => {},113 _ => {}86 }114 }87 },115 }88 _ => {},116 _ => {}89 }117 }90 return Err(AnyError)118 Err(AnyError)91}119}9212093impl<T> pallet_evm::OnChargeEVMTransaction<T> for ChargeEvmTransaction121impl<T> pallet_evm::OnChargeEVMTransaction<T> for ChargeEvmTransaction104 ) -> Result<Self::LiquidityInfo, pallet_evm::Error<T>> {132 ) -> Result<Self::LiquidityInfo, pallet_evm::Error<T>> {105 let mut who_pays_fee = *who;133 let mut who_pays_fee = *who;106 if let WithdrawReason::Call { target, input } = &reason {134 if let WithdrawReason::Call { target, input } = &reason {107 if let Some(collection_id) = crate::eth::map_eth_to_id(&target) {135 if let Some(collection_id) = crate::eth::map_eth_to_id(target) {108 if let Some(collection) = <CollectionById<T>>::get(collection_id) {136 if let Some(collection) = <CollectionById<T>>::get(collection_id) {109 if let Some(sponsor) = collection.sponsorship.sponsor() {137 if let Some(sponsor) = collection.sponsorship.sponsor() {110 if try_sponsor(who, collection_id, &collection, &input).is_ok() {138 if try_sponsor(who, collection_id, &collection, input).is_ok() {111 who_pays_fee =139 who_pays_fee =112 T::EvmBackwardsAddressMapping::from_account_id(sponsor.clone());140 T::EvmBackwardsAddressMapping::from_account_id(sponsor.clone());113 }141 }pallets/nft/src/lib.rsdiffbeforeafterboth6#![recursion_limit = "1024"]6#![recursion_limit = "1024"]78#![cfg_attr(not(feature = "std"), no_std)]7#![cfg_attr(not(feature = "std"), no_std)]8#![allow(9 clippy::too_many_arguments,10 clippy::unnecessary_mut_passed,11 clippy::unused_unit12)]91310extern crate alloc;14extern crate alloc;1115303331use frame_system::{self as system, ensure_signed, ensure_root};34use frame_system::{self as system, ensure_signed, ensure_root};32use sp_core::H160;35use sp_core::H160;36use sp_std::vec;33use sp_runtime::sp_std::prelude::Vec;37use sp_runtime::sp_std::prelude::Vec;34use core::ops::{Deref, DerefMut};38use core::ops::{Deref, DerefMut};35use core::cell::RefCell;39use core::cell::RefCell;36use nft_data_structs::{40use nft_data_structs::{37 MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_REFUNGIBLE_PIECES,41 MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_REFUNGIBLE_PIECES,38 AccessMode, ChainLimits, Collection, CreateItemData, CollectionLimits,42 AccessMode, ChainLimits, Collection, CreateItemData, CollectionLimits, CollectionId,39 CollectionId, CollectionMode, TokenId, 43 CollectionMode, TokenId, SchemaVersion, SponsorshipState, Ownership, NftItemType,40 SchemaVersion, SponsorshipState, Ownership,41 NftItemType, FungibleItemType, ReFungibleItemType44 FungibleItemType, ReFungibleItemType,42};45};43use pallet_ethereum::EthereumTransactionSender;46use pallet_ethereum::EthereumTransactionSender;4447211 self.logs.log(log.to_log(self.evm_address))213 self.logs.log(log.to_log(self.evm_address))212 }214 }213 pub fn into_inner(self) -> Collection<T> {215 pub fn into_inner(self) -> Collection<T> {214 self.collection.clone()216 self.collection215 }217 }216}218}217impl<T: Config> Deref for CollectionHandle<T> {219impl<T: Config> Deref for CollectionHandle<T> {236238237 type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;239 type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;238 type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;240 type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;239 type EvmWithdrawOrigin: pallet_evm::EnsureAddressOrigin<Self::Origin, Success = Self::AccountId>;240241241 type CrossAccountId: CrossAccountId<Self::AccountId>;242 type CrossAccountId: CrossAccountId<Self::AccountId>;242 type Currency: Currency<Self::AccountId>;243 type Currency: Currency<Self::AccountId>;243 type CollectionCreationPrice: Get<<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance>;244 type CollectionCreationPrice: Get<245 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,246 >;244 type TreasuryAccountId: Get<Self::AccountId>;247 type TreasuryAccountId: Get<Self::AccountId>;245248375 CrossAccountId = <T as Config>::CrossAccountId,378 CrossAccountId = <T as Config>::CrossAccountId,376 {379 {377 /// New collection was created380 /// New collection was created378 /// 381 ///379 /// # Arguments382 /// # Arguments380 /// 383 ///381 /// * collection_id: Globally unique identifier of newly created collection.384 /// * collection_id: Globally unique identifier of newly created collection.382 /// 385 ///383 /// * mode: [CollectionMode] converted into u8.386 /// * mode: [CollectionMode] converted into u8.384 /// 387 ///385 /// * account_id: Collection owner.388 /// * account_id: Collection owner.386 CollectionCreated(CollectionId, u8, AccountId),389 CollectionCreated(CollectionId, u8, AccountId),387390388 /// New item was created.391 /// New item was created.389 /// 392 ///390 /// # Arguments393 /// # Arguments391 /// 394 ///392 /// * collection_id: Id of the collection where item was created.395 /// * collection_id: Id of the collection where item was created.393 /// 396 ///394 /// * item_id: Id of an item. Unique within the collection.397 /// * item_id: Id of an item. Unique within the collection.395 ///398 ///396 /// * recipient: Owner of newly created item 399 /// * recipient: Owner of newly created item397 ItemCreated(CollectionId, TokenId, CrossAccountId),400 ItemCreated(CollectionId, TokenId, CrossAccountId),398401399 /// Collection item was burned.402 /// Collection item was burned.400 /// 403 ///401 /// # Arguments404 /// # Arguments402 /// 405 ///403 /// collection_id.406 /// collection_id.404 /// 407 ///405 /// item_id: Identifier of burned NFT.408 /// item_id: Identifier of burned NFT.406 ItemDestroyed(CollectionId, TokenId),409 ItemDestroyed(CollectionId, TokenId),407410444 }447 }445448446 /// This method creates a Collection of NFTs. Each Token may have multiple properties encoded as an array of bytes of certain length. The initial owner and admin of the collection are set to the address that signed the transaction. Both addresses can be changed later.449 /// This method creates a Collection of NFTs. Each Token may have multiple properties encoded as an array of bytes of certain length. The initial owner and admin of the collection are set to the address that signed the transaction. Both addresses can be changed later.447 /// 450 ///448 /// # Permissions451 /// # Permissions449 /// 452 ///450 /// * Anyone.453 /// * Anyone.451 /// 454 ///452 /// # Arguments455 /// # Arguments453 /// 456 ///454 /// * collection_name: UTF-16 string with collection name (limit 64 characters), will be stored as zero-terminated.457 /// * collection_name: UTF-16 string with collection name (limit 64 characters), will be stored as zero-terminated.455 /// 458 ///456 /// * collection_description: UTF-16 string with collection description (limit 256 characters), will be stored as zero-terminated.459 /// * collection_description: UTF-16 string with collection description (limit 256 characters), will be stored as zero-terminated.457 /// 460 ///458 /// * token_prefix: UTF-8 string with token prefix.461 /// * token_prefix: UTF-8 string with token prefix.459 /// 462 ///460 /// * mode: [CollectionMode] collection type and type dependent data.463 /// * mode: [CollectionMode] collection type and type dependent data.461 // returns collection ID464 // returns collection ID462 #[weight = <T as Config>::WeightInfo::create_collection()]465 #[weight = <T as Config>::WeightInfo::create_collection()]522 mint_mode: false,525 mint_mode: false,523 access: AccessMode::Normal,526 access: AccessMode::Normal,524 description: collection_description,527 description: collection_description,525 decimal_points: decimal_points,528 decimal_points,526 token_prefix: token_prefix,529 token_prefix,527 offchain_schema: Vec::new(),530 offchain_schema: Vec::new(),528 schema_version: SchemaVersion::ImageURL,531 schema_version: SchemaVersion::ImageURL,529 sponsorship: SponsorshipState::Disabled,532 sponsorship: SponsorshipState::Disabled,536 <CollectionById<T>>::insert(next_id, new_collection);539 <CollectionById<T>>::insert(next_id, new_collection);537540538 // call event541 // call event539 Self::deposit_event(RawEvent::CollectionCreated(next_id, mode.into(), who));542 Self::deposit_event(RawEvent::CollectionCreated(next_id, mode.id(), who));540543541 Ok(())544 Ok(())542 }545 }543546544 /// **DANGEROUS**: Destroys collection and all NFTs within this collection. Users irrecoverably lose their assets and may lose real money.547 /// **DANGEROUS**: Destroys collection and all NFTs within this collection. Users irrecoverably lose their assets and may lose real money.545 /// 548 ///546 /// # Permissions549 /// # Permissions547 /// 550 ///548 /// * Collection Owner.551 /// * Collection Owner.549 /// 552 ///550 /// # Arguments553 /// # Arguments551 /// 554 ///552 /// * collection_id: collection to destroy.555 /// * collection_id: collection to destroy.553 #[weight = <T as Config>::WeightInfo::destroy_collection()]556 #[weight = <T as Config>::WeightInfo::destroy_collection()]554 #[transactional]557 #[transactional]587 }590 }588591589 /// Add an address to white list.592 /// Add an address to white list.590 /// 593 ///591 /// # Permissions594 /// # Permissions592 /// 595 ///593 /// * Collection Owner596 /// * Collection Owner594 /// * Collection Admin597 /// * Collection Admin595 /// 598 ///596 /// # Arguments599 /// # Arguments597 /// 600 ///598 /// * collection_id.601 /// * collection_id.599 /// 602 ///600 /// * address.603 /// * address.601 #[weight = <T as Config>::WeightInfo::add_to_white_list()]604 #[weight = <T as Config>::WeightInfo::add_to_white_list()]602 #[transactional]605 #[transactional]616 }619 }617620618 /// Remove an address from white list.621 /// Remove an address from white list.619 /// 622 ///620 /// # Permissions623 /// # Permissions621 /// 624 ///622 /// * Collection Owner625 /// * Collection Owner623 /// * Collection Admin626 /// * Collection Admin624 /// 627 ///625 /// # Arguments628 /// # Arguments626 /// 629 ///627 /// * collection_id.630 /// * collection_id.628 /// 631 ///629 /// * address.632 /// * address.630 #[weight = <T as Config>::WeightInfo::remove_from_white_list()]633 #[weight = <T as Config>::WeightInfo::remove_from_white_list()]631 #[transactional]634 #[transactional]645 }648 }646649647 /// Toggle between normal and white list access for the methods with access for `Anyone`.650 /// Toggle between normal and white list access for the methods with access for `Anyone`.648 /// 651 ///649 /// # Permissions652 /// # Permissions650 /// 653 ///651 /// * Collection Owner.654 /// * Collection Owner.652 /// 655 ///653 /// # Arguments656 /// # Arguments654 /// 657 ///655 /// * collection_id.658 /// * collection_id.656 /// 659 ///657 /// * mode: [AccessMode]660 /// * mode: [AccessMode]658 #[weight = <T as Config>::WeightInfo::set_public_access_mode()]661 #[weight = <T as Config>::WeightInfo::set_public_access_mode()]659 #[transactional]662 #[transactional]673 /// * White List is enabled, and676 /// * White List is enabled, and674 /// * Address is added to white list, and677 /// * Address is added to white list, and675 /// * This method was called with True parameter678 /// * This method was called with True parameter676 /// 679 ///677 /// # Permissions680 /// # Permissions678 /// * Collection Owner681 /// * Collection Owner679 ///682 ///680 /// # Arguments683 /// # Arguments681 /// 684 ///682 /// * collection_id.685 /// * collection_id.683 /// 686 ///684 /// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.687 /// * mint_permission: Boolean parameter. If True, allows minting to Anyone with conditions above.685 #[weight = <T as Config>::WeightInfo::set_mint_permission()]688 #[weight = <T as Config>::WeightInfo::set_mint_permission()]686 #[transactional]689 #[transactional]697 }700 }698701699 /// Change the owner of the collection.702 /// Change the owner of the collection.700 /// 703 ///701 /// # Permissions704 /// # Permissions702 /// 705 ///703 /// * Collection Owner.706 /// * Collection Owner.704 /// 707 ///705 /// # Arguments708 /// # Arguments706 /// 709 ///707 /// * collection_id.710 /// * collection_id.708 /// 711 ///709 /// * new_owner.712 /// * new_owner.710 #[weight = <T as Config>::WeightInfo::change_collection_owner()]713 #[weight = <T as Config>::WeightInfo::change_collection_owner()]711 #[transactional]714 #[transactional]721 }724 }722725723 /// Adds an admin of the Collection.726 /// Adds an admin of the Collection.724 /// NFT Collection can be controlled by multiple admin addresses (some which can also be servers, for example). Admins can issue and burn NFTs, as well as add and remove other admins, but cannot change NFT or Collection ownership. 727 /// NFT Collection can be controlled by multiple admin addresses (some which can also be servers, for example). Admins can issue and burn NFTs, as well as add and remove other admins, but cannot change NFT or Collection ownership.725 /// 728 ///726 /// # Permissions729 /// # Permissions727 /// 730 ///728 /// * Collection Owner.731 /// * Collection Owner.729 /// * Collection Admin.732 /// * Collection Admin.730 /// 733 ///731 /// # Arguments734 /// # Arguments732 /// 735 ///733 /// * collection_id: ID of the Collection to add admin for.736 /// * collection_id: ID of the Collection to add admin for.734 /// 737 ///735 /// * new_admin_id: Address of new admin to add.738 /// * new_admin_id: Address of new admin to add.736 #[weight = <T as Config>::WeightInfo::add_collection_admin()]739 #[weight = <T as Config>::WeightInfo::add_collection_admin()]737 #[transactional]740 #[transactional]756 /// Remove admin address of the Collection. An admin address can remove itself. List of admins may become empty, in which case only Collection Owner will be able to add an Admin.759 /// Remove admin address of the Collection. An admin address can remove itself. List of admins may become empty, in which case only Collection Owner will be able to add an Admin.757 ///760 ///758 /// # Permissions761 /// # Permissions759 /// 762 ///760 /// * Collection Owner.763 /// * Collection Owner.761 /// * Collection Admin.764 /// * Collection Admin.762 /// 765 ///763 /// # Arguments766 /// # Arguments764 /// 767 ///765 /// * collection_id: ID of the Collection to remove admin for.768 /// * collection_id: ID of the Collection to remove admin for.766 /// 769 ///767 /// * account_id: Address of admin to remove.770 /// * account_id: Address of admin to remove.768 #[weight = <T as Config>::WeightInfo::remove_collection_admin()]771 #[weight = <T as Config>::WeightInfo::remove_collection_admin()]769 #[transactional]772 #[transactional]773 Self::check_owner_or_admin_permissions(&collection, &sender)?;776 Self::check_owner_or_admin_permissions(&collection, &sender)?;774 let mut admin_arr = <AdminList<T>>::get(collection_id);777 let mut admin_arr = <AdminList<T>>::get(collection_id);775778776 match admin_arr.binary_search(&account_id) {779 if let Ok(idx) = admin_arr.binary_search(&account_id) {777 Ok(idx) => {778 admin_arr.remove(idx);780 admin_arr.remove(idx);779 <AdminList<T>>::insert(collection_id, admin_arr);781 <AdminList<T>>::insert(collection_id, admin_arr);780 },781 Err(_) => {}782 }782 }783 Ok(())783 Ok(())784 }784 }785785786 /// # Permissions786 /// # Permissions787 /// 787 ///788 /// * Collection Owner788 /// * Collection Owner789 /// 789 ///790 /// # Arguments790 /// # Arguments791 /// 791 ///792 /// * collection_id.792 /// * collection_id.793 /// 793 ///794 /// * new_sponsor.794 /// * new_sponsor.795 #[weight = <T as Config>::WeightInfo::set_collection_sponsor()]795 #[weight = <T as Config>::WeightInfo::set_collection_sponsor()]796 #[transactional]796 #[transactional]806 }806 }807807808 /// # Permissions808 /// # Permissions809 /// 809 ///810 /// * Sponsor.810 /// * Sponsor.811 /// 811 ///812 /// # Arguments812 /// # Arguments813 /// 813 ///814 /// * collection_id.814 /// * collection_id.815 #[weight = <T as Config>::WeightInfo::confirm_sponsorship()]815 #[weight = <T as Config>::WeightInfo::confirm_sponsorship()]816 #[transactional]816 #[transactional]834 /// # Permissions834 /// # Permissions835 ///835 ///836 /// * Collection owner.836 /// * Collection owner.837 /// 837 ///838 /// # Arguments838 /// # Arguments839 /// 839 ///840 /// * collection_id.840 /// * collection_id.841 #[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]841 #[weight = <T as Config>::WeightInfo::remove_collection_sponsor()]842 #[transactional]842 #[transactional]853 }853 }854854855 /// This method creates a concrete instance of NFT Collection created with CreateCollection method.855 /// This method creates a concrete instance of NFT Collection created with CreateCollection method.856 /// 856 ///857 /// # Permissions857 /// # Permissions858 /// 858 ///859 /// * Collection Owner.859 /// * Collection Owner.860 /// * Collection Admin.860 /// * Collection Admin.861 /// * Anyone if861 /// * Anyone if862 /// * White List is enabled, and862 /// * White List is enabled, and863 /// * Address is added to white list, and863 /// * Address is added to white list, and864 /// * MintPermission is enabled (see SetMintPermission method)864 /// * MintPermission is enabled (see SetMintPermission method)865 /// 865 ///866 /// # Arguments866 /// # Arguments867 /// 867 ///868 /// * collection_id: ID of the collection.868 /// * collection_id: ID of the collection.869 /// 869 ///870 /// * owner: Address, initial owner of the NFT.870 /// * owner: Address, initial owner of the NFT.871 ///871 ///872 /// * data: Token data to store on chain.872 /// * data: Token data to store on chain.876 // .saturating_add(RocksDbWeight::get().reads(10 as Weight))876 // .saturating_add(RocksDbWeight::get().reads(10 as Weight))877 // .saturating_add(RocksDbWeight::get().writes(8 as Weight))]877 // .saturating_add(RocksDbWeight::get().writes(8 as Weight))]878878879 #[weight = <T as Config>::WeightInfo::create_item(data.len())]879 #[weight = <T as Config>::WeightInfo::create_item(data.data_size())]880 #[transactional]880 #[transactional]881 pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResult {881 pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResult {882 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);882 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);889 }889 }890890891 /// This method creates multiple items in a collection created with CreateCollection method.891 /// This method creates multiple items in a collection created with CreateCollection method.892 /// 892 ///893 /// # Permissions893 /// # Permissions894 /// 894 ///895 /// * Collection Owner.895 /// * Collection Owner.896 /// * Collection Admin.896 /// * Collection Admin.897 /// * Anyone if897 /// * Anyone if898 /// * White List is enabled, and898 /// * White List is enabled, and899 /// * Address is added to white list, and899 /// * Address is added to white list, and900 /// * MintPermission is enabled (see SetMintPermission method)900 /// * MintPermission is enabled (see SetMintPermission method)901 /// 901 ///902 /// # Arguments902 /// # Arguments903 /// 903 ///904 /// * collection_id: ID of the collection.904 /// * collection_id: ID of the collection.905 /// 905 ///906 /// * itemsData: Array items properties. Each property is an array of bytes itself, see [create_item].906 /// * itemsData: Array items properties. Each property is an array of bytes itself, see [create_item].907 /// 907 ///908 /// * owner: Address, initial owner of the NFT.908 /// * owner: Address, initial owner of the NFT.909 #[weight = <T as Config>::WeightInfo::create_item(items_data.into_iter()909 #[weight = <T as Config>::WeightInfo::create_item(items_data.iter()910 .map(|data| { data.len() })910 .map(|data| { data.data_size() })911 .sum())]911 .sum())]912 #[transactional]912 #[transactional]913 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResult {913 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResult {914914915 ensure!(items_data.len() > 0, Error::<T>::EmptyArgument);915 ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);916 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);916 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);917 let collection = Self::get_collection(collection_id)?;917 let collection = Self::get_collection(collection_id)?;918918923 }923 }924924925 /// Destroys a concrete instance of NFT.925 /// Destroys a concrete instance of NFT.926 /// 926 ///927 /// # Permissions927 /// # Permissions928 /// 928 ///929 /// * Collection Owner.929 /// * Collection Owner.930 /// * Collection Admin.930 /// * Collection Admin.931 /// * Current NFT Owner.931 /// * Current NFT Owner.932 /// 932 ///933 /// # Arguments933 /// # Arguments934 /// 934 ///935 /// * collection_id: ID of the collection.935 /// * collection_id: ID of the collection.936 /// 936 ///937 /// * item_id: ID of NFT to burn.937 /// * item_id: ID of NFT to burn.938 #[weight = <T as Config>::WeightInfo::burn_item()]938 #[weight = <T as Config>::WeightInfo::burn_item()]939 #[transactional]939 #[transactional]949 }949 }950950951 /// Change ownership of the token.951 /// Change ownership of the token.952 /// 952 ///953 /// # Permissions953 /// # Permissions954 /// 954 ///955 /// * Collection Owner955 /// * Collection Owner956 /// * Collection Admin956 /// * Collection Admin957 /// * Current NFT owner957 /// * Current NFT owner958 ///958 ///959 /// # Arguments959 /// # Arguments960 /// 960 ///961 /// * recipient: Address of token recipient.961 /// * recipient: Address of token recipient.962 /// 962 ///963 /// * collection_id.963 /// * collection_id.964 /// 964 ///965 /// * item_id: ID of the item965 /// * item_id: ID of the item966 /// * Non-Fungible Mode: Required.966 /// * Non-Fungible Mode: Required.967 /// * Fungible Mode: Ignored.967 /// * Fungible Mode: Ignored.968 /// * Re-Fungible Mode: Required.968 /// * Re-Fungible Mode: Required.969 /// 969 ///970 /// * value: Amount to transfer.970 /// * value: Amount to transfer.971 /// * Non-Fungible Mode: Ignored971 /// * Non-Fungible Mode: Ignored972 /// * Fungible Mode: Must specify transferred amount972 /// * Fungible Mode: Must specify transferred amount984 }984 }985985986 /// Set, change, or remove approved address to transfer the ownership of the NFT.986 /// Set, change, or remove approved address to transfer the ownership of the NFT.987 /// 987 ///988 /// # Permissions988 /// # Permissions989 /// 989 ///990 /// * Collection Owner990 /// * Collection Owner991 /// * Collection Admin991 /// * Collection Admin992 /// * Current NFT owner992 /// * Current NFT owner993 /// 993 ///994 /// # Arguments994 /// # Arguments995 /// 995 ///996 /// * approved: Address that is approved to transfer this NFT or zero (if needed to remove approval).996 /// * approved: Address that is approved to transfer this NFT or zero (if needed to remove approval).997 /// 997 ///998 /// * collection_id.998 /// * collection_id.999 /// 999 ///1000 /// * item_id: ID of the item.1000 /// * item_id: ID of the item.1001 #[weight = <T as Config>::WeightInfo::approve()]1001 #[weight = <T as Config>::WeightInfo::approve()]1002 #[transactional]1002 #[transactional]1011 }1011 }1012 10121013 /// Change ownership of a NFT on behalf of the owner. See Approve method for additional information. After this method executes, the approval is removed so that the approved address will not be able to transfer this NFT again from this owner.1013 /// Change ownership of a NFT on behalf of the owner. See Approve method for additional information. After this method executes, the approval is removed so that the approved address will not be able to transfer this NFT again from this owner.1014 /// 1014 ///1015 /// # Permissions1015 /// # Permissions1016 /// * Collection Owner1016 /// * Collection Owner1017 /// * Collection Admin1017 /// * Collection Admin1018 /// * Current NFT owner1018 /// * Current NFT owner1019 /// * Address approved by current NFT owner1019 /// * Address approved by current NFT owner1020 /// 1020 ///1021 /// # Arguments1021 /// # Arguments1022 /// 1022 ///1023 /// * from: Address that owns token.1023 /// * from: Address that owns token.1024 /// 1024 ///1025 /// * recipient: Address of token recipient.1025 /// * recipient: Address of token recipient.1026 /// 1026 ///1027 /// * collection_id.1027 /// * collection_id.1028 /// 1028 ///1029 /// * item_id: ID of the item.1029 /// * item_id: ID of the item.1030 /// 1030 ///1031 /// * value: Amount to transfer.1031 /// * value: Amount to transfer.1032 #[weight = <T as Config>::WeightInfo::transfer_from()]1032 #[weight = <T as Config>::WeightInfo::transfer_from()]1033 #[transactional]1033 #[transactional]1054 // }1054 // }105510551056 /// Set off-chain data schema.1056 /// Set off-chain data schema.1057 /// 1057 ///1058 /// # Permissions1058 /// # Permissions1059 /// 1059 ///1060 /// * Collection Owner1060 /// * Collection Owner1061 /// * Collection Admin1061 /// * Collection Admin1062 /// 1062 ///1063 /// # Arguments1063 /// # Arguments1064 /// 1064 ///1065 /// * collection_id.1065 /// * collection_id.1066 /// 1066 ///1067 /// * schema: String representing the offchain data schema.1067 /// * schema: String representing the offchain data schema.1068 #[weight = <T as Config>::WeightInfo::set_variable_meta_data()]1068 #[weight = <T as Config>::WeightInfo::set_variable_meta_data()]1069 #[transactional]1069 #[transactional]1085 /// Set schema standard1085 /// Set schema standard1086 /// ImageURL1086 /// ImageURL1087 /// Unique1087 /// Unique1088 /// 1088 ///1089 /// # Permissions1089 /// # Permissions1090 /// 1090 ///1091 /// * Collection Owner1091 /// * Collection Owner1092 /// * Collection Admin1092 /// * Collection Admin1093 /// 1093 ///1094 /// # Arguments1094 /// # Arguments1095 /// 1095 ///1096 /// * collection_id.1096 /// * collection_id.1097 /// 1097 ///1098 /// * schema: SchemaVersion: enum1098 /// * schema: SchemaVersion: enum1099 #[weight = <T as Config>::WeightInfo::set_schema_version()]1099 #[weight = <T as Config>::WeightInfo::set_schema_version()]1100 #[transactional]1100 #[transactional]1113 }1113 }111411141115 /// Set off-chain data schema.1115 /// Set off-chain data schema.1116 /// 1116 ///1117 /// # Permissions1117 /// # Permissions1118 /// 1118 ///1119 /// * Collection Owner1119 /// * Collection Owner1120 /// * Collection Admin1120 /// * Collection Admin1121 /// 1121 ///1122 /// # Arguments1122 /// # Arguments1123 /// 1123 ///1124 /// * collection_id.1124 /// * collection_id.1125 /// 1125 ///1126 /// * schema: String representing the offchain data schema.1126 /// * schema: String representing the offchain data schema.1127 #[weight = <T as Config>::WeightInfo::set_offchain_schema()]1127 #[weight = <T as Config>::WeightInfo::set_offchain_schema()]1128 #[transactional]1128 #[transactional]1145 }1145 }114611461147 /// Set const on-chain data schema.1147 /// Set const on-chain data schema.1148 /// 1148 ///1149 /// # Permissions1149 /// # Permissions1150 /// 1150 ///1151 /// * Collection Owner1151 /// * Collection Owner1152 /// * Collection Admin1152 /// * Collection Admin1153 /// 1153 ///1154 /// # Arguments1154 /// # Arguments1155 /// 1155 ///1156 /// * collection_id.1156 /// * collection_id.1157 /// 1157 ///1158 /// * schema: String representing the const on-chain data schema.1158 /// * schema: String representing the const on-chain data schema.1159 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1159 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1160 #[transactional]1160 #[transactional]1177 }1177 }117811781179 /// Set variable on-chain data schema.1179 /// Set variable on-chain data schema.1180 /// 1180 ///1181 /// # Permissions1181 /// # Permissions1182 /// 1182 ///1183 /// * Collection Owner1183 /// * Collection Owner1184 /// * Collection Admin1184 /// * Collection Admin1185 /// 1185 ///1186 /// # Arguments1186 /// # Arguments1187 /// 1187 ///1188 /// * collection_id.1188 /// * collection_id.1189 /// 1189 ///1190 /// * schema: String representing the variable on-chain data schema.1190 /// * schema: String representing the variable on-chain data schema.1191 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1191 #[weight = <T as Config>::WeightInfo::set_const_on_chain_schema()]1192 #[transactional]1192 #[transactional]1232 ) -> DispatchResult {1232 ) -> DispatchResult {1233 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1233 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1234 let mut target_collection = Self::get_collection(collection_id)?;1234 let mut target_collection = Self::get_collection(collection_id)?;1235 Self::check_owner_permissions(&target_collection, &sender.as_sub())?;1235 Self::check_owner_permissions(&target_collection, sender.as_sub())?;1236 let old_limits = &target_collection.limits;1236 let old_limits = &target_collection.limits;1237 let chain_limits = ChainLimit::get();1237 let chain_limits = ChainLimit::get();123812381267 owner: &T::CrossAccountId,1268 data: CreateItemData,1269 ) -> DispatchResult {1265 Self::can_create_items_in_collection(&collection, &sender, &owner, 1)?;1270 Self::can_create_items_in_collection(collection, sender, owner, 1)?;1266 Self::validate_create_item_args(&collection, &data)?;1271 Self::validate_create_item_args(collection, &data)?;1267 Self::create_item_no_validation(&collection, owner, data)?;1272 Self::create_item_no_validation(collection, owner, data)?;126812731269 Ok(())1274 Ok(())1270 }1275 }127112761272 pub fn transfer_internal(sender: &T::CrossAccountId, recipient: &T::CrossAccountId, target_collection: &CollectionHandle<T>, item_id: TokenId, value: u128) -> DispatchResult {1277 pub fn transfer_internal(1278 sender: &T::CrossAccountId,1279 recipient: &T::CrossAccountId,1280 target_collection: &CollectionHandle<T>,1281 item_id: TokenId,1282 value: u128,1283 ) -> DispatchResult {1273 target_collection.consume_gas(2000000)?;1284 target_collection.consume_gas(2000000)?;1274 // Limits check1285 // Limits check1275 Self::is_correct_transfer(target_collection, &recipient)?;1286 Self::is_correct_transfer(target_collection, recipient)?;127612871277 // Transfer permissions check1288 // Transfer permissions check1278 ensure!(Self::is_item_owner(&sender, target_collection, item_id) ||1289 ensure!(1290 Self::is_item_owner(sender, target_collection, item_id)1279 Self::is_owner_or_admin_permissions(target_collection, &sender),1291 || Self::is_owner_or_admin_permissions(target_collection, sender),1280 Error::<T>::NoPermission);1292 Error::<T>::NoPermission1293 );128112941282 if target_collection.access == AccessMode::WhiteList {1295 if target_collection.access == AccessMode::WhiteList {1283 Self::check_white_list(target_collection, &sender)?;1296 Self::check_white_list(target_collection, sender)?;1284 Self::check_white_list(target_collection, &recipient)?;1297 Self::check_white_list(target_collection, recipient)?;1285 }1298 }128612991287 match target_collection.mode1300 match target_collection.mode {1288 {1289 CollectionMode::NFT => Self::transfer_nft(target_collection, item_id, sender.clone(), recipient.clone())?,1301 CollectionMode::NFT => Self::transfer_nft(1302 target_collection,1303 item_id,1304 sender.clone(),1305 recipient.clone(),1306 )?,1290 CollectionMode::Fungible(_) => Self::transfer_fungible(target_collection, value, &sender, &recipient)?,1307 CollectionMode::Fungible(_) => {1308 Self::transfer_fungible(target_collection, value, sender, recipient)?1309 }1291 CollectionMode::ReFungible => Self::transfer_refungible(target_collection, item_id, value, sender.clone(), recipient.clone())?,1310 CollectionMode::ReFungible => Self::transfer_refungible(1311 target_collection,1312 item_id,1313 value,1314 sender.clone(),1315 recipient.clone(),1316 )?,1292 _ => ()1317 _ => (),1293 };1318 };129413191295 Self::deposit_event(RawEvent::Transfer(target_collection.id, item_id, sender.clone(), recipient.clone(), value));1320 Self::deposit_event(RawEvent::Transfer(1305 amount: u1281336 amount: u128,1306 ) -> DispatchResult {1337 ) -> DispatchResult {1307 collection.consume_gas(2000000)?;1338 collection.consume_gas(2000000)?;1308 Self::token_exists(&collection, item_id)?;1339 Self::token_exists(collection, item_id)?;130913401310 // Transfer permissions check1341 // Transfer permissions check1311 let bypasses_limits = collection.limits.owner_can_transfer &&1342 let bypasses_limits = collection.limits.owner_can_transfer1312 Self::is_owner_or_admin_permissions(1343 && Self::is_owner_or_admin_permissions(collection, sender);1313 &collection,1314 &sender,1315 );131613441317 let allowance_limit = if bypasses_limits {1345 let allowance_limit = if bypasses_limits {1318 None1346 None1319 } else if let Some(amount) = Self::owned_amount(1347 } else if let Some(amount) = Self::owned_amount(sender, collection, item_id) {1320 &sender,1321 &collection,1322 item_id,1323 ) {1324 Some(amount)1348 Some(amount)1325 } else {1349 } else {1326 fail!(Error::<T>::NoPermission);1350 fail!(Error::<T>::NoPermission);1327 };1351 };132813521329 if collection.access == AccessMode::WhiteList {1353 if collection.access == AccessMode::WhiteList {1330 Self::check_white_list(&collection, &sender)?;1354 Self::check_white_list(collection, sender)?;1331 Self::check_white_list(&collection, &spender)?;1355 Self::check_white_list(collection, spender)?;1332 }1356 }133313571334 let allowance: u128 = amount1358 let allowance: u128 = amount1353 collection.log(ERC20Events::Approval {1384 collection.log(ERC20Events::Approval {1354 owner: *sender.as_eth(),1385 owner: *sender.as_eth(),1355 spender: *spender.as_eth(),1386 spender: *spender.as_eth(),1356 value: allowance.into()1387 value: allowance.into(),1357 });1388 });1358 }1389 }135913901412 <Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));137514131376 // Limits check1414 // Limits check1377 Self::is_correct_transfer(&collection, &recipient)?;1415 Self::is_correct_transfer(collection, recipient)?;137814161379 // Transfer permissions check1417 // Transfer permissions check1380 ensure!(1418 ensure!(1381 approval >= amount || 1419 approval >= amount1382 (1420 || (collection.limits.owner_can_transfer1383 collection.limits.owner_can_transfer &&1421 && Self::is_owner_or_admin_permissions(collection, sender)),1384 Self::is_owner_or_admin_permissions(&collection, &sender)1385 ),1386 Error::<T>::NoPermission1422 Error::<T>::NoPermission1387 );1423 );138814241389 if collection.access == AccessMode::WhiteList {1425 if collection.access == AccessMode::WhiteList {1390 Self::check_white_list(&collection, &sender)?;1426 Self::check_white_list(collection, sender)?;1391 Self::check_white_list(&collection, &recipient)?;1427 Self::check_white_list(collection, recipient)?;1392 }1428 }139314291394 // Reduce approval by transferred amount or remove if remaining approval drops to 01430 // Reduce approval by transferred amount or remove if remaining approval drops to 0140114411402 match collection.mode {1442 match collection.mode {1403 CollectionMode::NFT => {1443 CollectionMode::NFT => {1404 Self::transfer_nft(&collection, item_id, from.clone(), recipient.clone())?1444 Self::transfer_nft(collection, item_id, from.clone(), recipient.clone())?1405 }1445 }1406 CollectionMode::Fungible(_) => {1446 CollectionMode::Fungible(_) => {1407 Self::transfer_fungible(&collection, amount, &from, &recipient)?1447 Self::transfer_fungible(collection, amount, from, recipient)?1408 }1448 }1409 CollectionMode::ReFungible => {1449 CollectionMode::ReFungible => Self::transfer_refungible(1410 Self::transfer_refungible(&collection, item_id, amount, from.clone(), recipient.clone())?1450 collection,1411 }1451 item_id,1452 amount,1453 from.clone(),1454 recipient.clone(),1455 )?,1412 _ => ()1456 _ => (),1413 };1457 };141414581415 if matches!(collection.mode, CollectionMode::Fungible(_)) {1459 if matches!(collection.mode, CollectionMode::Fungible(_)) {1416 collection.log(ERC20Events::Approval {1460 collection.log(ERC20Events::Approval {1417 owner: *from.as_eth(),1461 owner: *from.as_eth(),1418 spender: *sender.as_eth(),1462 spender: *sender.as_eth(),1419 value: allowance.into()1463 value: allowance.into(),1420 });1464 });1421 }1465 }142214661429 item_id: TokenId,1473 item_id: TokenId,1430 data: Vec<u8>,1474 data: Vec<u8>,1431 ) -> DispatchResult {1475 ) -> DispatchResult {1432 Self::token_exists(&collection, item_id)?;1476 Self::token_exists(collection, item_id)?;143314771434 ensure!(ChainLimit::get().custom_data_limit >= data.len() as u32, Error::<T>::TokenVariableDataLimitExceeded);1478 ensure!(1479 ChainLimit::get().custom_data_limit >= data.len() as u32,1480 Error::<T>::TokenVariableDataLimitExceeded1481 );143514821436 // Modify permissions check1483 // Modify permissions check1437 ensure!(Self::is_item_owner(&sender, &collection, item_id) ||1484 ensure!(1485 Self::is_item_owner(sender, collection, item_id)1438 Self::is_owner_or_admin_permissions(&collection, &sender),1486 || Self::is_owner_or_admin_permissions(collection, sender),1439 Error::<T>::NoPermission);1487 Error::<T>::NoPermission1488 );144014891441 match collection.mode1490 match collection.mode {1442 {1443 CollectionMode::NFT => Self::set_nft_variable_data(&collection, item_id, data)?,1491 CollectionMode::NFT => Self::set_nft_variable_data(collection, item_id, data)?,1444 CollectionMode::ReFungible => Self::set_re_fungible_variable_data(&collection, item_id, data)?,1492 CollectionMode::ReFungible => {1493 Self::set_re_fungible_variable_data(collection, item_id, data)?1494 }1445 CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),1495 CollectionMode::Fungible(_) => fail!(Error::<T>::CantStoreMetadataInFungibleTokens),1446 _ => fail!(Error::<T>::UnexpectedCollectionType)1496 _ => fail!(Error::<T>::UnexpectedCollectionType),1447 };1497 };144814981449 Ok(())1499 Ok(())1455 owner: &T::CrossAccountId,1505 owner: &T::CrossAccountId,1456 items_data: Vec<CreateItemData>,1506 items_data: Vec<CreateItemData>,1457 ) -> DispatchResult {1507 ) -> DispatchResult {1458 Self::can_create_items_in_collection(&collection, &sender, &owner, items_data.len() as u32)?;1508 Self::can_create_items_in_collection(collection, sender, owner, items_data.len() as u32)?;145915091460 for data in &items_data {1510 for data in &items_data {1461 Self::validate_create_item_args(&collection, data)?;1511 Self::validate_create_item_args(collection, data)?;1462 }1512 }1463 for data in &items_data {1513 for data in &items_data {1464 Self::create_item_no_validation(&collection, owner, data.clone())?;1514 Self::create_item_no_validation(collection, owner, data.clone())?;1465 }1515 }146615161467 Ok(())1517 Ok(())1474 value: u128,1524 value: u128,1475 ) -> DispatchResult {1525 ) -> DispatchResult {1476 ensure!(1526 ensure!(1477 Self::is_item_owner(&sender, &collection, item_id) ||1527 Self::is_item_owner(sender, collection, item_id)1478 (1528 || (collection.limits.owner_can_transfer1479 collection.limits.owner_can_transfer &&1529 && Self::is_owner_or_admin_permissions(collection, sender)),1480 Self::is_owner_or_admin_permissions(&collection, &sender)1481 ),1482 Error::<T>::NoPermission1530 Error::<T>::NoPermission1483 );1531 );148415321485 if collection.access == AccessMode::WhiteList {1533 if collection.access == AccessMode::WhiteList {1486 Self::check_white_list(&collection, &sender)?;1534 Self::check_white_list(collection, sender)?;1487 }1535 }148815361489 match collection.mode1537 match collection.mode {1490 {1491 CollectionMode::NFT => Self::burn_nft_item(&collection, item_id)?,1538 CollectionMode::NFT => Self::burn_nft_item(collection, item_id)?,1492 CollectionMode::Fungible(_) => Self::burn_fungible_item(&sender, &collection, value)?,1539 CollectionMode::Fungible(_) => Self::burn_fungible_item(sender, collection, value)?,1493 CollectionMode::ReFungible => Self::burn_refungible_item(&collection, item_id, &sender)?,1540 CollectionMode::ReFungible => Self::burn_refungible_item(collection, item_id, sender)?,1494 _ => ()1541 _ => (),1495 };1542 };149615431497 Ok(())1544 Ok(())1503 address: &T::CrossAccountId,1550 address: &T::CrossAccountId,1504 whitelisted: bool,1551 whitelisted: bool,1505 ) -> DispatchResult {1552 ) -> DispatchResult {1506 Self::check_owner_or_admin_permissions(&collection, &sender)?;1553 Self::check_owner_or_admin_permissions(collection, sender)?;150715541508 if whitelisted {1555 if whitelisted {1509 <WhiteList<T>>::insert(collection.id, address.as_sub(), true);1556 <WhiteList<T>>::insert(collection.id, address.as_sub(), true);1603 Error::<T>::AccountTokenLimitExceeded1604 );153916051540 if !Self::is_owner_or_admin_permissions(collection, &sender) {1606 if !Self::is_owner_or_admin_permissions(collection, sender) {1541 ensure!(collection.mint_mode == true, Error::<T>::PublicMintingNotAllowed);1607 ensure!(collection.mint_mode, Error::<T>::PublicMintingNotAllowed);1542 Self::check_white_list(collection, owner)?;1608 Self::check_white_list(collection, owner)?;1543 Self::check_white_list(collection, sender)?;1609 Self::check_white_list(collection, sender)?;1544 }1610 }1557 } else {1631 } else {1558 fail!(Error::<T>::NotNftDataUsedToMintNftCollectionToken);1632 fail!(Error::<T>::NotNftDataUsedToMintNftCollectionToken);1559 }1633 }1560 },1634 }1561 CollectionMode::Fungible(_) => {1635 CollectionMode::Fungible(_) => {1562 if let CreateItemData::Fungible(_) = data {1636 if let CreateItemData::Fungible(_) = data {1563 } else {1637 } else {1564 fail!(Error::<T>::NotFungibleDataUsedToMintFungibleCollectionToken);1638 fail!(Error::<T>::NotFungibleDataUsedToMintFungibleCollectionToken);1565 }1639 }1566 },1640 }1567 CollectionMode::ReFungible => {1641 CollectionMode::ReFungible => {1568 if let CreateItemData::ReFungible(data) = data {1642 if let CreateItemData::ReFungible(data) = data {15691577 } else {1659 } else {1578 fail!(Error::<T>::NotReFungibleDataUsedToMintReFungibleCollectionToken);1660 fail!(Error::<T>::NotReFungibleDataUsedToMintReFungibleCollectionToken);1579 }1661 }1580 },1662 }1581 _ => { fail!(Error::<T>::UnexpectedCollectionType); }1663 _ => {1664 fail!(Error::<T>::UnexpectedCollectionType);1665 }1591 let item = NftItemType {1678 let item = NftItemType {1592 owner: owner.clone(),1679 owner: owner.clone(),1593 const_data: data.const_data,1680 const_data: data.const_data,1594 variable_data: data.variable_data1681 variable_data: data.variable_data,1595 };1682 };159616831597 Self::add_nft_item(collection, item)?;1684 Self::add_nft_item(collection, item)?;1598 },1685 }1599 CreateItemData::Fungible(data) => {1686 CreateItemData::Fungible(data) => {1600 Self::add_fungible_item(collection, &owner, data.value)?;1687 Self::add_fungible_item(collection, owner, data.value)?;1601 },1688 }1602 CreateItemData::ReFungible(data) => {1689 CreateItemData::ReFungible(data) => {1603 let mut owner_list = Vec::new();1604 owner_list.push(Ownership {owner: owner.clone(), fraction: data.pieces});1690 let owner_list = vec![Ownership {1691 owner: owner.clone(),1692 fraction: data.pieces,1693 }];160516941606 let item = ReFungibleItemType {1695 let item = ReFungibleItemType {1607 owner: owner_list,1696 owner: owner_list,1608 const_data: data.const_data,1697 const_data: data.const_data,1609 variable_data: data.variable_data1698 variable_data: data.variable_data,1610 };1699 };161117001612 Self::add_refungible_item(collection, item)?;1701 Self::add_refungible_item(collection, item)?;1622 // Does new owner already have an account?1715 // Does new owner already have an account?1623 let balance: u128 = <FungibleItemList<T>>::get(collection_id, owner.as_sub()).value;1716 let balance: u128 = <FungibleItemList<T>>::get(collection_id, owner.as_sub()).value;162417171625 // Mint 1718 // Mint1626 let item = FungibleItemType {1719 let item = FungibleItemType {1627 value: balance.checked_add(value).ok_or(Error::<T>::NumOverflow)?,1720 value: balance.checked_add(value).ok_or(Error::<T>::NumOverflow)?,1628 };1721 };179919021800 pub fn submit_logs(collection: CollectionHandle<T>) -> DispatchResult {1903 pub fn submit_logs(collection: CollectionHandle<T>) -> DispatchResult {1801 if collection.logs.is_empty() {1904 if collection.logs.is_empty() {1802 return Ok(())1905 return Ok(());1803 }1906 }1804 T::EthereumTransactionSender::submit_logs_transaction(1907 T::EthereumTransactionSender::submit_logs_transaction(1805 eth::generate_transaction(collection.id, T::EthereumChainId::get()),1908 eth::generate_transaction(collection.id, T::EthereumChainId::get()),1926 collection: &CollectionHandle<T>,1927 subject: &T::CrossAccountId,1928 ) -> bool {1820 *subject.as_sub() == collection.owner || <AdminList<T>>::get(collection.id).contains(&subject)1929 *subject.as_sub() == collection.owner1930 || <AdminList<T>>::get(collection.id).contains(subject)1821 }1931 }182219321837 let collection_id = target_collection.id;1950 let collection_id = target_collection.id;183819511839 match target_collection.mode {1952 match target_collection.mode {1840 CollectionMode::NFT => (<NftItemList<T>>::get(collection_id, item_id)?.owner == *subject)1953 CollectionMode::NFT => {1841 .then(|| 1),1954 (<NftItemList<T>>::get(collection_id, item_id)?.owner == *subject).then(|| 1)1955 }1842 CollectionMode::Fungible(_) => Some(<FungibleItemList<T>>::get(collection_id, &subject.as_sub())1956 CollectionMode::Fungible(_) => {1843 .value),1957 Some(<FungibleItemList<T>>::get(collection_id, &subject.as_sub()).value)1958 }1844 CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id)?1959 CollectionMode::ReFungible => <ReFungibleItemList<T>>::get(collection_id, item_id)?1845 .owner1960 .owner1846 .iter()1961 .iter()1972 ) -> bool {1854 match target_collection.mode {1973 match target_collection.mode {1855 CollectionMode::Fungible(_) => true,1974 CollectionMode::Fungible(_) => true,1856 _ => Self::owned_amount(&subject, target_collection, item_id).is_some(),1975 _ => Self::owned_amount(subject, target_collection, item_id).is_some(),1857 }1976 }1858 }1977 }185919781866 Ok(())1991 Ok(())1867 }1992 }186819931869 /// Check if token exists. In case of Fungible, check if there is an entry for 1994 /// Check if token exists. In case of Fungible, check if there is an entry for1870 /// the owner in fungible balances double map1995 /// the owner in fungible balances double map1871 fn token_exists(1996 fn token_exists(target_collection: &CollectionHandle<T>, item_id: TokenId) -> DispatchResult {1872 target_collection: &CollectionHandle<T>,1873 item_id: TokenId,1874 ) -> DispatchResult {1875 let collection_id = target_collection.id;1997 let collection_id = target_collection.id;1876 let exists = match target_collection.mode1998 let exists = match target_collection.mode {1877 {1878 CollectionMode::NFT => <NftItemList<T>>::contains_key(collection_id, item_id),1999 CollectionMode::NFT => <NftItemList<T>>::contains_key(collection_id, item_id),1879 CollectionMode::Fungible(_) => true,2000 CollectionMode::Fungible(_) => true,1880 CollectionMode::ReFungible => <ReFungibleItemList<T>>::contains_key(collection_id, item_id),2001 CollectionMode::ReFungible => {2002 <ReFungibleItemList<T>>::contains_key(collection_id, item_id)2003 }1881 _ => false2004 _ => false,1882 };2005 };188320061884 ensure!(exists == true, Error::<T>::TokenNotFound);2007 ensure!(exists, Error::<T>::TokenNotFound);1885 Ok(())2008 Ok(())1886 }2009 }188720101935 let item = full_item2063 let item = full_item1936 .owner2064 .owner1937 .iter()2065 .iter()1938 .filter(|i| i.owner == owner)2066 .find(|i| i.owner == owner)1939 .next()1940 .ok_or(Error::<T>::TokenNotFound)?;2067 .ok_or(Error::<T>::TokenNotFound)?;1941 let amount = item.fraction;2068 let amount = item.fraction;194220691956 let old_owner = item.owner.clone();2083 let old_owner = item.owner.clone();1957 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);2084 let new_owner_has_account = full_item.owner.iter().any(|i| i.owner == new_owner);195820852086 let mut new_full_item = full_item.clone();1959 // transfer2087 // transfer1960 if amount == value && !new_owner_has_account {2088 if amount == value && !new_owner_has_account {1961 // change owner2089 // change owner1962 // new owner do not have account2090 // new owner do not have account1963 let mut new_full_item = full_item.clone();1964 new_full_item2091 new_full_item1965 .owner2092 .owner1966 .iter_mut()2093 .iter_mut()1972 // update index collection2099 // update index collection1973 Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;2100 Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;1974 } else {2101 } else {1975 let mut new_full_item = full_item.clone();1976 new_full_item2102 new_full_item1977 .owner2103 .owner1978 .iter_mut()2104 .iter_mut()2186 let item_contains = list.contains(&item_index.clone());2326 let item_contains = list.contains(&item_index.clone());218723272188 if !item_contains {2328 if !item_contains {2189 list.push(item_index.clone());2329 list.push(item_index);2190 }2330 }219123312192 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), list);2332 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), list);2193 } else {2333 } else {2194 let mut itm = Vec::new();2334 let itm = vec![item_index];2195 itm.push(item_index.clone());2196 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), itm);2335 <AddressTokens<T>>::insert(collection_id, owner.as_sub(), itm);2197 }2336 }21982337pallets/nft/src/mock.rsdiffbeforeafterboth1#![allow(clippy::from_over_into)]21use crate as pallet_template;3use crate as pallet_template;2use sp_core::H256;4use sp_core::H256;3use frame_support::{ 5use frame_support::{parameter_types, weights::IdentityFee};4 parameter_types,5 weights::IdentityFee,6};7use sp_runtime::{6use sp_runtime::{8 traits::{BlakeTwo256, IdentityLookup}, 7 traits::{BlakeTwo256, IdentityLookup},11};10};12use pallet_transaction_payment::{ CurrencyAdapter};11use pallet_transaction_payment::{CurrencyAdapter};13use frame_system as system;12use frame_system as system;13use pallet_evm::AddressMapping;14use crate::{EvmBackwardsAddressMapping, CrossAccountId};15use codec::{Encode, Decode};141615type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;17type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;16type Block = frame_system::mocking::MockBlock<Test>; 18type Block = frame_system::mocking::MockBlock<Test>;22 NodeBlock = Block,24 NodeBlock = Block,23 UncheckedExtrinsic = UncheckedExtrinsic,25 UncheckedExtrinsic = UncheckedExtrinsic,24 {26 {25 System: frame_system::{Module, Call, Config, Storage, Event<T>},27 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},26 TemplateModule: pallet_template::{Module, Call, Storage},28 TemplateModule: pallet_template::{Pallet, Call, Storage},27 Balances: pallet_balances::{Module, Call, Storage},29 Balances: pallet_balances::{Pallet, Call, Storage},28 }30 }29);31);303256 type OnKilledAccount = ();58 type OnKilledAccount = ();57 type SystemWeightInfo = ();59 type SystemWeightInfo = ();58 type SS58Prefix = SS58Prefix;60 type SS58Prefix = SS58Prefix;61 type OnSetCode = ();59}62}606361parameter_types! {64parameter_types! {78}81}798280impl pallet_transaction_payment::Config for Test {83impl pallet_transaction_payment::Config for Test {81 type OnChargeTransaction = CurrencyAdapter<pallet_balances::Module<Test>, ()>;84 type OnChargeTransaction = CurrencyAdapter<pallet_balances::Pallet<Test>, ()>;82 type TransactionByteFee = TransactionByteFee;85 type TransactionByteFee = TransactionByteFee;83 type WeightToFee = IdentityFee<u64>;86 type WeightToFee = IdentityFee<u64>;84 type FeeMultiplierUpdate = ();87 type FeeMultiplierUpdate = ();94 type WeightInfo = ();97 type WeightInfo = ();95}98}969997type Timestamp = pallet_timestamp::Module<Test>;100type Timestamp = pallet_timestamp::Pallet<Test>;98type Randomness = pallet_randomness_collective_flip::Module<Test>;101type Randomness = pallet_randomness_collective_flip::Pallet<Test>;99102100parameter_types! {103parameter_types! {101 pub const TombstoneDeposit: u64 = 1;104 pub const TombstoneDeposit: u64 = 1;102 pub const DepositPerContract: u64 = 1;105 pub const DepositPerContract: u64 = 1;103 pub const DepositPerStorageByte: u64 = 1;106 pub const DepositPerStorageByte: u64 = 1;104 pub const DepositPerStorageItem: u64 = 1;107 pub const DepositPerStorageItem: u64 = 1;105 pub RentFraction: Perbill = Perbill::from_rational_approximation(1u32, 30 * 24 * 60 * 10);108 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * 24 * 60 * 10);106 pub const SurchargeReward: u64 = 1;109 pub const SurchargeReward: u64 = 1;107 pub const SignedClaimHandicap: u32 = 2;110 pub const SignedClaimHandicap: u32 = 2;108 pub const MaxDepth: u32 = 32;109 pub const MaxValueSize: u32 = 16 * 1024;110 pub DeletionWeightLimit: u64 = u64::MAX;//Perbill::from_percent(10);111 pub DeletionWeightLimit: u64 = u64::MAX;//Perbill::from_percent(10);111 pub DeletionQueueDepth: u32 = 10;112 pub DeletionQueueDepth: u32 = 10;113 pub Schedule: pallet_contracts::Schedule<Test> = Default::default();112}114}113115114impl pallet_contracts::Config for Test {116impl pallet_contracts::Config for Test {115 type Time = Timestamp;117 type Time = Timestamp;116 type Randomness = Randomness;118 type Randomness = Randomness;117 type Currency = pallet_balances::Module<Test>;119 type Currency = pallet_balances::Pallet<Test>;118 type Event = ();120 type Event = ();119 type RentPayment = ();121 type RentPayment = ();120 type SignedClaimHandicap = SignedClaimHandicap;122 type SignedClaimHandicap = SignedClaimHandicap;125 type RentFraction = RentFraction;127 type RentFraction = RentFraction;126 type SurchargeReward = SurchargeReward;128 type SurchargeReward = SurchargeReward;127 type DeletionWeightLimit = DeletionWeightLimit;129 type DeletionWeightLimit = DeletionWeightLimit;128 type MaxDepth = MaxDepth;129 type DeletionQueueDepth = DeletionQueueDepth;130 type DeletionQueueDepth = DeletionQueueDepth;130 type MaxValueSize = MaxValueSize;131 type ChainExtension = ();131 type ChainExtension = ();132 type MaxCodeSize = ();133 type WeightPrice = ();132 type WeightPrice = ();134 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;133 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;134 type Schedule = Schedule;135 type CallStack = [pallet_contracts::Frame<Self>; 31];135}136}136137137parameter_types! {138parameter_types! {138 pub const CollectionCreationPrice: u32 = 0;139 pub const CollectionCreationPrice: u32 = 0;139 pub TreasuryAccountId: u64 = 1234;140 pub TreasuryAccountId: u64 = 1234;141 pub EthereumChainId: u32 = 1111;140}142}143144pub struct TestEvmAddressMapping;145impl AddressMapping<u64> for TestEvmAddressMapping {146 fn into_account_id(_addr: sp_core::H160) -> u64 {147 unimplemented!()148 }149}150151pub struct TestEvmBackwardsAddressMapping;152impl EvmBackwardsAddressMapping<u64> for TestEvmBackwardsAddressMapping {153 fn from_account_id(_account_id: u64) -> sp_core::H160 {154 unimplemented!()155 }156}157158#[derive(Encode, Decode, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]159pub struct TestCrossAccountId(u64, sp_core::H160);160impl CrossAccountId<u64> for TestCrossAccountId {161 fn from_sub(sub: u64) -> Self {162 let mut eth = [0; 20];163 eth[12..20].copy_from_slice(&sub.to_be_bytes());164 Self(sub, sp_core::H160(eth))165 }166 fn as_sub(&self) -> &u64 {167 &self.0168 }169 fn from_eth(_eth: sp_core::H160) -> Self {170 unimplemented!()171 }172 fn as_eth(&self) -> &sp_core::H160 {173 &self.1174 }175}176177pub struct TestEtheremTransactionSender;178impl pallet_ethereum::EthereumTransactionSender for TestEtheremTransactionSender {179 fn submit_logs_transaction(180 _tx: pallet_ethereum::Transaction,181 _logs: Vec<pallet_ethereum::Log>,182 ) -> Result<(), sp_runtime::DispatchError> {183 Ok(())184 }185}141186142impl pallet_template::Config for Test {187impl pallet_template::Config for Test {143 type Event = ();188 type Event = ();144 type WeightInfo = ();189 type WeightInfo = ();145 type CollectionCreationPrice = CollectionCreationPrice;190 type CollectionCreationPrice = CollectionCreationPrice;146 type Currency = pallet_balances::Module<Test>;191 type Currency = pallet_balances::Pallet<Test>;147 type TreasuryAccountId = TreasuryAccountId;192 type TreasuryAccountId = TreasuryAccountId;193 type EvmAddressMapping = TestEvmAddressMapping;194 type EvmBackwardsAddressMapping = TestEvmBackwardsAddressMapping;195 type CrossAccountId = TestCrossAccountId;196 type EthereumChainId = EthereumChainId;197 type EthereumTransactionSender = TestEtheremTransactionSender;148}198}149199150// Build genesis storage according to the mock runtime.200// Build genesis storage according to the mock runtime.pallets/nft/src/sponsorship.rsdiffbeforeafterboth1use crate::{Config, Call, CollectionById, CreateItemBasket, VariableMetaDataBasket, ReFungibleTransferBasket, FungibleTransferBasket, NftTransferBasket, ChainLimit, CreateItemData, CollectionMode};1use crate::{2 Config, Call, CollectionById, CreateItemBasket, VariableMetaDataBasket,3 ReFungibleTransferBasket, FungibleTransferBasket, NftTransferBasket, ChainLimit,4 CreateItemData, CollectionMode,5};2use core::marker::PhantomData;6use core::marker::PhantomData;3use up_sponsorship::SponsorshipHandler;7use up_sponsorship::SponsorshipHandler;4use frame_support::{8use frame_support::{5 traits::IsSubType,9 traits::IsSubType,6 storage::{StorageMap, StorageDoubleMap, StorageValue},10 storage::{StorageMap, StorageDoubleMap, StorageValue},7};11};8use nft_data_structs::{TokenId, CollectionId};12use nft_data_structs::{TokenId, CollectionId};9use alloc::vec::Vec;101311pub struct NftSponsorshipHandler<T>(PhantomData<T>);14pub struct NftSponsorshipHandler<T>(PhantomData<T>);12impl<T: Config> NftSponsorshipHandler<T> {15impl<T: Config> NftSponsorshipHandler<T> {32 CreateItemBasket::<T>::insert((collection_id, who.clone()), block_number);34 CreateItemBasket::<T>::insert((collection_id, who.clone()), block_number);333534 // check free create limit36 // check free create limit35 if collection.limits.sponsored_data_size >= (_properties.len() as u32) {37 if collection.limits.sponsored_data_size >= (_properties.data_size() as u32) {36 collection.sponsorship.sponsor()38 collection.sponsorship.sponsor().cloned()37 .cloned()38 } else {39 } else {128125129 sponsored126 sponsored130 }127 }131 _ => {128 _ => false,132 false133 },134 };129 };135 }130 }136131145 pub fn withdraw_set_variable_meta_data(139 pub fn withdraw_set_variable_meta_data(146 collection_id: &CollectionId,140 collection_id: &CollectionId,147 item_id: &TokenId,141 item_id: &TokenId,148 data: &Vec<u8>,142 data: &[u8],149 ) -> Option<T::AccountId> {143 ) -> Option<T::AccountId> {150151 let mut sponsor_metadata_changes = false;144 let mut sponsor_metadata_changes = false;184impl<T, C> SponsorshipHandler<T::AccountId, C> for NftSponsorshipHandler<T>175impl<T, C> SponsorshipHandler<T::AccountId, C> for NftSponsorshipHandler<T>185where 176where186 T: Config,177 T: Config,187 C: IsSubType<Call<T>>178 C: IsSubType<Call<T>>,188{179{189 fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {180 fn get_sponsor(who: &T::AccountId, call: &C) -> Option<T::AccountId> {190 match IsSubType::<Call<T>>::is_sub_type(call)? {181 match IsSubType::<Call<T>>::is_sub_type(call)? {191 Call::create_item(collection_id, _owner, _properties) => {182 Call::create_item(collection_id, _owner, properties) => {192 Self::withdraw_create_item(who, collection_id, &_properties)183 Self::withdraw_create_item(who, collection_id, properties)193 },184 }194 Call::transfer(_new_owner, collection_id, item_id, _value) => {185 Call::transfer(_new_owner, collection_id, item_id, _value) => {195 Self::withdraw_transfer(who, collection_id, item_id)186 Self::withdraw_transfer(who, collection_id, item_id)196 },187 }197 Call::set_variable_meta_data(collection_id, item_id, data) => {188 Call::set_variable_meta_data(collection_id, item_id, data) => {198 Self::withdraw_set_variable_meta_data(collection_id, item_id, &data)189 Self::withdraw_set_variable_meta_data(collection_id, item_id, data)199 },190 }200 _ => None,191 _ => None,201 }192 }202 }193 }pallets/nft/src/tests.rsdiffbeforeafterboth1// Tests to be written here1// Tests to be written here2use super::*;2use super::*;3use crate::mock::*;3use crate::mock::*;4use crate::{AccessMode, CollectionMode,4use crate::{AccessMode, CollectionMode, Ownership, ChainLimits, CreateItemData};5 Ownership, ChainLimits, CreateItemData, CreateNftData, CreateFungibleData, CreateReFungibleData,5use nft_data_structs::{6 CollectionId, TokenId, MAX_DECIMAL_POINTS};6 CreateNftData, CreateFungibleData, CreateReFungibleData, CollectionId, TokenId,7 MAX_DECIMAL_POINTS,8};7use frame_support::{assert_noop, assert_ok};9use frame_support::{assert_noop, assert_ok};8use frame_system::{ RawOrigin };10use frame_system::{RawOrigin};91110fn default_collection_numbers_limit() -> u32 {12fn default_collection_numbers_limit() -> u32 {11 1013 1012}14}131514fn default_limits() {16fn default_limits() {15 assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits {17 assert_ok!(TemplateModule::set_chain_limits(18 RawOrigin::Root.into(),19 ChainLimits {16 collection_numbers_limit: default_collection_numbers_limit(),20 collection_numbers_limit: default_collection_numbers_limit(),17 account_token_ownership_limit: 10,21 account_token_ownership_limit: 10,18 collections_admins_limit: 5,22 collections_admins_limit: 5,19 custom_data_limit: 2048,23 custom_data_limit: 2048,20 nft_sponsor_transfer_timeout: 15,24 nft_sponsor_transfer_timeout: 15,21 fungible_sponsor_transfer_timeout: 15,25 fungible_sponsor_transfer_timeout: 15,22 refungible_sponsor_transfer_timeout: 15,26 refungible_sponsor_transfer_timeout: 15,23 const_on_chain_schema_limit: 1024,27 const_on_chain_schema_limit: 1024,24 offchain_schema_limit: 1024,28 offchain_schema_limit: 1024,25 variable_on_chain_schema_limit: 1024,29 variable_on_chain_schema_limit: 1024,26 }));30 }31 ));27}32}283329fn default_nft_data() -> CreateNftData {34fn default_nft_data() -> CreateNftData {30 CreateNftData { const_data: vec![1, 2, 3], variable_data: vec![3, 2, 1] }35 CreateNftData {36 const_data: vec![1, 2, 3],37 variable_data: vec![3, 2, 1],38 }31}39}324033fn default_fungible_data () -> CreateFungibleData {41fn default_fungible_data() -> CreateFungibleData {34 CreateFungibleData { value: 5 }42 CreateFungibleData { value: 5 }35}43}364437fn default_re_fungible_data () -> CreateReFungibleData {45fn default_re_fungible_data() -> CreateReFungibleData {38 CreateReFungibleData { const_data: vec![1, 2, 3], variable_data: vec![3, 2, 1], pieces: 1023 }46 CreateReFungibleData {47 const_data: vec![1, 2, 3],48 variable_data: vec![3, 2, 1],49 pieces: 1023,50 }39}51}405241fn create_test_collection_for_owner(mode: &CollectionMode, owner: u64, id: CollectionId) -> CollectionId {53fn create_test_collection_for_owner(54 mode: &CollectionMode,55 owner: u64,56 id: CollectionId,57) -> CollectionId {42 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();58 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();43 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();59 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();44 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();60 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();456146 let origin1 = Origin::signed(owner);62 let origin1 = Origin::signed(owner);47 assert_ok!(TemplateModule::create_collection(63 assert_ok!(TemplateModule::create_collection(48 origin1.clone(),64 origin1,49 col_name1.clone(),65 col_name1,50 col_desc1.clone(),66 col_desc1,51 token_prefix1.clone(),67 token_prefix1,52 mode.clone()68 mode.clone()53 ));69 ));547055 let saved_col_name: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();71 let saved_col_name: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();56 let saved_description: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();72 let saved_description: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();57 let saved_prefix: Vec<u8> = b"token_prefix1\0".to_vec();73 let saved_prefix: Vec<u8> = b"token_prefix1\0".to_vec();58 assert_eq!(TemplateModule::collection_id(id).unwrap().owner, owner);74 assert_eq!(TemplateModule::collection_id(id).unwrap().owner, owner);59 assert_eq!(TemplateModule::collection_id(id).unwrap().name, saved_col_name);75 assert_eq!(76 TemplateModule::collection_id(id).unwrap().name,77 saved_col_name78 );60 assert_eq!(TemplateModule::collection_id(id).unwrap().mode, *mode);79 assert_eq!(TemplateModule::collection_id(id).unwrap().mode, *mode);61 assert_eq!(TemplateModule::collection_id(id).unwrap().description, saved_description);80 assert_eq!(81 TemplateModule::collection_id(id).unwrap().description,82 saved_description83 );62 assert_eq!(TemplateModule::collection_id(id).unwrap().token_prefix, saved_prefix);84 assert_eq!(85 TemplateModule::collection_id(id).unwrap().token_prefix,86 saved_prefix87 );63 id88 id64}89}659066fn create_test_collection(mode: &CollectionMode, id: CollectionId) -> CollectionId {91fn create_test_collection(mode: &CollectionMode, id: CollectionId) -> CollectionId {67 create_test_collection_for_owner(&mode, 1, id)92 create_test_collection_for_owner(&mode, 1, id)68}93}699470fn create_test_item(collection_id: CollectionId, data: &CreateItemData) {95fn create_test_item(collection_id: CollectionId, data: &CreateItemData) {71 let origin1 = Origin::signed(1);96 let origin1 = Origin::signed(1);72 assert_ok!(TemplateModule::create_item(97 assert_ok!(TemplateModule::create_item(73 origin1.clone(),98 origin1,74 collection_id,99 collection_id,75 1,100 account(1),76 data.clone()101 data.clone()77 ));102 ));103}78104105fn account(sub: u64) -> TestCrossAccountId {106 TestCrossAccountId::from_sub(sub)79}107}8010881// Use cases tests region109// Use cases tests region82// #region110// #region8311184#[test]112#[test]85fn set_version_schema() {113fn set_version_schema() {86 new_test_ext().execute_with(|| {114 new_test_ext().execute_with(|| {87 default_limits();115 default_limits();88 let origin1 = Origin::signed(1);116 let origin1 = Origin::signed(1);89 let collection_id = create_test_collection(&CollectionMode::NFT, 1);117 let collection_id = create_test_collection(&CollectionMode::NFT, 1);90 11891 assert_ok!(TemplateModule::set_schema_version(origin1, collection_id, SchemaVersion::Unique));119 assert_ok!(TemplateModule::set_schema_version(120 origin1,121 collection_id,122 SchemaVersion::Unique123 ));92 assert_eq!(TemplateModule::collection_id(collection_id).unwrap().schema_version, SchemaVersion::Unique);124 assert_eq!(125 TemplateModule::collection_id(collection_id)126 .unwrap()127 .schema_version,128 SchemaVersion::Unique129 );93 });130 });94}131}9513296#[test]133#[test]97fn create_fungible_collection_fails_with_large_decimal_numbers() {134fn create_fungible_collection_fails_with_large_decimal_numbers() {98 new_test_ext().execute_with(|| {135 new_test_ext().execute_with(|| {99 default_limits();136 default_limits();100137101 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();138 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();102 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();139 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();103 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();140 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();104141105 let origin1 = Origin::signed(1);142 let origin1 = Origin::signed(1);106 assert_noop!(TemplateModule::create_collection(143 assert_noop!(144 TemplateModule::create_collection(107 origin1,145 origin1,108 col_name1,146 col_name1,109 col_desc1,147 col_desc1,110 token_prefix1,148 token_prefix1,111 CollectionMode::Fungible(MAX_DECIMAL_POINTS + 1)149 CollectionMode::Fungible(MAX_DECIMAL_POINTS + 1)112 ), Error::<Test>::CollectionDecimalPointLimitExceeded);150 ),151 Error::<Test>::CollectionDecimalPointLimitExceeded152 );113 }); 153 });114}154}115155116#[test]156#[test]117fn create_nft_item() {157fn create_nft_item() {118 new_test_ext().execute_with(|| {158 new_test_ext().execute_with(|| {119 default_limits();159 default_limits();120 let collection_id = create_test_collection(&CollectionMode::NFT, 1);160 let collection_id = create_test_collection(&CollectionMode::NFT, 1);121 161122 let data = default_nft_data();162 let data = default_nft_data();123 create_test_item(collection_id, &data.clone().into());163 create_test_item(collection_id, &data.clone().into());124 let item = TemplateModule::nft_item_id(collection_id, 1).unwrap();164 let item = TemplateModule::nft_item_id(collection_id, 1).unwrap();125 assert_eq!(item.const_data, data.const_data);165 assert_eq!(item.const_data, data.const_data);126 assert_eq!(item.variable_data, data.variable_data);166 assert_eq!(item.variable_data, data.variable_data);127 });167 });128}168}129169130// Use cases tests region170// Use cases tests region131// #region171// #region132#[test]172#[test]133fn create_nft_multiple_items() {173fn create_nft_multiple_items() {134 new_test_ext().execute_with(|| {174 new_test_ext().execute_with(|| {135 default_limits();175 default_limits();136 137 create_test_collection(&CollectionMode::NFT, 1);138176139 let origin1 = Origin::signed(1);177 create_test_collection(&CollectionMode::NFT, 1);140178141 let items_data = vec![default_nft_data(), default_nft_data(), default_nft_data()];179 let origin1 = Origin::signed(1);142180143 assert_ok!(TemplateModule::create_multiple_items(181 let items_data = vec![default_nft_data(), default_nft_data(), default_nft_data()];182183 assert_ok!(TemplateModule::create_multiple_items(144 origin1.clone(),184 origin1,145 1,185 1,146 1,186 account(1),147 items_data.clone().into_iter().map(|d| { d.into() }).collect()187 items_data188 .clone()189 .into_iter()190 .map(|d| { d.into() })191 .collect()148 ));192 ));149 for (index, data) in items_data.iter().enumerate() {193 for (index, data) in items_data.iter().enumerate() {150 let item = TemplateModule::nft_item_id(1, (index + 1) as TokenId).unwrap(); 194 let item = TemplateModule::nft_item_id(1, (index + 1) as TokenId).unwrap();151 assert_eq!(item.const_data.to_vec(), data.const_data);195 assert_eq!(item.const_data.to_vec(), data.const_data);152 assert_eq!(item.variable_data.to_vec(), data.variable_data);196 assert_eq!(item.variable_data.to_vec(), data.variable_data);153 }197 }154 });198 });155}199}156200157#[test]201#[test]158fn create_refungible_item() {202fn create_refungible_item() {159 new_test_ext().execute_with(|| {203 new_test_ext().execute_with(|| {160 default_limits();204 default_limits();161 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);205 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);162206163 let data = default_re_fungible_data();207 let data = default_re_fungible_data();164 create_test_item(collection_id, &data.clone().into());208 create_test_item(collection_id, &data.clone().into());165 let item = TemplateModule::refungible_item_id(collection_id, 1).unwrap();209 let item = TemplateModule::refungible_item_id(collection_id, 1).unwrap();166 assert_eq!(210 assert_eq!(item.const_data, data.const_data);167 item.const_data,168 data.const_data169 );170 assert_eq!(211 assert_eq!(item.variable_data, data.variable_data);171 item.variable_data,172 data.variable_data173 );174 assert_eq!(212 assert_eq!(175 item.owner[0],213 item.owner[0],176 Ownership {214 Ownership {177 owner: 1,215 owner: account(1),178 fraction: 1023216 fraction: 1023179 }217 }180 );218 );181 });219 });182}220}183221184#[test]222#[test]185fn create_multiple_refungible_items() {223fn create_multiple_refungible_items() {186 new_test_ext().execute_with(|| {224 new_test_ext().execute_with(|| {187 default_limits();225 default_limits();188 189 create_test_collection(&CollectionMode::ReFungible, 1);190226191 let origin1 = Origin::signed(1);227 create_test_collection(&CollectionMode::ReFungible, 1);192228193 let items_data = vec![default_re_fungible_data(), default_re_fungible_data(), default_re_fungible_data()];229 let origin1 = Origin::signed(1);194230195 assert_ok!(TemplateModule::create_multiple_items(231 let items_data = vec![196 origin1.clone(),232 default_re_fungible_data(),197 1,233 default_re_fungible_data(),198 1,199 items_data.clone().into_iter().map(|d| { d.into() }).collect()234 default_re_fungible_data(),200 ));235 ];201 for (index, data) in items_data.iter().enumerate() {202236237 assert_ok!(TemplateModule::create_multiple_items(238 origin1,239 1,240 account(1),241 items_data242 .clone()243 .into_iter()203 let item = TemplateModule::refungible_item_id(1, (index + 1) as TokenId).unwrap();244 .map(|d| { d.into() })245 .collect()246 ));247 for (index, data) in items_data.iter().enumerate() {248 let item = TemplateModule::refungible_item_id(1, (index + 1) as TokenId).unwrap();204 assert_eq!(item.const_data.to_vec(), data.const_data);249 assert_eq!(item.const_data.to_vec(), data.const_data);205 assert_eq!(item.variable_data.to_vec(), data.variable_data);250 assert_eq!(item.variable_data.to_vec(), data.variable_data);206 assert_eq!(251 assert_eq!(207 item.owner[0],252 item.owner[0],208 Ownership {253 Ownership {209 owner: 1,254 owner: account(1),210 fraction: 1023255 fraction: 1023211 }256 }212 );257 );213 }258 }214 });259 });215}260}216261217#[test]262#[test]218fn create_fungible_item() {263fn create_fungible_item() {219 new_test_ext().execute_with(|| {264 new_test_ext().execute_with(|| {220 default_limits();265 default_limits();221 222 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);223266224 let data = default_fungible_data();267 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);225 create_test_item(collection_id, &data.into());226268227 assert_eq!(TemplateModule::fungible_item_id(collection_id, 1).value, 5);269 let data = default_fungible_data();270 create_test_item(collection_id, &data.into());271272 assert_eq!(TemplateModule::fungible_item_id(collection_id, 1).value, 5);228 });273 });229}274}230275231//#[test]276//#[test]245// 1,290// 1,246// items_data.clone().into_iter().map(|d| { d.into() }).collect()291// items_data.clone().into_iter().map(|d| { d.into() }).collect()247// ));292// ));248 293249// for (index, _) in items_data.iter().enumerate() {294// for (index, _) in items_data.iter().enumerate() {250// assert_eq!(TemplateModule::fungible_item_id(1, (index + 1) as TokenId).value, 5);295// assert_eq!(TemplateModule::fungible_item_id(1, (index + 1) as TokenId).value, 5);251// }296// }256301257#[test]302#[test]258fn transfer_fungible_item() {303fn transfer_fungible_item() {259 new_test_ext().execute_with(|| {304 new_test_ext().execute_with(|| {260 default_limits();305 default_limits();261 262 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);263306264 let origin1 = Origin::signed(1);307 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);265 let origin2 = Origin::signed(2);266308267 let data = default_fungible_data();309 let origin1 = Origin::signed(1);268 create_test_item(collection_id, &data.into());310 let origin2 = Origin::signed(2);269311270 assert_eq!(TemplateModule::fungible_item_id(1, 1).value, 5);312 let data = default_fungible_data();271 assert_eq!(TemplateModule::balance_count(1, 1), 5);313 create_test_item(collection_id, &data.into());272314273 // change owner scenario274 assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 5));275 assert_eq!(TemplateModule::fungible_item_id(1, 1).value, 0);315 assert_eq!(TemplateModule::fungible_item_id(1, 1).value, 5);276 assert_eq!(TemplateModule::balance_count(1, 1), 0);316 assert_eq!(TemplateModule::balance_count(1, 1), 5);277 assert_eq!(TemplateModule::balance_count(1, 2), 5);278317279 // split item scenario318 // change owner scenario280 assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 3));319 assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 5));281 assert_eq!(TemplateModule::balance_count(1, 2), 2);320 assert_eq!(TemplateModule::fungible_item_id(1, 1).value, 0);321 assert_eq!(TemplateModule::balance_count(1, 1), 0);282 assert_eq!(TemplateModule::balance_count(1, 3), 3);322 assert_eq!(TemplateModule::balance_count(1, 2), 5);283323284 // split item and new owner has account scenario324 // split item scenario325 assert_ok!(TemplateModule::transfer(326 origin2.clone(),327 account(3),328 1,329 1,330 3331 ));332 assert_eq!(TemplateModule::balance_count(1, 2), 2);333 assert_eq!(TemplateModule::balance_count(1, 3), 3);334335 // split item and new owner has account scenario285 assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 1));336 assert_ok!(TemplateModule::transfer(origin2, account(3), 1, 1, 1));286 assert_eq!(TemplateModule::fungible_item_id(1, 2).value, 1);337 assert_eq!(TemplateModule::fungible_item_id(1, 2).value, 1);287 assert_eq!(TemplateModule::fungible_item_id(1, 3).value, 4);338 assert_eq!(TemplateModule::fungible_item_id(1, 3).value, 4);288 assert_eq!(TemplateModule::balance_count(1, 2), 1);339 assert_eq!(TemplateModule::balance_count(1, 2), 1);289 assert_eq!(TemplateModule::balance_count(1, 3), 4);340 assert_eq!(TemplateModule::balance_count(1, 3), 4);290 });341 });291}342}292343293#[test]344#[test]294fn transfer_refungible_item() {345fn transfer_refungible_item() {295 new_test_ext().execute_with(|| {346 new_test_ext().execute_with(|| {296 default_limits();347 default_limits();297 298 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);299348300 let data = default_re_fungible_data();349 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);301 create_test_item(collection_id, &data.clone().into());302350303 let origin1 = Origin::signed(1);351 let data = default_re_fungible_data();304 let origin2 = Origin::signed(2);352 create_test_item(collection_id, &data.clone().into());305 {306 let item = TemplateModule::refungible_item_id(collection_id, 1).unwrap();307 assert_eq!(308 item.const_data,309 data.const_data310 );311 assert_eq!(312 item.variable_data,313 data.variable_data314 );315 assert_eq!(316 item.owner[0],317 Ownership {318 owner: 1,319 fraction: 1023320 }321 );322 }323 assert_eq!(TemplateModule::balance_count(1, 1), 1023);324 assert_eq!(TemplateModule::address_tokens(1, 1), [1]);325353326 // change owner scenario354 let origin1 = Origin::signed(1);327 assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1023));328 assert_eq!(355 let origin2 = Origin::signed(2);356 {329 TemplateModule::refungible_item_id(1, 1).unwrap().owner[0],357 let item = TemplateModule::refungible_item_id(collection_id, 1).unwrap();358 assert_eq!(item.const_data, data.const_data);359 assert_eq!(item.variable_data, data.variable_data);360 assert_eq!(361 item.owner[0],330 Ownership {362 Ownership {331 owner: 2,363 owner: account(1),332 fraction: 1023364 fraction: 1023333 }365 }334 );366 );367 }335 assert_eq!(TemplateModule::balance_count(1, 1), 0);368 assert_eq!(TemplateModule::balance_count(1, 1), 1023);336 assert_eq!(TemplateModule::balance_count(1, 2), 1023);337 // assert_eq!(TemplateModule::address_tokens(1, 1), []);369 assert_eq!(TemplateModule::address_tokens(1, 1), [1]);338 assert_eq!(TemplateModule::address_tokens(1, 2), [1]);339370340 // split item scenario371 // change owner scenario341 assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 500));372 assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 1023));342 {373 assert_eq!(343 let item = TemplateModule::refungible_item_id(1, 1).unwrap();374 TemplateModule::refungible_item_id(1, 1).unwrap().owner[0],344 assert_eq!(345 item.owner[0],346 Ownership {375 Ownership {347 owner: 2,376 owner: account(2),348 fraction: 523349 }350 );351 assert_eq!(352 item.owner[1],353 Ownership {354 owner: 3,355 fraction: 500377 fraction: 1023356 }378 }357 );379 );358 }359 assert_eq!(TemplateModule::balance_count(1, 2), 523);380 assert_eq!(TemplateModule::balance_count(1, 1), 0);360 assert_eq!(TemplateModule::balance_count(1, 3), 500);381 assert_eq!(TemplateModule::balance_count(1, 2), 1023);361 assert_eq!(TemplateModule::address_tokens(1, 2), [1]);382 // assert_eq!(TemplateModule::address_tokens(1, 1), []);362 assert_eq!(TemplateModule::address_tokens(1, 3), [1]);383 assert_eq!(TemplateModule::address_tokens(1, 2), [1]);363384364 // split item and new owner has account scenario385 // split item scenario365 assert_ok!(TemplateModule::transfer(origin2.clone(), 3, 1, 1, 200));386 assert_ok!(TemplateModule::transfer(387 origin2.clone(),388 account(3),389 1,390 1,391 500392 ));366 {393 {367 let item = TemplateModule::refungible_item_id(1, 1).unwrap();394 let item = TemplateModule::refungible_item_id(1, 1).unwrap();368 assert_eq!(395 assert_eq!(369 item.owner[0],396 item.owner[0],370 Ownership {397 Ownership {371 owner: 2,398 owner: account(2),372 fraction: 323399 fraction: 523400 }401 );402 assert_eq!(403 item.owner[1],404 Ownership {405 owner: account(3),406 fraction: 500407 }408 );409 }373 }410 assert_eq!(TemplateModule::balance_count(1, 2), 523);411 assert_eq!(TemplateModule::balance_count(1, 3), 500);412 assert_eq!(TemplateModule::address_tokens(1, 2), [1]);413 assert_eq!(TemplateModule::address_tokens(1, 3), [1]);414415 // split item and new owner has account scenario374 );416 assert_ok!(TemplateModule::transfer(origin2, account(3), 1, 1, 200));417 {375 assert_eq!(418 let item = TemplateModule::refungible_item_id(1, 1).unwrap();419 assert_eq!(420 item.owner[0],376 item.owner[1],421 Ownership {422 owner: account(2),423 fraction: 323424 }425 );426 assert_eq!(427 item.owner[1],377 Ownership {428 Ownership {378 owner: 3,429 owner: account(3),379 fraction: 700430 fraction: 700380 }431 }381 );432 );382 }433 }383 assert_eq!(TemplateModule::balance_count(1, 2), 323);434 assert_eq!(TemplateModule::balance_count(1, 2), 323);384 assert_eq!(TemplateModule::balance_count(1, 3), 700);435 assert_eq!(TemplateModule::balance_count(1, 3), 700);385 assert_eq!(TemplateModule::address_tokens(1, 2), [1]);436 assert_eq!(TemplateModule::address_tokens(1, 2), [1]);386 assert_eq!(TemplateModule::address_tokens(1, 3), [1]);437 assert_eq!(TemplateModule::address_tokens(1, 3), [1]);387 });438 });388}439}389440390#[test]441#[test]391fn transfer_nft_item() {442fn transfer_nft_item() {392 new_test_ext().execute_with(|| {443 new_test_ext().execute_with(|| {393 default_limits();444 default_limits();394 395 let collection_id = create_test_collection(&CollectionMode::NFT, 1);396445397 let data = default_nft_data();446 let collection_id = create_test_collection(&CollectionMode::NFT, 1);398 create_test_item(collection_id, &data.into());399 assert_eq!(TemplateModule::balance_count(1, 1), 1);400 assert_eq!(TemplateModule::address_tokens(1, 1), [1]);401447402 let origin1 = Origin::signed(1);448 let data = default_nft_data();449 create_test_item(collection_id, &data.into());450 assert_eq!(TemplateModule::balance_count(1, 1), 1);451 assert_eq!(TemplateModule::address_tokens(1, 1), [1]);452453 let origin1 = Origin::signed(1);403 // default scenario454 // default scenario404 assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1000));455 assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 1000));405 assert_eq!(TemplateModule::nft_item_id(1, 1).unwrap().owner, 2);456 assert_eq!(TemplateModule::nft_item_id(1, 1).unwrap().owner, account(2));406 assert_eq!(TemplateModule::balance_count(1, 1), 0);457 assert_eq!(TemplateModule::balance_count(1, 1), 0);407 assert_eq!(TemplateModule::balance_count(1, 2), 1);458 assert_eq!(TemplateModule::balance_count(1, 2), 1);408 // assert_eq!(TemplateModule::address_tokens(1, 1), []);459 // assert_eq!(TemplateModule::address_tokens(1, 1), []);409 assert_eq!(TemplateModule::address_tokens(1, 2), [1]);460 assert_eq!(TemplateModule::address_tokens(1, 2), [1]);410 });461 });411}462}412463413#[test]464#[test]414fn nft_approve_and_transfer_from() {465fn nft_approve_and_transfer_from() {415 new_test_ext().execute_with(|| {466 new_test_ext().execute_with(|| {416 default_limits();467 default_limits();417 418 let collection_id = create_test_collection(&CollectionMode::NFT, 1);419468420 let data = default_nft_data();469 let collection_id = create_test_collection(&CollectionMode::NFT, 1);421 create_test_item(collection_id, &data.into());422470423 let origin1 = Origin::signed(1);471 let data = default_nft_data();424 let origin2 = Origin::signed(2);472 create_test_item(collection_id, &data.into());425473426 assert_eq!(TemplateModule::balance_count(1, 1), 1);474 let origin1 = Origin::signed(1);427 assert_eq!(TemplateModule::address_tokens(1, 1), [1]);475 let origin2 = Origin::signed(2);428476429 // neg transfer430 assert_noop!(TemplateModule::transfer_from(477 assert_eq!(TemplateModule::balance_count(1, 1), 1);431 origin2.clone(),432 1,433 2,434 1,435 1,478 assert_eq!(TemplateModule::address_tokens(1, 1), [1]);436 1), Error::<Test>::NoPermission);437479438 // do approve480 // neg transfer439 assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1, 5));481 assert_noop!(440 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);482 TemplateModule::transfer_from(origin2.clone(), account(1), account(2), 1, 1, 1),441 assert_eq!(483 Error::<Test>::NoPermission442 TemplateModule::approved(1, (1, 1, 2)),443 5444 );484 );445485446 assert_ok!(TemplateModule::transfer_from(486 // do approve447 origin2.clone(),487 assert_ok!(TemplateModule::approve(origin1, account(2), 1, 1, 5));448 1,488 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);489 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);490491 assert_ok!(TemplateModule::transfer_from(492 origin2,493 account(1),449 3,494 account(3),450 1,495 1,451 1,496 1,452 1497 1453 ));498 ));454 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 4);499 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 4);455 });500 });456}501}457502458#[test]503#[test]459fn nft_approve_and_transfer_from_white_list() {504fn nft_approve_and_transfer_from_white_list() {460 new_test_ext().execute_with(|| {505 new_test_ext().execute_with(|| {461 default_limits();506 default_limits();462 463 let collection_id = create_test_collection(&CollectionMode::NFT, 1);464507465 let origin1 = Origin::signed(1);508 let collection_id = create_test_collection(&CollectionMode::NFT, 1);466 let origin2 = Origin::signed(2);467509468 let data = default_nft_data();510 let origin1 = Origin::signed(1);469 create_test_item(collection_id, &data.clone().into());511 let origin2 = Origin::signed(2);470512471 assert_eq!(TemplateModule::nft_item_id(1, 1).unwrap().const_data, data.const_data);513 let data = default_nft_data();472 assert_eq!(TemplateModule::balance_count(1, 1), 1);514 create_test_item(collection_id, &data.clone().into());473 assert_eq!(TemplateModule::address_tokens(1, 1), [1]);474515475 assert_ok!(TemplateModule::set_mint_permission(516 assert_eq!(476 origin1.clone(),477 1,517 TemplateModule::nft_item_id(1, 1).unwrap().const_data,478 true518 data.const_data479 ));480 assert_ok!(TemplateModule::set_public_access_mode(481 origin1.clone(),482 1,483 AccessMode::WhiteList484 ));519 );485 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));520 assert_eq!(TemplateModule::balance_count(1, 1), 1);486 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));487 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));521 assert_eq!(TemplateModule::address_tokens(1, 1), [1]);488522489 // do approve490 assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1, 5));523 assert_ok!(TemplateModule::set_mint_permission(524 origin1.clone(),525 1,526 true527 ));491 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);528 assert_ok!(TemplateModule::set_public_access_mode(529 origin1.clone(),530 1,531 AccessMode::WhiteList532 ));492 assert_ok!(TemplateModule::approve(origin1.clone(), 3, 1, 1, 5));533 assert_ok!(TemplateModule::add_to_white_list(534 origin1.clone(),535 1,536 account(1)537 ));493 assert_eq!(TemplateModule::approved(1, (1, 1, 3)), 5);538 assert_ok!(TemplateModule::add_to_white_list(539 origin1.clone(),540 1,541 account(2)542 ));543 assert_ok!(TemplateModule::add_to_white_list(544 origin1.clone(),545 1,546 account(3)547 ));494548495 assert_ok!(TemplateModule::transfer_from(549 // do approve550 assert_ok!(TemplateModule::approve(496 origin2.clone(),551 origin1.clone(),552 account(2),553 1,554 1,555 5556 ));497 1,557 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);558 assert_ok!(TemplateModule::approve(origin1, account(3), 1, 1, 5));559 assert_eq!(TemplateModule::approved(1, (1, 1, 3)), 5);560561 assert_ok!(TemplateModule::transfer_from(562 origin2,563 account(1),498 3,564 account(3),499 1,565 1,500 1,566 1,501 1567 1502 ));568 ));503 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 4);569 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 4);504 });570 });505}571}506572507#[test]573#[test]508fn refungible_approve_and_transfer_from() {574fn refungible_approve_and_transfer_from() {509 new_test_ext().execute_with(|| {575 new_test_ext().execute_with(|| {510 default_limits();576 default_limits();511 512 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);513 514 let origin1 = Origin::signed(1);515 let origin2 = Origin::signed(2);516577517 let data = default_re_fungible_data();578 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);518 create_test_item(collection_id, &data.into());519579520 assert_eq!(TemplateModule::balance_count(1, 1), 1023);580 let origin1 = Origin::signed(1);521 assert_eq!(TemplateModule::address_tokens(1, 1), [1]);581 let origin2 = Origin::signed(2);522582523 assert_ok!(TemplateModule::set_mint_permission(583 let data = default_re_fungible_data();524 origin1.clone(),525 1,526 true527 ));528 assert_ok!(TemplateModule::set_public_access_mode(584 create_test_item(collection_id, &data.into());529 origin1.clone(),530 1,531 AccessMode::WhiteList532 ));533 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));534 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));535 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));536585537 // do approve538 assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1, 1023));586 assert_eq!(TemplateModule::balance_count(1, 1), 1023);539 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1023);587 assert_eq!(TemplateModule::address_tokens(1, 1), [1]);540588541 assert_ok!(TemplateModule::transfer_from(589 assert_ok!(TemplateModule::set_mint_permission(542 origin2.clone(),590 origin1.clone(),543 1,591 1,544 3,592 true545 1,546 1,547 100548 ));593 ));549 assert_eq!(TemplateModule::balance_count(1, 1), 923);594 assert_ok!(TemplateModule::set_public_access_mode(595 origin1.clone(),596 1,597 AccessMode::WhiteList598 ));550 assert_eq!(TemplateModule::balance_count(1, 3), 100);599 assert_ok!(TemplateModule::add_to_white_list(600 origin1.clone(),601 1,602 account(1)603 ));551 assert_eq!(TemplateModule::address_tokens(1, 1), [1]);604 assert_ok!(TemplateModule::add_to_white_list(605 origin1.clone(),606 1,607 account(2)608 ));552 assert_eq!(TemplateModule::address_tokens(1, 3), [1]);609 assert_ok!(TemplateModule::add_to_white_list(610 origin1.clone(),611 1,612 account(3)613 ));553614554 assert_eq!(615 // do approve616 assert_ok!(TemplateModule::approve(origin1, account(2), 1, 1, 1023));555 TemplateModule::approved(1, (1, 1, 2)),617 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1023);618619 assert_ok!(TemplateModule::transfer_from(620 origin2,621 account(1),622 account(3),623 1,624 1,625 100626 ));556 923627 assert_eq!(TemplateModule::balance_count(1, 1), 923);557 );628 assert_eq!(TemplateModule::balance_count(1, 3), 100);629 assert_eq!(TemplateModule::address_tokens(1, 1), [1]);630 assert_eq!(TemplateModule::address_tokens(1, 3), [1]);631558 });632 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 923);633 });559}634}560635561#[test]636#[test]562fn fungible_approve_and_transfer_from() {637fn fungible_approve_and_transfer_from() {563 new_test_ext().execute_with(|| {638 new_test_ext().execute_with(|| {564 default_limits();639 default_limits();565 566 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);567 568 let data = default_fungible_data();569 create_test_item(collection_id, &data.into());570640571 let origin1 = Origin::signed(1);641 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);572 let origin2 = Origin::signed(2);573642574 assert_eq!(TemplateModule::balance_count(1, 1), 5);643 let data = default_fungible_data();644 create_test_item(collection_id, &data.into());575645576 assert_ok!(TemplateModule::set_mint_permission(646 let origin1 = Origin::signed(1);577 origin1.clone(),578 1,579 true580 ));581 assert_ok!(TemplateModule::set_public_access_mode(582 origin1.clone(),583 1,584 AccessMode::WhiteList585 ));586 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));647 let origin2 = Origin::signed(2);587 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));588 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));589648590 // do approve591 assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1, 5));592 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);649 assert_eq!(TemplateModule::balance_count(1, 1), 5);593 assert_ok!(TemplateModule::approve(origin1.clone(), 3, 1, 1, 5));594 assert_eq!(TemplateModule::approved(1, (1, 1, 3)), 5);595 assert_eq!(596 TemplateModule::approved(1, (1, 1, 2)),597 5598 );599650600 assert_ok!(TemplateModule::transfer_from(651 assert_ok!(TemplateModule::set_mint_permission(601 origin2.clone(),652 origin1.clone(),602 1,653 1,603 3,654 true655 ));656 assert_ok!(TemplateModule::set_public_access_mode(604 1,657 origin1.clone(),605 1,658 1,606 4659 AccessMode::WhiteList607 ));660 ));608 assert_eq!(TemplateModule::balance_count(1, 1), 1);661 assert_ok!(TemplateModule::add_to_white_list(662 origin1.clone(),663 1,664 account(1)665 ));666 assert_ok!(TemplateModule::add_to_white_list(667 origin1.clone(),668 1,669 account(2)670 ));609 assert_eq!(TemplateModule::balance_count(1, 3), 4);671 assert_ok!(TemplateModule::add_to_white_list(672 origin1.clone(),673 1,674 account(3)675 ));610676611 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1);677 // do approve678 assert_ok!(TemplateModule::approve(679 origin1.clone(),680 account(2),681 1,682 1,683 5684 ));685 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);686 assert_ok!(TemplateModule::approve(origin1, account(3), 1, 1, 5));687 assert_eq!(TemplateModule::approved(1, (1, 1, 3)), 5);688 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 5);612689613 assert_noop!(TemplateModule::transfer_from(690 assert_ok!(TemplateModule::transfer_from(614 origin2.clone(),691 origin2.clone(),615 1,692 account(1),616 3,693 account(3),617 1,694 1,618 1,695 1,696 4697 ));619 4698 assert_eq!(TemplateModule::balance_count(1, 1), 1);699 assert_eq!(TemplateModule::balance_count(1, 3), 4);700701 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1);702703 assert_noop!(620 ), Error::<Test>::NoPermission);704 TemplateModule::transfer_from(origin2, account(1), account(3), 1, 1, 4),705 Error::<Test>::NoPermission706 );621 });707 });622}708}623709624#[test]710#[test]625fn change_collection_owner() {711fn change_collection_owner() {626 new_test_ext().execute_with(|| {712 new_test_ext().execute_with(|| {627 default_limits();713 default_limits();628 714629 let collection_id = create_test_collection(&CollectionMode::NFT, 1);715 let collection_id = create_test_collection(&CollectionMode::NFT, 1);630 716631 let origin1 = Origin::signed(1);717 let origin1 = Origin::signed(1);632 assert_ok!(TemplateModule::change_collection_owner(718 assert_ok!(TemplateModule::change_collection_owner(633 origin1.clone(),719 origin1,634 collection_id,720 collection_id,635 2721 2636 ));722 ));637 assert_eq!(TemplateModule::collection_id(collection_id).unwrap().owner, 2);723 assert_eq!(724 TemplateModule::collection_id(collection_id).unwrap().owner,725 2726 );638 });727 });639}728}640729641#[test]730#[test]642fn destroy_collection() {731fn destroy_collection() {643 new_test_ext().execute_with(|| {732 new_test_ext().execute_with(|| {644 default_limits();733 default_limits();645 734646 let collection_id = create_test_collection(&CollectionMode::NFT, 1);735 let collection_id = create_test_collection(&CollectionMode::NFT, 1);647 736648 let origin1 = Origin::signed(1);737 let origin1 = Origin::signed(1);649 assert_ok!(TemplateModule::destroy_collection(origin1.clone(), collection_id));738 assert_ok!(TemplateModule::destroy_collection(origin1, collection_id));650 });739 });651}740}652741653#[test]742#[test]654fn burn_nft_item() {743fn burn_nft_item() {655 new_test_ext().execute_with(|| {744 new_test_ext().execute_with(|| {656 default_limits();745 default_limits();657 658 let collection_id = create_test_collection(&CollectionMode::NFT, 1);659746660 let origin1 = Origin::signed(1);747 let collection_id = create_test_collection(&CollectionMode::NFT, 1);661 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection_id, 2));662 663 let data = default_nft_data();664 create_test_item(collection_id, &data.into());665748666 // check balance (collection with id = 1, user id = 1)749 let origin1 = Origin::signed(1);667 assert_eq!(TemplateModule::balance_count(1, 1), 1);750 assert_ok!(TemplateModule::add_collection_admin(751 origin1.clone(),752 collection_id,753 account(2)754 ));668755669 // burn item756 let data = default_nft_data();670 assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 5));671 assert_noop!(757 create_test_item(collection_id, &data.into());672 TemplateModule::burn_item(origin1.clone(), 1, 1, 5),673 Error::<Test>::TokenNotFound674 );675758676 assert_eq!(TemplateModule::balance_count(1, 1), 0);759 // check balance (collection with id = 1, user id = 1)760 assert_eq!(TemplateModule::balance_count(1, 1), 1);761677 });762 // burn item763 assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 5));764 assert_noop!(765 TemplateModule::burn_item(origin1, 1, 1, 5),766 Error::<Test>::TokenNotFound767 );768769 assert_eq!(TemplateModule::balance_count(1, 1), 0);770 });678}771}679772680#[test]773#[test]681fn burn_fungible_item() {774fn burn_fungible_item() {682 new_test_ext().execute_with(|| {775 new_test_ext().execute_with(|| {683 default_limits();776 default_limits();684 685 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);686 687 let origin1 = Origin::signed(1);688 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection_id, 2));689 690 let data = default_fungible_data();691 create_test_item(collection_id, &data.into());692777693 // check balance (collection with id = 1, user id = 1)778 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);694 assert_eq!(TemplateModule::balance_count(1, 1), 5);695779696 // burn item780 let origin1 = Origin::signed(1);697 assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 5));698 assert_noop!(781 assert_ok!(TemplateModule::add_collection_admin(699 TemplateModule::burn_item(origin1.clone(), 1, 1, 5),782 origin1.clone(),700 Error::<Test>::TokenValueNotEnough783 collection_id,784 account(2)701 );785 ));702786703 assert_eq!(TemplateModule::balance_count(1, 1), 0);787 let data = default_fungible_data();788 create_test_item(collection_id, &data.into());789790 // check balance (collection with id = 1, user id = 1)791 assert_eq!(TemplateModule::balance_count(1, 1), 5);792704 });793 // burn item794 assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 5));795 assert_noop!(796 TemplateModule::burn_item(origin1, 1, 1, 5),797 Error::<Test>::TokenValueNotEnough798 );799800 assert_eq!(TemplateModule::balance_count(1, 1), 0);801 });705}802}706803707#[test]804#[test]708fn burn_refungible_item() {805fn burn_refungible_item() {709 new_test_ext().execute_with(|| {806 new_test_ext().execute_with(|| {710 default_limits();807 default_limits();711 712 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);713 let origin1 = Origin::signed(1);714808715 assert_ok!(TemplateModule::set_mint_permission(809 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);716 origin1.clone(),717 collection_id,718 true719 ));720 assert_ok!(TemplateModule::set_public_access_mode(810 let origin1 = Origin::signed(1);721 origin1.clone(),722 collection_id,723 AccessMode::WhiteList724 ));725 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));726811727 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), 1, 2));812 assert_ok!(TemplateModule::set_mint_permission(728 813 origin1.clone(),814 collection_id,815 true816 ));817 assert_ok!(TemplateModule::set_public_access_mode(729 let data = default_re_fungible_data();818 origin1.clone(),819 collection_id,820 AccessMode::WhiteList821 ));730 create_test_item(collection_id, &data.into());822 assert_ok!(TemplateModule::add_to_white_list(823 origin1.clone(),824 1,825 account(1)826 ));731827732 // check balance (collection with id = 1, user id = 2)733 assert_eq!(TemplateModule::balance_count(1, 1), 1023);828 assert_ok!(TemplateModule::add_collection_admin(829 origin1.clone(),830 1,831 account(2)832 ));734833735 // burn item834 let data = default_re_fungible_data();736 assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 1023));737 assert_noop!(835 create_test_item(collection_id, &data.into());738 TemplateModule::burn_item(origin1.clone(), 1, 1, 1023),739 Error::<Test>::TokenNotFound740 );741836742 assert_eq!(TemplateModule::balance_count(1, 1), 0);837 // check balance (collection with id = 1, user id = 2)838 assert_eq!(TemplateModule::balance_count(1, 1), 1023);839743 });840 // burn item841 assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 1023));842 assert_noop!(843 TemplateModule::burn_item(origin1, 1, 1, 1023),844 Error::<Test>::TokenNotFound845 );846847 assert_eq!(TemplateModule::balance_count(1, 1), 0);848 });744}849}745850746#[test]851#[test]747fn add_collection_admin() {852fn add_collection_admin() {748 new_test_ext().execute_with(|| {853 new_test_ext().execute_with(|| {749 default_limits();854 default_limits();750 751 let collection1_id = create_test_collection_for_owner(&CollectionMode::NFT, 1, 1);752 create_test_collection_for_owner(&CollectionMode::NFT, 2, 2);753 create_test_collection_for_owner(&CollectionMode::NFT, 3, 3);754 755 let origin1 = Origin::signed(1);756855757 // collection admin856 let collection1_id = create_test_collection_for_owner(&CollectionMode::NFT, 1, 1);758 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection1_id, 2));857 create_test_collection_for_owner(&CollectionMode::NFT, 2, 2);759 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection1_id, 3));858 create_test_collection_for_owner(&CollectionMode::NFT, 3, 3);760859761 assert_eq!(TemplateModule::admin_list_collection(collection1_id).contains(&2), true);860 let origin1 = Origin::signed(1);861862 // collection admin863 assert_ok!(TemplateModule::add_collection_admin(864 origin1.clone(),865 collection1_id,866 account(2)867 ));868 assert_ok!(TemplateModule::add_collection_admin(869 origin1,870 collection1_id,871 account(3)872 ));873874 assert!(TemplateModule::admin_list_collection(collection1_id).contains(&account(2)),);762 assert_eq!(TemplateModule::admin_list_collection(collection1_id).contains(&3), true);875 assert!(TemplateModule::admin_list_collection(collection1_id).contains(&account(3)),);763 });876 });764}877}765878766#[test]879#[test]767fn remove_collection_admin() {880fn remove_collection_admin() {768 new_test_ext().execute_with(|| {881 new_test_ext().execute_with(|| {769 default_limits();882 default_limits();770 771 let collection1_id = create_test_collection_for_owner(&CollectionMode::NFT, 1, 1);772 create_test_collection_for_owner(&CollectionMode::NFT, 2, 2);773 create_test_collection_for_owner(&CollectionMode::NFT, 3, 3);774883775 let origin1 = Origin::signed(1);884 let collection1_id = create_test_collection_for_owner(&CollectionMode::NFT, 1, 1);776 let origin2 = Origin::signed(2);885 create_test_collection_for_owner(&CollectionMode::NFT, 2, 2);886 create_test_collection_for_owner(&CollectionMode::NFT, 3, 3);777887778 // collection admin888 let origin1 = Origin::signed(1);779 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection1_id, 2));780 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection1_id, 3));889 let origin2 = Origin::signed(2);781890782 assert_eq!(TemplateModule::admin_list_collection(1).contains(&2), true);891 // collection admin892 assert_ok!(TemplateModule::add_collection_admin(893 origin1.clone(),894 collection1_id,895 account(2)896 ));783 assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), true);897 assert_ok!(TemplateModule::add_collection_admin(898 origin1,899 collection1_id,900 account(3)901 ));784902903 assert!(TemplateModule::admin_list_collection(1).contains(&account(2)),);904 assert!(TemplateModule::admin_list_collection(1).contains(&account(3)),);905785 // remove admin906 // remove admin786 assert_ok!(TemplateModule::remove_collection_admin(907 assert_ok!(TemplateModule::remove_collection_admin(787 origin2.clone(),908 origin2,788 1,909 1,789 3910 account(3)790 ));911 ));791 assert_eq!(TemplateModule::admin_list_collection(1).contains(&3), false);912 assert!(!TemplateModule::admin_list_collection(1).contains(&account(3)),);792 });913 });793}914}794915795#[test]916#[test]796fn balance_of() {917fn balance_of() {797 new_test_ext().execute_with(|| {918 new_test_ext().execute_with(|| {798 default_limits();919 default_limits();799 800 let nft_collection_id = create_test_collection(&CollectionMode::NFT, 1);801 let fungible_collection_id = create_test_collection(&CollectionMode::Fungible(3), 2);802 let re_fungible_collection_id = create_test_collection(&CollectionMode::ReFungible, 3);803 804 // check balance before805 assert_eq!(TemplateModule::balance_count(nft_collection_id, 1), 0);806 assert_eq!(TemplateModule::balance_count(fungible_collection_id, 1), 0);807 assert_eq!(TemplateModule::balance_count(re_fungible_collection_id, 1), 0);808920809 let nft_data = default_nft_data();921 let nft_collection_id = create_test_collection(&CollectionMode::NFT, 1);810 create_test_item(nft_collection_id, &nft_data.into());811 812 let fungible_data = default_fungible_data();922 let fungible_collection_id = create_test_collection(&CollectionMode::Fungible(3), 2);813 create_test_item(fungible_collection_id, &fungible_data.into());814 815 let re_fungible_data = default_re_fungible_data();923 let re_fungible_collection_id = create_test_collection(&CollectionMode::ReFungible, 3);816 create_test_item(re_fungible_collection_id, &re_fungible_data.into());817924818 // check balance (collection with id = 1, user id = 1)925 // check balance before926 assert_eq!(TemplateModule::balance_count(nft_collection_id, 1), 0);927 assert_eq!(TemplateModule::balance_count(fungible_collection_id, 1), 0);928 assert_eq!(929 TemplateModule::balance_count(re_fungible_collection_id, 1),930 0931 );932933 let nft_data = default_nft_data();934 create_test_item(nft_collection_id, &nft_data.into());935936 let fungible_data = default_fungible_data();937 create_test_item(fungible_collection_id, &fungible_data.into());938939 let re_fungible_data = default_re_fungible_data();940 create_test_item(re_fungible_collection_id, &re_fungible_data.into());941942 // check balance (collection with id = 1, user id = 1)819 assert_eq!(TemplateModule::balance_count(nft_collection_id, 1), 1);943 assert_eq!(TemplateModule::balance_count(nft_collection_id, 1), 1);820 assert_eq!(TemplateModule::balance_count(fungible_collection_id, 1), 5);944 assert_eq!(TemplateModule::balance_count(fungible_collection_id, 1), 5);821 assert_eq!(TemplateModule::balance_count(re_fungible_collection_id, 1), 1023);945 assert_eq!(946 TemplateModule::balance_count(re_fungible_collection_id, 1),947 1023948 );822 assert_eq!(TemplateModule::nft_item_id(nft_collection_id, 1).unwrap().owner, 1);949 assert_eq!(950 TemplateModule::nft_item_id(nft_collection_id, 1)951 .unwrap()952 .owner,953 account(1)954 );823 assert_eq!(TemplateModule::fungible_item_id(fungible_collection_id, 1).value, 5);955 assert_eq!(956 TemplateModule::fungible_item_id(fungible_collection_id, 1).value,957 5958 );824 assert_eq!(TemplateModule::refungible_item_id(re_fungible_collection_id, 1).unwrap().owner[0].owner, 1);959 assert_eq!(960 TemplateModule::refungible_item_id(re_fungible_collection_id, 1)961 .unwrap()962 .owner[0]963 .owner,964 account(1)965 );825 });966 });826}967}827968828#[test]969#[test]829fn approve() {970fn approve() {830 new_test_ext().execute_with(|| {971 new_test_ext().execute_with(|| {831 default_limits();972 default_limits();832 833 let collection_id = create_test_collection(&CollectionMode::NFT, 1);834 835 let data = default_nft_data();836 create_test_item(collection_id, &data.into());837973838 let origin1 = Origin::signed(1);974 let collection_id = create_test_collection(&CollectionMode::NFT, 1);839 975976 let data = default_nft_data();977 create_test_item(collection_id, &data.into());978979 let origin1 = Origin::signed(1);980840 // approve981 // approve841 assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1, 1));982 assert_ok!(TemplateModule::approve(origin1, account(2), 1, 1, 1));842 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1);983 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1);843 });984 });844}985}845986846#[test]987#[test]847fn transfer_from() {988fn transfer_from() {848 new_test_ext().execute_with(|| {989 new_test_ext().execute_with(|| {849 default_limits();990 default_limits();850 851 let collection_id = create_test_collection(&CollectionMode::NFT, 1);852 let origin1 = Origin::signed(1);853 let origin2 = Origin::signed(2);854991855 let data = default_nft_data();992 let collection_id = create_test_collection(&CollectionMode::NFT, 1);993 let origin1 = Origin::signed(1);856 create_test_item(collection_id, &data.into());994 let origin2 = Origin::signed(2);857995858 // approve996 let data = default_nft_data();859 assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1, 1));860 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1);997 create_test_item(collection_id, &data.into());861998862 assert_ok!(TemplateModule::set_mint_permission(999 // approve1000 assert_ok!(TemplateModule::approve(863 origin1.clone(),1001 origin1.clone(),864 1,865 true866 ));867 assert_ok!(TemplateModule::set_public_access_mode(1002 account(2),868 origin1.clone(),869 1,1003 1,870 AccessMode::WhiteList1004 1,1005 1871 ));1006 ));872 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));1007 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1);873 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));874 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 3));8751008876 assert_ok!(TemplateModule::transfer_from(1009 assert_ok!(TemplateModule::set_mint_permission(877 origin2.clone(),1010 origin1.clone(),878 1,1011 1,1012 true1013 ));1014 assert_ok!(TemplateModule::set_public_access_mode(879 2,1015 origin1.clone(),880 1,1016 1,1017 AccessMode::WhiteList1018 ));1019 assert_ok!(TemplateModule::add_to_white_list(1020 origin1.clone(),881 1,1021 1,882 11022 account(1)1023 ));1024 assert_ok!(TemplateModule::add_to_white_list(1025 origin1.clone(),1026 1,1027 account(2)1028 ));883 ));1029 assert_ok!(TemplateModule::add_to_white_list(origin1, 1, account(3)));88410301031 assert_ok!(TemplateModule::transfer_from(1032 origin2,1033 account(1),1034 account(2),1035 1,1036 1,1037 11038 ));1039885 // after transfer1040 // after transfer886 assert_eq!(TemplateModule::balance_count(1, 1), 0);1041 assert_eq!(TemplateModule::balance_count(1, 1), 0);887 assert_eq!(TemplateModule::balance_count(1, 2), 1);1042 assert_eq!(TemplateModule::balance_count(1, 2), 1);888 });1043 });889}1044}8901045891// #endregion1046// #endregion8951050896#[test]1051#[test]897fn owner_can_add_address_to_white_list() {1052fn owner_can_add_address_to_white_list() {898 new_test_ext().execute_with(|| {1053 new_test_ext().execute_with(|| {899 default_limits();1054 default_limits();900 901 let collection_id = create_test_collection(&CollectionMode::NFT, 1);9021055903 let origin1 = Origin::signed(1);1056 let collection_id = create_test_collection(&CollectionMode::NFT, 1);10571058 let origin1 = Origin::signed(1);904 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1059 assert_ok!(TemplateModule::add_to_white_list(1060 origin1,1061 collection_id,1062 account(2)1063 ));905 assert_eq!(TemplateModule::white_list(collection_id, 2), true);1064 assert!(TemplateModule::white_list(collection_id, 2));906 });1065 });907}1066}9081067909#[test]1068#[test]910fn admin_can_add_address_to_white_list() {1069fn admin_can_add_address_to_white_list() {911 new_test_ext().execute_with(|| {1070 new_test_ext().execute_with(|| {912 default_limits();1071 default_limits();913 914 let collection_id = create_test_collection(&CollectionMode::NFT, 1);915 let origin1 = Origin::signed(1);916 let origin2 = Origin::signed(2);9171072918 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection_id, 2));1073 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1074 let origin1 = Origin::signed(1);1075 let origin2 = Origin::signed(2);10761077 assert_ok!(TemplateModule::add_collection_admin(1078 origin1,1079 collection_id,1080 account(2)1081 ));919 assert_ok!(TemplateModule::add_to_white_list(origin2.clone(), collection_id, 3));1082 assert_ok!(TemplateModule::add_to_white_list(1083 origin2,1084 collection_id,1085 account(3)1086 ));920 assert_eq!(TemplateModule::white_list(collection_id, 3), true);1087 assert!(TemplateModule::white_list(collection_id, 3));921 });1088 });922}1089}9231090924#[test]1091#[test]925fn nonprivileged_user_cannot_add_address_to_white_list() {1092fn nonprivileged_user_cannot_add_address_to_white_list() {926 new_test_ext().execute_with(|| {1093 new_test_ext().execute_with(|| {927 default_limits();1094 default_limits();928 929 let collection_id = create_test_collection(&CollectionMode::NFT, 1);9301095931 let origin2 = Origin::signed(2);1096 let collection_id = create_test_collection(&CollectionMode::NFT, 1);10971098 let origin2 = Origin::signed(2);932 assert_noop!(1099 assert_noop!(933 TemplateModule::add_to_white_list(origin2.clone(), collection_id, 3),1100 TemplateModule::add_to_white_list(origin2, collection_id, account(3)),934 Error::<Test>::NoPermission1101 Error::<Test>::NoPermission935 );1102 );936 });1103 });937}1104}9381105939#[test]1106#[test]940fn nobody_can_add_address_to_white_list_of_nonexisting_collection() {1107fn nobody_can_add_address_to_white_list_of_nonexisting_collection() {941 new_test_ext().execute_with(|| {1108 new_test_ext().execute_with(|| {942 default_limits();1109 default_limits();9431110944 let origin1 = Origin::signed(1);1111 let origin1 = Origin::signed(1);9451112946 assert_noop!(1113 assert_noop!(947 TemplateModule::add_to_white_list(origin1.clone(), 1, 2),1114 TemplateModule::add_to_white_list(origin1, 1, account(2)),948 Error::<Test>::CollectionNotFound1115 Error::<Test>::CollectionNotFound949 );1116 );950 });1117 });951}1118}9521119953#[test]1120#[test]954fn nobody_can_add_address_to_white_list_of_deleted_collection() {1121fn nobody_can_add_address_to_white_list_of_deleted_collection() {955 new_test_ext().execute_with(|| {1122 new_test_ext().execute_with(|| {956 default_limits();1123 default_limits();957 958 let collection_id = create_test_collection(&CollectionMode::NFT, 1);9591124960 let origin1 = Origin::signed(1);1125 let collection_id = create_test_collection(&CollectionMode::NFT, 1);11261127 let origin1 = Origin::signed(1);961 assert_ok!(TemplateModule::destroy_collection(origin1.clone(), collection_id));1128 assert_ok!(TemplateModule::destroy_collection(1129 origin1.clone(),1130 collection_id1131 ));962 assert_noop!(1132 assert_noop!(963 TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2),1133 TemplateModule::add_to_white_list(origin1, collection_id, account(2)),964 Error::<Test>::CollectionNotFound1134 Error::<Test>::CollectionNotFound965 );1135 );966 });1136 });967}1137}9681138969// If address is already added to white list, nothing happens1139// If address is already added to white list, nothing happens970#[test]1140#[test]971fn address_is_already_added_to_white_list() {1141fn address_is_already_added_to_white_list() {972 new_test_ext().execute_with(|| {1142 new_test_ext().execute_with(|| {973 default_limits();1143 default_limits();974 1144975 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1145 let collection_id = create_test_collection(&CollectionMode::NFT, 1);976 let origin1 = Origin::signed(1);1146 let origin1 = Origin::signed(1);977 1147978 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1148 assert_ok!(TemplateModule::add_to_white_list(1149 origin1.clone(),1150 collection_id,1151 account(2)1152 ));979 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1153 assert_ok!(TemplateModule::add_to_white_list(1154 origin1,1155 collection_id,1156 account(2)1157 ));980 assert_eq!(TemplateModule::white_list(collection_id, 2), true);1158 assert!(TemplateModule::white_list(collection_id, 2));981 });1159 });982}1160}9831161984#[test]1162#[test]985fn owner_can_remove_address_from_white_list() {1163fn owner_can_remove_address_from_white_list() {986 new_test_ext().execute_with(|| {1164 new_test_ext().execute_with(|| {987 default_limits();1165 default_limits();988 989 let collection_id = create_test_collection(&CollectionMode::NFT, 1);9901166991 let origin1 = Origin::signed(1);1167 let collection_id = create_test_collection(&CollectionMode::NFT, 1);11681169 let origin1 = Origin::signed(1);992 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1170 assert_ok!(TemplateModule::add_to_white_list(1171 origin1.clone(),1172 collection_id,1173 account(2)1174 ));993 assert_ok!(TemplateModule::remove_from_white_list(1175 assert_ok!(TemplateModule::remove_from_white_list(994 origin1.clone(),1176 origin1,995 collection_id,1177 collection_id,996 21178 account(2)997 ));1179 ));998 assert_eq!(TemplateModule::white_list(collection_id, 2), false);1180 assert!(!TemplateModule::white_list(collection_id, 2));999 });1181 });1000}1182}100111831002#[test]1184#[test]1003fn admin_can_remove_address_from_white_list() {1185fn admin_can_remove_address_from_white_list() {1004 new_test_ext().execute_with(|| {1186 new_test_ext().execute_with(|| {1005 default_limits();1187 default_limits();1006 1007 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1008 let origin1 = Origin::signed(1);1009 let origin2 = Origin::signed(2);101011881011 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection_id, 2));1189 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1190 let origin1 = Origin::signed(1);1191 let origin2 = Origin::signed(2);101211921013 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 3));1193 assert_ok!(TemplateModule::add_collection_admin(1194 origin1.clone(),1195 collection_id,1196 account(2)1197 ));11981199 assert_ok!(TemplateModule::add_to_white_list(1200 origin1,1201 collection_id,1202 account(3)1203 ));1014 assert_ok!(TemplateModule::remove_from_white_list(1204 assert_ok!(TemplateModule::remove_from_white_list(1015 origin2.clone(),1205 origin2,1016 collection_id,1206 collection_id,1017 31207 account(3)1018 ));1208 ));1019 assert_eq!(TemplateModule::white_list(collection_id, 3), false);1209 assert!(!TemplateModule::white_list(collection_id, 3));1020 });1210 });1021}1211}102212121023#[test]1213#[test]1024fn nonprivileged_user_cannot_remove_address_from_white_list() {1214fn nonprivileged_user_cannot_remove_address_from_white_list() {1025 new_test_ext().execute_with(|| {1215 new_test_ext().execute_with(|| {1026 default_limits();1216 default_limits();1027 1028 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1029 let origin1 = Origin::signed(1);1030 let origin2 = Origin::signed(2);103112171032 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1218 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1219 let origin1 = Origin::signed(1);1220 let origin2 = Origin::signed(2);12211222 assert_ok!(TemplateModule::add_to_white_list(1223 origin1,1224 collection_id,1225 account(2)1226 ));1033 assert_noop!(1227 assert_noop!(1034 TemplateModule::remove_from_white_list(origin2.clone(), collection_id, 2),1228 TemplateModule::remove_from_white_list(origin2, collection_id, account(2)),1035 Error::<Test>::NoPermission1229 Error::<Test>::NoPermission1036 );1230 );1037 assert_eq!(TemplateModule::white_list(collection_id, 2), true);1231 assert!(TemplateModule::white_list(collection_id, 2));1038 });1232 });1039}1233}104012341041#[test]1235#[test]1042fn nobody_can_remove_address_from_white_list_of_nonexisting_collection() {1236fn nobody_can_remove_address_from_white_list_of_nonexisting_collection() {1043 new_test_ext().execute_with(|| {1237 new_test_ext().execute_with(|| {1044 default_limits();1238 default_limits();1045 let origin1 = Origin::signed(1);1239 let origin1 = Origin::signed(1);104612401047 assert_noop!(1241 assert_noop!(1048 TemplateModule::remove_from_white_list(origin1.clone(), 1, 2),1242 TemplateModule::remove_from_white_list(origin1, 1, account(2)),1049 Error::<Test>::CollectionNotFound1243 Error::<Test>::CollectionNotFound1050 );1244 );1051 });1245 });1052}1246}105312471054#[test]1248#[test]1055fn nobody_can_remove_address_from_white_list_of_deleted_collection() {1249fn nobody_can_remove_address_from_white_list_of_deleted_collection() {1056 new_test_ext().execute_with(|| {1250 new_test_ext().execute_with(|| {1057 default_limits();1251 default_limits();1058 1059 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1060 let origin1 = Origin::signed(1);1061 let origin2 = Origin::signed(2);106212521063 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1253 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1254 let origin1 = Origin::signed(1);1255 let origin2 = Origin::signed(2);12561257 assert_ok!(TemplateModule::add_to_white_list(1258 origin1.clone(),1259 collection_id,1260 account(2)1261 ));1064 assert_ok!(TemplateModule::destroy_collection(origin1.clone(), collection_id));1262 assert_ok!(TemplateModule::destroy_collection(origin1, collection_id));1065 assert_noop!(1263 assert_noop!(1066 TemplateModule::remove_from_white_list(origin2.clone(), collection_id, 2),1264 TemplateModule::remove_from_white_list(origin2, collection_id, account(2)),1067 Error::<Test>::CollectionNotFound1265 Error::<Test>::CollectionNotFound1068 );1266 );1069 assert_eq!(TemplateModule::white_list(collection_id, 2), false);1267 assert!(!TemplateModule::white_list(collection_id, 2));1070 });1268 });1071}1269}107212701073// If address is already removed from white list, nothing happens1271// If address is already removed from white list, nothing happens1074#[test]1272#[test]1075fn address_is_already_removed_from_white_list() {1273fn address_is_already_removed_from_white_list() {1076 new_test_ext().execute_with(|| {1274 new_test_ext().execute_with(|| {1077 default_limits();1275 default_limits();1078 1079 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1080 let origin1 = Origin::signed(1);108112761082 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1277 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1278 let origin1 = Origin::signed(1);12791280 assert_ok!(TemplateModule::add_to_white_list(1281 origin1.clone(),1282 collection_id,1283 account(2)1284 ));1083 assert_ok!(TemplateModule::remove_from_white_list(1285 assert_ok!(TemplateModule::remove_from_white_list(1084 origin1.clone(),1286 origin1.clone(),1085 collection_id,1287 collection_id,1086 21288 account(2)1087 ));1289 ));1088 assert_ok!(TemplateModule::remove_from_white_list(1290 assert_ok!(TemplateModule::remove_from_white_list(1089 origin1.clone(),1291 origin1,1090 collection_id,1292 collection_id,1091 21293 account(2)1092 ));1294 ));1093 assert_eq!(TemplateModule::white_list(collection_id, 2), false);1295 assert!(!TemplateModule::white_list(collection_id, 2));1094 });1296 });1095}1297}109612981097// If Public Access mode is set to WhiteList, tokens can’t be transferred from a non-whitelisted address with transfer or transferFrom (2 tests)1299// If Public Access mode is set to WhiteList, tokens can’t be transferred from a non-whitelisted address with transfer or transferFrom (2 tests)1098#[test]1300#[test]1099fn white_list_test_1() {1301fn white_list_test_1() {1100 new_test_ext().execute_with(|| {1302 new_test_ext().execute_with(|| {1101 default_limits();1303 default_limits();1102 1103 let collection_id = create_test_collection(&CollectionMode::NFT, 1);110413041105 let origin1 = Origin::signed(1);1305 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1106 1107 let data = default_nft_data();1108 create_test_item(collection_id, &data.into());110913061110 assert_ok!(TemplateModule::set_public_access_mode(1307 let origin1 = Origin::signed(1);1111 origin1.clone(),1112 collection_id,1113 AccessMode::WhiteList1114 ));1115 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));111613081117 assert_noop!(1309 let data = default_nft_data();1310 create_test_item(collection_id, &data.into());13111312 assert_ok!(TemplateModule::set_public_access_mode(1313 origin1.clone(),1314 collection_id,1315 AccessMode::WhiteList1316 ));1118 TemplateModule::transfer(origin1.clone(), 3, 1, 1, 1),1317 assert_ok!(TemplateModule::add_to_white_list(1318 origin1.clone(),1319 collection_id,1320 account(2)1321 ));13221323 assert_noop!(1324 TemplateModule::transfer(origin1, account(3), 1, 1, 1),1119 Error::<Test>::AddresNotInWhiteList1325 Error::<Test>::AddresNotInWhiteList1120 );1326 );1121 });1327 });1122}1328}112313291124#[test]1330#[test]1125fn white_list_test_2() {1331fn white_list_test_2() {1126 new_test_ext().execute_with(|| {1332 new_test_ext().execute_with(|| {1127 default_limits();1333 default_limits();1128 1129 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1130 let origin1 = Origin::signed(1);1131 1132 let data = default_nft_data();1133 create_test_item(collection_id, &data.into());113413341135 assert_ok!(TemplateModule::set_public_access_mode(1335 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1136 origin1.clone(),1137 collection_id,1138 AccessMode::WhiteList1139 ));1140 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));1141 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 2));1336 let origin1 = Origin::signed(1);114213371143 // do approve1338 let data = default_nft_data();1144 assert_ok!(TemplateModule::approve(origin1.clone(), 1, 1, 1, 1));1145 assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 1);1339 create_test_item(collection_id, &data.into());114613401147 assert_ok!(TemplateModule::remove_from_white_list(1341 assert_ok!(TemplateModule::set_public_access_mode(1148 origin1.clone(),1342 origin1.clone(),1343 collection_id,1344 AccessMode::WhiteList1345 ));1346 assert_ok!(TemplateModule::add_to_white_list(1347 origin1.clone(),1149 1,1348 1,1150 11349 account(1)1350 ));1351 assert_ok!(TemplateModule::add_to_white_list(1352 origin1.clone(),1353 1,1354 account(2)1151 ));1355 ));115213561153 assert_noop!(1357 // do approve1358 assert_ok!(TemplateModule::approve(1359 origin1.clone(),1360 account(1),1361 1,1362 1,1363 11364 ));1154 TemplateModule::transfer_from(origin1.clone(), 1, 3, 1, 1, 1),1365 assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 1);13661367 assert_ok!(TemplateModule::remove_from_white_list(1368 origin1.clone(),1369 1,1370 account(1)1371 ));13721373 assert_noop!(1374 TemplateModule::transfer_from(origin1, account(1), account(3), 1, 1, 1),1155 Error::<Test>::AddresNotInWhiteList1375 Error::<Test>::AddresNotInWhiteList1156 );1376 );1157 });1377 });1158}1378}115913791160// If Public Access mode is set to WhiteList, tokens can’t be transferred to a non-whitelisted address with transfer or transferFrom (2 tests)1380// If Public Access mode is set to WhiteList, tokens can’t be transferred to a non-whitelisted address with transfer or transferFrom (2 tests)1161#[test]1381#[test]1162fn white_list_test_3() {1382fn white_list_test_3() {1163 new_test_ext().execute_with(|| {1383 new_test_ext().execute_with(|| {1164 default_limits();1384 default_limits();1165 1166 let collection_id = create_test_collection(&CollectionMode::NFT, 1);116713851168 let origin1 = Origin::signed(1);1386 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1169 1170 let data = default_nft_data();1171 create_test_item(collection_id, &data.into());117213871173 assert_ok!(TemplateModule::set_public_access_mode(1388 let origin1 = Origin::signed(1);1174 origin1.clone(),1175 collection_id,1176 AccessMode::WhiteList1177 ));1178 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));117913891180 assert_noop!(1390 let data = default_nft_data();1391 create_test_item(collection_id, &data.into());13921393 assert_ok!(TemplateModule::set_public_access_mode(1394 origin1.clone(),1395 collection_id,1396 AccessMode::WhiteList1397 ));1181 TemplateModule::transfer(origin1.clone(), 3, 1, 1, 1),1398 assert_ok!(TemplateModule::add_to_white_list(1399 origin1.clone(),1400 1,1401 account(1)1402 ));14031404 assert_noop!(1405 TemplateModule::transfer(origin1, account(3), 1, 1, 1),1182 Error::<Test>::AddresNotInWhiteList1406 Error::<Test>::AddresNotInWhiteList1183 );1407 );1184 });1408 });1185}1409}118614101187#[test]1411#[test]1188fn white_list_test_4() {1412fn white_list_test_4() {1189 new_test_ext().execute_with(|| {1413 new_test_ext().execute_with(|| {1190 default_limits();1414 default_limits();1191 1192 let collection_id = create_test_collection(&CollectionMode::NFT, 1);119314151194 let origin1 = Origin::signed(1);1416 let collection_id = create_test_collection(&CollectionMode::NFT, 1);119514171196 let data = default_nft_data();1418 let origin1 = Origin::signed(1);1197 create_test_item(collection_id, &data.into());119814191199 assert_ok!(TemplateModule::set_public_access_mode(1420 let data = default_nft_data();1200 origin1.clone(),1201 collection_id,1202 AccessMode::WhiteList1203 ));1204 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 1));1421 create_test_item(collection_id, &data.into());1205 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));120614221207 // do approve1208 assert_ok!(TemplateModule::approve(origin1.clone(), 1, 1, 1, 1));1423 assert_ok!(TemplateModule::set_public_access_mode(1424 origin1.clone(),1425 collection_id,1426 AccessMode::WhiteList1427 ));1428 assert_ok!(TemplateModule::add_to_white_list(1429 origin1.clone(),1430 collection_id,1431 account(1)1432 ));1209 assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 1);1433 assert_ok!(TemplateModule::add_to_white_list(1434 origin1.clone(),1435 collection_id,1436 account(2)1437 ));121014381211 assert_ok!(TemplateModule::remove_from_white_list(1439 // do approve1440 assert_ok!(TemplateModule::approve(1212 origin1.clone(),1441 origin1.clone(),1213 collection_id,1442 account(1),1214 21443 1,1444 1,1445 11446 ));1215 ));1447 assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 1);121614481217 assert_noop!(1449 assert_ok!(TemplateModule::remove_from_white_list(1218 TemplateModule::transfer_from(origin1.clone(), 1, 3, 1, 1, 1),1450 origin1.clone(),1451 collection_id,1452 account(2)1453 ));14541455 assert_noop!(1456 TemplateModule::transfer_from(origin1, account(1), account(3), 1, 1, 1),1219 Error::<Test>::AddresNotInWhiteList1457 Error::<Test>::AddresNotInWhiteList1220 );1458 );1221 });1459 });1222}1460}122314611224// If Public Access mode is set to WhiteList, tokens can’t be destroyed by a non-whitelisted address (even if it owned them before enabling WhiteList mode)1462// If Public Access mode is set to WhiteList, tokens can’t be destroyed by a non-whitelisted address (even if it owned them before enabling WhiteList mode)1225#[test]1463#[test]1226fn white_list_test_5() {1464fn white_list_test_5() {1227 new_test_ext().execute_with(|| {1465 new_test_ext().execute_with(|| {1228 default_limits();1466 default_limits();1229 1230 let collection_id = create_test_collection(&CollectionMode::NFT, 1);123114671232 let origin1 = Origin::signed(1);1468 let collection_id = create_test_collection(&CollectionMode::NFT, 1);123314691234 let data = default_nft_data();1470 let origin1 = Origin::signed(1);1235 create_test_item(collection_id, &data.into());123614711237 assert_ok!(TemplateModule::set_public_access_mode(1472 let data = default_nft_data();1473 create_test_item(collection_id, &data.into());14741475 assert_ok!(TemplateModule::set_public_access_mode(1238 origin1.clone(),1476 origin1.clone(),1239 collection_id,1477 collection_id,1240 AccessMode::WhiteList1478 AccessMode::WhiteList1241 ));1479 ));1242 assert_noop!(1480 assert_noop!(1243 TemplateModule::burn_item(origin1.clone(), 1, 1, 5),1481 TemplateModule::burn_item(origin1, 1, 1, 5),1244 Error::<Test>::AddresNotInWhiteList1482 Error::<Test>::AddresNotInWhiteList1245 );1483 );1246 });1484 });1247}1485}124814861249// If Public Access mode is set to WhiteList, token transfers can’t be Approved by a non-whitelisted address (see Approve method).1487// If Public Access mode is set to WhiteList, token transfers can’t be Approved by a non-whitelisted address (see Approve method).1250#[test]1488#[test]1251fn white_list_test_6() {1489fn white_list_test_6() {1252 new_test_ext().execute_with(|| {1490 new_test_ext().execute_with(|| {1253 default_limits();1491 default_limits();1254 1255 let collection_id = create_test_collection(&CollectionMode::NFT, 1);125614921257 let origin1 = Origin::signed(1);1493 let collection_id = create_test_collection(&CollectionMode::NFT, 1);125814941259 let data = default_nft_data();1495 let origin1 = Origin::signed(1);1260 create_test_item(collection_id, &data.into());126114961262 assert_ok!(TemplateModule::set_public_access_mode(1497 let data = default_nft_data();1263 origin1.clone(),1264 collection_id,1498 create_test_item(collection_id, &data.into());1265 AccessMode::WhiteList1266 ));126714991500 assert_ok!(TemplateModule::set_public_access_mode(1501 origin1.clone(),1502 collection_id,1503 AccessMode::WhiteList1504 ));15051268 // do approve1506 // do approve1269 assert_noop!(1507 assert_noop!(1270 TemplateModule::approve(origin1.clone(), 1, 1, 1, 5),1508 TemplateModule::approve(origin1, account(1), 1, 1, 5),1271 Error::<Test>::AddresNotInWhiteList1509 Error::<Test>::AddresNotInWhiteList1272 );1510 );1273 });1511 });1274}1512}127515131276// If Public Access mode is set to WhiteList, tokens can be transferred from a whitelisted address with transfer or transferFrom (2 tests) and1514// If Public Access mode is set to WhiteList, tokens can be transferred from a whitelisted address with transfer or transferFrom (2 tests) and1277// tokens can be transferred from a whitelisted address with transfer or transferFrom (2 tests)1515// tokens can be transferred from a whitelisted address with transfer or transferFrom (2 tests)1278#[test]1516#[test]1279fn white_list_test_7() {1517fn white_list_test_7() {1280 new_test_ext().execute_with(|| {1518 new_test_ext().execute_with(|| {1281 default_limits();1519 default_limits();1282 1283 let collection_id = create_test_collection(&CollectionMode::NFT, 1);128415201285 let data = default_nft_data();1521 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1286 create_test_item(collection_id, &data.into());1287 1288 let origin1 = Origin::signed(1);128915221290 assert_ok!(TemplateModule::set_public_access_mode(1523 let data = default_nft_data();1291 origin1.clone(),1292 collection_id,1293 AccessMode::WhiteList1294 ));1295 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 1));1524 create_test_item(collection_id, &data.into());1296 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));129715251298 assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1));1526 let origin1 = Origin::signed(1);15271528 assert_ok!(TemplateModule::set_public_access_mode(1529 origin1.clone(),1530 collection_id,1531 AccessMode::WhiteList1532 ));1533 assert_ok!(TemplateModule::add_to_white_list(1534 origin1.clone(),1535 collection_id,1536 account(1)1537 ));1538 assert_ok!(TemplateModule::add_to_white_list(1539 origin1.clone(),1540 collection_id,1541 account(2)1542 ));15431544 assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 1));1299 });1545 });1300}1546}130115471302#[test]1548#[test]1303fn white_list_test_8() {1549fn white_list_test_8() {1304 new_test_ext().execute_with(|| {1550 new_test_ext().execute_with(|| {1305 default_limits();1551 default_limits();1306 1307 let collection_id = create_test_collection(&CollectionMode::NFT, 1);130815521309 let data = default_nft_data();1553 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1310 create_test_item(collection_id, &data.into());1311 1312 let origin1 = Origin::signed(1);131315541314 assert_ok!(TemplateModule::set_public_access_mode(1555 let data = default_nft_data();1315 origin1.clone(),1316 collection_id,1317 AccessMode::WhiteList1318 ));1319 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 1));1556 create_test_item(collection_id, &data.into());1320 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));132115571322 // do approve1558 let origin1 = Origin::signed(1);1323 assert_ok!(TemplateModule::approve(origin1.clone(), 1, 1, 1, 5));1324 assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 5);132515591560 assert_ok!(TemplateModule::set_public_access_mode(1561 origin1.clone(),1562 collection_id,1563 AccessMode::WhiteList1564 ));1565 assert_ok!(TemplateModule::add_to_white_list(1566 origin1.clone(),1567 collection_id,1568 account(1)1569 ));1570 assert_ok!(TemplateModule::add_to_white_list(1571 origin1.clone(),1572 collection_id,1573 account(2)1574 ));15751326 assert_ok!(TemplateModule::transfer_from(1576 // do approve1577 assert_ok!(TemplateModule::approve(1327 origin1.clone(),1578 origin1.clone(),1579 account(1),1580 1,1581 1,1582 51583 ));1328 1,1584 assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 5);15851586 assert_ok!(TemplateModule::transfer_from(1587 origin1,1588 account(1),1329 2,1589 account(2),1330 1,1590 1,1331 1,1591 1,1332 11592 11333 ));1593 ));1334 });1594 });1335}1595}133615961337// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens can be created by owner.1597// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens can be created by owner.1338#[test]1598#[test]1339fn white_list_test_9() {1599fn white_list_test_9() {1340 new_test_ext().execute_with(|| {1600 new_test_ext().execute_with(|| {1341 default_limits();1601 default_limits();1342 1343 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1344 let origin1 = Origin::signed(1);134516021346 assert_ok!(TemplateModule::set_public_access_mode(1603 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1347 origin1.clone(),1348 collection_id,1349 AccessMode::WhiteList1350 ));1351 assert_ok!(TemplateModule::set_mint_permission(1604 let origin1 = Origin::signed(1);1352 origin1.clone(),1353 collection_id,1354 false1355 ));135616051606 assert_ok!(TemplateModule::set_public_access_mode(1607 origin1.clone(),1608 collection_id,1609 AccessMode::WhiteList1610 ));1611 assert_ok!(TemplateModule::set_mint_permission(1612 origin1,1613 collection_id,1614 false1615 ));16161357 let data = default_nft_data();1617 let data = default_nft_data();1358 create_test_item(collection_id, &data.into());1618 create_test_item(collection_id, &data.into());1359 });1619 });1360}1620}136116211362// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens can be created by admin.1622// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens can be created by admin.1363#[test]1623#[test]1364fn white_list_test_10() {1624fn white_list_test_10() {1365 new_test_ext().execute_with(|| {1625 new_test_ext().execute_with(|| {1366 default_limits();1626 default_limits();1367 1368 let collection_id = create_test_collection(&CollectionMode::NFT, 1);136916271370 let origin1 = Origin::signed(1);1628 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1371 let origin2 = Origin::signed(2);137216291373 assert_ok!(TemplateModule::set_public_access_mode(1630 let origin1 = Origin::signed(1);1374 origin1.clone(),1375 collection_id,1376 AccessMode::WhiteList1377 ));1378 assert_ok!(TemplateModule::set_mint_permission(1631 let origin2 = Origin::signed(2);1379 origin1.clone(),1380 collection_id,1381 false1382 ));138316321384 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection_id, 2));1633 assert_ok!(TemplateModule::set_public_access_mode(1634 origin1.clone(),1635 collection_id,1636 AccessMode::WhiteList1637 ));1638 assert_ok!(TemplateModule::set_mint_permission(1639 origin1.clone(),1640 collection_id,1641 false1642 ));138516431386 assert_ok!(TemplateModule::create_item(1644 assert_ok!(TemplateModule::add_collection_admin(1645 origin1,1646 collection_id,1647 account(2)1648 ));16491650 assert_ok!(TemplateModule::create_item(1387 origin2.clone(),1651 origin2,1388 collection_id,1652 collection_id,1389 2,1653 account(2),1390 default_nft_data().into()1654 default_nft_data().into()1391 ));1655 ));1392 });1656 });1393}1657}139416581395// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens cannot be created by non-privileged and white listed address.1659// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens cannot be created by non-privileged and white listed address.1396#[test]1660#[test]1397fn white_list_test_11() {1661fn white_list_test_11() {1398 new_test_ext().execute_with(|| {1662 new_test_ext().execute_with(|| {1399 default_limits();1663 default_limits();1400 1401 let collection_id = create_test_collection(&CollectionMode::NFT, 1);140216641403 let origin1 = Origin::signed(1);1665 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1404 let origin2 = Origin::signed(2);140516661406 assert_ok!(TemplateModule::set_public_access_mode(1667 let origin1 = Origin::signed(1);1407 origin1.clone(),1408 collection_id,1409 AccessMode::WhiteList1410 ));1411 assert_ok!(TemplateModule::set_mint_permission(1412 origin1.clone(),1413 collection_id,1414 false1415 ));1416 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1668 let origin2 = Origin::signed(2);141716691418 assert_noop!(1670 assert_ok!(TemplateModule::set_public_access_mode(1671 origin1.clone(),1672 collection_id,1673 AccessMode::WhiteList1674 ));1419 TemplateModule::create_item(origin2.clone(), 1, 2, default_nft_data().into()),1675 assert_ok!(TemplateModule::set_mint_permission(1676 origin1.clone(),1677 collection_id,1678 false1679 ));1680 assert_ok!(TemplateModule::add_to_white_list(1681 origin1,1682 collection_id,1683 account(2)1684 ));16851686 assert_noop!(1687 TemplateModule::create_item(origin2, 1, account(2), default_nft_data().into()),1420 Error::<Test>::PublicMintingNotAllowed1688 Error::<Test>::PublicMintingNotAllowed1421 );1689 );1422 });1690 });1423}1691}142416921425// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens cannot be created by non-privileged and non-white listed address.1693// If Public Access mode is set to WhiteList, and Mint Permission is set to false, tokens cannot be created by non-privileged and non-white listed address.1426#[test]1694#[test]1427fn white_list_test_12() {1695fn white_list_test_12() {1428 new_test_ext().execute_with(|| {1696 new_test_ext().execute_with(|| {1429 default_limits();1697 default_limits();1430 1431 let collection_id = create_test_collection(&CollectionMode::NFT, 1);143216981433 let origin1 = Origin::signed(1);1699 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1434 let origin2 = Origin::signed(2);143517001436 assert_ok!(TemplateModule::set_public_access_mode(1701 let origin1 = Origin::signed(1);1437 origin1.clone(),1438 collection_id,1439 AccessMode::WhiteList1440 ));1441 assert_ok!(TemplateModule::set_mint_permission(1702 let origin2 = Origin::signed(2);1442 origin1.clone(),1443 collection_id,1444 false1445 ));144617031447 assert_noop!(1704 assert_ok!(TemplateModule::set_public_access_mode(1448 TemplateModule::create_item(origin2.clone(), 1, 2, default_nft_data().into()),1705 origin1.clone(),1706 collection_id,1707 AccessMode::WhiteList1708 ));1709 assert_ok!(TemplateModule::set_mint_permission(1710 origin1,1711 collection_id,1712 false1713 ));17141715 assert_noop!(1716 TemplateModule::create_item(origin2, 1, account(2), default_nft_data().into()),1449 Error::<Test>::PublicMintingNotAllowed1717 Error::<Test>::PublicMintingNotAllowed1450 );1718 );1451 });1719 });1452}1720}145317211454// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by owner.1722// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by owner.1455#[test]1723#[test]1456fn white_list_test_13() {1724fn white_list_test_13() {1457 new_test_ext().execute_with(|| {1725 new_test_ext().execute_with(|| {1458 default_limits();1726 default_limits();1459 1460 let collection_id = create_test_collection(&CollectionMode::NFT, 1);146117271462 let origin1 = Origin::signed(1);1728 let collection_id = create_test_collection(&CollectionMode::NFT, 1);146317291464 assert_ok!(TemplateModule::set_public_access_mode(1730 let origin1 = Origin::signed(1);1465 origin1.clone(),1466 collection_id,1467 AccessMode::WhiteList1468 ));1469 assert_ok!(TemplateModule::set_mint_permission(1470 origin1.clone(),1471 collection_id,1472 true1473 ));147417311732 assert_ok!(TemplateModule::set_public_access_mode(1733 origin1.clone(),1734 collection_id,1735 AccessMode::WhiteList1736 ));1737 assert_ok!(TemplateModule::set_mint_permission(1738 origin1,1739 collection_id,1740 true1741 ));17421475 let data = default_nft_data();1743 let data = default_nft_data();1476 create_test_item(collection_id, &data.into());1744 create_test_item(collection_id, &data.into());1477 });1745 });1478}1746}147917471480// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by admin.1748// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by admin.1481#[test]1749#[test]1482fn white_list_test_14() {1750fn white_list_test_14() {1483 new_test_ext().execute_with(|| {1751 new_test_ext().execute_with(|| {1484 default_limits();1752 default_limits();1485 1486 let collection_id = create_test_collection(&CollectionMode::NFT, 1);148717531488 let origin1 = Origin::signed(1);1754 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1489 let origin2 = Origin::signed(2);149017551491 assert_ok!(TemplateModule::set_public_access_mode(1756 let origin1 = Origin::signed(1);1492 origin1.clone(),1493 collection_id,1494 AccessMode::WhiteList1495 ));1496 assert_ok!(TemplateModule::set_mint_permission(1757 let origin2 = Origin::signed(2);1497 origin1.clone(),1498 collection_id,1499 true1500 ));150117581502 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection_id, 2));1759 assert_ok!(TemplateModule::set_public_access_mode(1760 origin1.clone(),1761 collection_id,1762 AccessMode::WhiteList1763 ));1764 assert_ok!(TemplateModule::set_mint_permission(1765 origin1.clone(),1766 collection_id,1767 true1768 ));150317691504 assert_ok!(TemplateModule::create_item(1770 assert_ok!(TemplateModule::add_collection_admin(1771 origin1,1772 collection_id,1773 account(2)1774 ));17751776 assert_ok!(TemplateModule::create_item(1505 origin2.clone(),1777 origin2,1506 1,1778 1,1507 2,1779 account(2),1508 default_nft_data().into()1780 default_nft_data().into()1509 ));1781 ));1510 });1782 });1511}1783}151217841513// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens cannot be created by non-privileged and non-white listed address.1785// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens cannot be created by non-privileged and non-white listed address.1514#[test]1786#[test]1515fn white_list_test_15() {1787fn white_list_test_15() {1516 new_test_ext().execute_with(|| {1788 new_test_ext().execute_with(|| {1517 default_limits();1789 default_limits();1518 1519 let collection_id = create_test_collection(&CollectionMode::NFT, 1);152017901521 let origin1 = Origin::signed(1);1791 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1522 let origin2 = Origin::signed(2);152317921524 assert_ok!(TemplateModule::set_public_access_mode(1793 let origin1 = Origin::signed(1);1525 origin1.clone(),1526 collection_id,1527 AccessMode::WhiteList1528 ));1529 assert_ok!(TemplateModule::set_mint_permission(1794 let origin2 = Origin::signed(2);1530 origin1.clone(),1531 collection_id,1532 true1533 ));153417951535 assert_noop!(1796 assert_ok!(TemplateModule::set_public_access_mode(1536 TemplateModule::create_item(origin2.clone(), 1, 2, default_nft_data().into()),1797 origin1.clone(),1798 collection_id,1799 AccessMode::WhiteList1800 ));1801 assert_ok!(TemplateModule::set_mint_permission(1802 origin1,1803 collection_id,1804 true1805 ));18061807 assert_noop!(1808 TemplateModule::create_item(origin2, 1, account(2), default_nft_data().into()),1537 Error::<Test>::AddresNotInWhiteList1809 Error::<Test>::AddresNotInWhiteList1538 );1810 );1539 });1811 });1540}1812}154118131542// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by non-privileged and white listed address.1814// If Public Access mode is set to WhiteList, and Mint Permission is set to true, tokens can be created by non-privileged and white listed address.1543#[test]1815#[test]1544fn white_list_test_16() {1816fn white_list_test_16() {1545 new_test_ext().execute_with(|| {1817 new_test_ext().execute_with(|| {1546 default_limits();1818 default_limits();1547 1548 let collection_id = create_test_collection(&CollectionMode::NFT, 1);154918191550 let origin1 = Origin::signed(1);1820 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1551 let origin2 = Origin::signed(2);155218211553 assert_ok!(TemplateModule::set_public_access_mode(1822 let origin1 = Origin::signed(1);1554 origin1.clone(),1555 collection_id,1556 AccessMode::WhiteList1557 ));1558 assert_ok!(TemplateModule::set_mint_permission(1559 origin1.clone(),1560 collection_id,1561 true1562 ));1563 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1823 let origin2 = Origin::signed(2);156418241565 assert_ok!(TemplateModule::create_item(1825 assert_ok!(TemplateModule::set_public_access_mode(1566 origin2.clone(),1826 origin1.clone(),1827 collection_id,1828 AccessMode::WhiteList1829 ));1830 assert_ok!(TemplateModule::set_mint_permission(1831 origin1.clone(),1832 collection_id,1833 true1834 ));1835 assert_ok!(TemplateModule::add_to_white_list(1836 origin1,1837 collection_id,1838 account(2)1839 ));18401841 assert_ok!(TemplateModule::create_item(1842 origin2,1567 1,1843 1,1568 2,1844 account(2),1569 default_nft_data().into()1845 default_nft_data().into()1570 ));1846 ));1571 });1847 });1572}1848}157318491574// Total number of collections. Positive test1850// Total number of collections. Positive test1575#[test]1851#[test]1576fn total_number_collections_bound() {1852fn total_number_collections_bound() {1577 new_test_ext().execute_with(|| {1853 new_test_ext().execute_with(|| {1578 default_limits();1854 default_limits();1579 18551580 create_test_collection(&CollectionMode::NFT, 1);1856 create_test_collection(&CollectionMode::NFT, 1);1581 });1857 });1582}1858}158318591584// Total number of collections. Negotive test1860// Total number of collections. Negotive test1585#[test]1861#[test]1586fn total_number_collections_bound_neg() {1862fn total_number_collections_bound_neg() {1587 new_test_ext().execute_with(|| {1863 new_test_ext().execute_with(|| {1588 default_limits();1864 default_limits();158918651590 let origin1 = Origin::signed(1);1866 let origin1 = Origin::signed(1);159118671592 for i in 0..default_collection_numbers_limit() {1868 for i in 0..default_collection_numbers_limit() {1593 create_test_collection(&CollectionMode::NFT, i + 1);1869 create_test_collection(&CollectionMode::NFT, i + 1);1594 }1870 }159518711596 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();1872 let col_name1: Vec<u16> = "Test1\0".encode_utf16().collect::<Vec<u16>>();1597 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();1873 let col_desc1: Vec<u16> = "TestDescription1\0".encode_utf16().collect::<Vec<u16>>();1598 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();1874 let token_prefix1: Vec<u8> = b"token_prefix1\0".to_vec();159918751600 // 11-th collection in chain. Expects error1876 // 11-th collection in chain. Expects error1601 assert_noop!(TemplateModule::create_collection(1877 assert_noop!(1878 TemplateModule::create_collection(1602 origin1.clone(),1879 origin1,1603 col_name1.clone(),1880 col_name1,1604 col_desc1.clone(),1881 col_desc1,1605 token_prefix1.clone(),1882 token_prefix1,1606 CollectionMode::NFT1883 CollectionMode::NFT1607 ), Error::<Test>::TotalCollectionsLimitExceeded);1884 ),1885 Error::<Test>::TotalCollectionsLimitExceeded1886 );1608 });1887 });1609}1888}161018891611// Owned tokens by a single address. Positive test1890// Owned tokens by a single address. Positive test1612#[test]1891#[test]1613fn owned_tokens_bound() {1892fn owned_tokens_bound() {1614 new_test_ext().execute_with(|| {1893 new_test_ext().execute_with(|| {1615 default_limits();1894 default_limits();1616 1617 let collection_id = create_test_collection(&CollectionMode::NFT, 1);161818951619 let data = default_nft_data();1896 let collection_id = create_test_collection(&CollectionMode::NFT, 1);18971898 let data = default_nft_data();1620 create_test_item(collection_id, &data.clone().into());1899 create_test_item(collection_id, &data.clone().into());1621 create_test_item(collection_id, &data.into());1900 create_test_item(collection_id, &data.into());1622 });1901 });1623}1902}162419031625// Owned tokens by a single address. Negotive test1904// Owned tokens by a single address. Negotive test1626#[test]1905#[test]1627fn owned_tokens_bound_neg() {1906fn owned_tokens_bound_neg() {1628 new_test_ext().execute_with(|| {1907 new_test_ext().execute_with(|| {1629 assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits { 1908 assert_ok!(TemplateModule::set_chain_limits(1909 RawOrigin::Root.into(),1910 ChainLimits {1630 collection_numbers_limit: 10,1911 collection_numbers_limit: 10,1631 account_token_ownership_limit: 1,1912 account_token_ownership_limit: 1,1632 collections_admins_limit: 5,1913 collections_admins_limit: 5,1633 custom_data_limit: 2048,1914 custom_data_limit: 2048,1634 nft_sponsor_transfer_timeout: 15,1915 nft_sponsor_transfer_timeout: 15,1635 fungible_sponsor_transfer_timeout: 15,1916 fungible_sponsor_transfer_timeout: 15,1636 refungible_sponsor_transfer_timeout: 15,1917 refungible_sponsor_transfer_timeout: 15,1637 const_on_chain_schema_limit: 1024,1918 const_on_chain_schema_limit: 1024,1638 offchain_schema_limit: 1024,1919 offchain_schema_limit: 1024,1639 variable_on_chain_schema_limit: 1024,1920 variable_on_chain_schema_limit: 1024,1640 }));1921 }1641 1642 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1922 ));164319231644 let origin1 = Origin::signed(1);1924 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1645 let data = default_nft_data();1646 create_test_item(collection_id, &data.clone().into());164719251648 assert_noop!(TemplateModule::create_item(1926 let origin1 = Origin::signed(1);1927 let data = default_nft_data();1928 create_test_item(collection_id, &data.clone().into());19291930 assert_noop!(1649 origin1.clone(),1931 TemplateModule::create_item(origin1, 1, account(1), data.into()),1650 1,1651 1,1652 data.into()1653 ), Error::<Test>::AddressOwnershipLimitExceeded);1932 Error::<Test>::AddressOwnershipLimitExceeded1933 );1654 });1934 });1655}1935}165619361657// Number of collection admins. Positive test1937// Number of collection admins. Positive test1658#[test]1938#[test]1659fn collection_admins_bound() {1939fn collection_admins_bound() {1660 new_test_ext().execute_with(|| {1940 new_test_ext().execute_with(|| {1661 assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits { 1941 assert_ok!(TemplateModule::set_chain_limits(1942 RawOrigin::Root.into(),1943 ChainLimits {1662 collection_numbers_limit: 10,1944 collection_numbers_limit: 10,1663 account_token_ownership_limit: 10,1945 account_token_ownership_limit: 10,1664 collections_admins_limit: 2,1946 collections_admins_limit: 2,1665 custom_data_limit: 2048,1947 custom_data_limit: 2048,1666 nft_sponsor_transfer_timeout: 15,1948 nft_sponsor_transfer_timeout: 15,1667 fungible_sponsor_transfer_timeout: 15,1949 fungible_sponsor_transfer_timeout: 15,1668 refungible_sponsor_transfer_timeout: 15,1950 refungible_sponsor_transfer_timeout: 15,1669 const_on_chain_schema_limit: 1024,1951 const_on_chain_schema_limit: 1024,1670 offchain_schema_limit: 1024,1952 offchain_schema_limit: 1024,1671 variable_on_chain_schema_limit: 1024,1953 variable_on_chain_schema_limit: 1024,1672 }));1954 }1673 1674 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1955 ));167519561676 let origin1 = Origin::signed(1);1957 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1677 19581959 let origin1 = Origin::signed(1);19601678 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection_id, 2));1961 assert_ok!(TemplateModule::add_collection_admin(1962 origin1.clone(),1963 collection_id,1964 account(2)1965 ));1679 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection_id, 3));1966 assert_ok!(TemplateModule::add_collection_admin(1967 origin1,1968 collection_id,1969 account(3)1970 ));1680 });1971 });1681}1972}168219731683// Number of collection admins. Negotive test1974// Number of collection admins. Negotive test1684#[test]1975#[test]1685fn collection_admins_bound_neg() {1976fn collection_admins_bound_neg() {1686 new_test_ext().execute_with(|| {1977 new_test_ext().execute_with(|| {1687 assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits { 1978 assert_ok!(TemplateModule::set_chain_limits(1979 RawOrigin::Root.into(),1980 ChainLimits {1688 collection_numbers_limit: 10,1981 collection_numbers_limit: 10,1689 account_token_ownership_limit: 1,1982 account_token_ownership_limit: 1,1690 collections_admins_limit: 1,1983 collections_admins_limit: 1,1691 custom_data_limit: 2048,1984 custom_data_limit: 2048,1692 nft_sponsor_transfer_timeout: 15,1985 nft_sponsor_transfer_timeout: 15,1693 fungible_sponsor_transfer_timeout: 15,1986 fungible_sponsor_transfer_timeout: 15,1694 refungible_sponsor_transfer_timeout: 15,1987 refungible_sponsor_transfer_timeout: 15,1695 const_on_chain_schema_limit: 1024,1988 const_on_chain_schema_limit: 1024,1696 offchain_schema_limit: 1024,1989 offchain_schema_limit: 1024,1697 variable_on_chain_schema_limit: 1024,1990 variable_on_chain_schema_limit: 1024,1698 }));1991 }1699 1700 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1992 ));170119931702 let origin1 = Origin::signed(1);1994 let collection_id = create_test_collection(&CollectionMode::NFT, 1);170319951704 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection_id, 2));1996 let origin1 = Origin::signed(1);19971998 assert_ok!(TemplateModule::add_collection_admin(1999 origin1.clone(),2000 collection_id,2001 account(2)2002 ));1705 assert_noop!(TemplateModule::add_collection_admin(origin1.clone(), collection_id, 3), Error::<Test>::CollectionAdminsLimitExceeded);2003 assert_noop!(2004 TemplateModule::add_collection_admin(origin1, collection_id, account(3)),2005 Error::<Test>::CollectionAdminsLimitExceeded2006 );1706 });2007 });1707}2008}170820091709// NFT custom data size. Negative test const_data.2010// NFT custom data size. Negative test const_data.1710#[test]2011#[test]1711fn custom_data_size_nft_const_data_bound_neg() {2012fn custom_data_size_nft_const_data_bound_neg() {1712 new_test_ext().execute_with(|| {2013 new_test_ext().execute_with(|| {1713 assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits { 2014 assert_ok!(TemplateModule::set_chain_limits(2015 RawOrigin::Root.into(),2016 ChainLimits {1714 collection_numbers_limit: 10,2017 collection_numbers_limit: 10,1715 account_token_ownership_limit: 10,2018 account_token_ownership_limit: 10,1716 collections_admins_limit: 5,2019 collections_admins_limit: 5,1717 custom_data_limit: 2,2020 custom_data_limit: 2,1718 nft_sponsor_transfer_timeout: 15,2021 nft_sponsor_transfer_timeout: 15,1719 fungible_sponsor_transfer_timeout: 15,2022 fungible_sponsor_transfer_timeout: 15,1720 refungible_sponsor_transfer_timeout: 15,2023 refungible_sponsor_transfer_timeout: 15,1721 const_on_chain_schema_limit: 1024,2024 const_on_chain_schema_limit: 1024,1722 offchain_schema_limit: 1024,2025 offchain_schema_limit: 1024,1723 variable_on_chain_schema_limit: 1024,2026 variable_on_chain_schema_limit: 1024,1724 }));2027 }1725 1726 let collection_id = create_test_collection(&CollectionMode::NFT, 1);2028 ));172720291728 let origin1 = Origin::signed(1);2030 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1729 let too_big_const_data = CreateItemData::NFT(CreateNftData{1730 const_data: vec![1, 2, 3, 4],1731 variable_data: vec![]1732 });173320311734 assert_noop!(TemplateModule::create_item(2032 let origin1 = Origin::signed(1);1735 origin1.clone(),2033 let too_big_const_data = CreateItemData::NFT(CreateNftData {2034 const_data: vec![1, 2, 3, 4],2035 variable_data: vec![],2036 });20372038 assert_noop!(1736 collection_id,2039 TemplateModule::create_item(origin1, collection_id, account(1), too_big_const_data),1737 1,1738 too_big_const_data1739 ), Error::<Test>::TokenConstDataLimitExceeded);2040 Error::<Test>::TokenConstDataLimitExceeded2041 );1740 });2042 });1741}2043}174220441743// NFT custom data size. Negative test variable_data.2045// NFT custom data size. Negative test variable_data.1744#[test]2046#[test]1745fn custom_data_size_nft_variable_data_bound_neg() {2047fn custom_data_size_nft_variable_data_bound_neg() {1746 new_test_ext().execute_with(|| {2048 new_test_ext().execute_with(|| {1747 assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits { 2049 assert_ok!(TemplateModule::set_chain_limits(2050 RawOrigin::Root.into(),2051 ChainLimits {1748 collection_numbers_limit: 10,2052 collection_numbers_limit: 10,1749 account_token_ownership_limit: 10,2053 account_token_ownership_limit: 10,1750 collections_admins_limit: 5,2054 collections_admins_limit: 5,1751 custom_data_limit: 2,2055 custom_data_limit: 2,1752 nft_sponsor_transfer_timeout: 15,2056 nft_sponsor_transfer_timeout: 15,1753 fungible_sponsor_transfer_timeout: 15,2057 fungible_sponsor_transfer_timeout: 15,1754 refungible_sponsor_transfer_timeout: 15,2058 refungible_sponsor_transfer_timeout: 15,1755 const_on_chain_schema_limit: 1024,2059 const_on_chain_schema_limit: 1024,1756 offchain_schema_limit: 1024,2060 offchain_schema_limit: 1024,1757 variable_on_chain_schema_limit: 1024,2061 variable_on_chain_schema_limit: 1024,1758 }));2062 }2063 ));175920641760 let collection_id = create_test_collection(&CollectionMode::NFT, 1);2065 let collection_id = create_test_collection(&CollectionMode::NFT, 1);176120661762 let origin1 = Origin::signed(1);2067 let origin1 = Origin::signed(1);1763 let too_big_const_data = CreateItemData::NFT(CreateNftData{2068 let too_big_const_data = CreateItemData::NFT(CreateNftData {1764 const_data: vec![],2069 const_data: vec![],1765 variable_data: vec![1, 2, 3, 4]2070 variable_data: vec![1, 2, 3, 4],1766 });2071 });176720721768 assert_noop!(TemplateModule::create_item(2073 assert_noop!(1769 origin1.clone(),2074 TemplateModule::create_item(origin1, collection_id, account(1), too_big_const_data),1770 collection_id,1771 1,1772 too_big_const_data1773 ), Error::<Test>::TokenVariableDataLimitExceeded);2075 Error::<Test>::TokenVariableDataLimitExceeded2076 );1774 });2077 });1775}2078}177620791777// Re fungible custom data size. Negative test const_data.2080// Re fungible custom data size. Negative test const_data.1778#[test]2081#[test]1779fn custom_data_size_re_fungible_const_data_bound_neg() {2082fn custom_data_size_re_fungible_const_data_bound_neg() {1780 new_test_ext().execute_with(|| {2083 new_test_ext().execute_with(|| {1781 assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits { 2084 assert_ok!(TemplateModule::set_chain_limits(2085 RawOrigin::Root.into(),2086 ChainLimits {1782 collection_numbers_limit: 10,2087 collection_numbers_limit: 10,1783 account_token_ownership_limit: 10,2088 account_token_ownership_limit: 10,1784 collections_admins_limit: 5,2089 collections_admins_limit: 5,1785 custom_data_limit: 2,2090 custom_data_limit: 2,1786 nft_sponsor_transfer_timeout: 15,2091 nft_sponsor_transfer_timeout: 15,1787 fungible_sponsor_transfer_timeout: 15,2092 fungible_sponsor_transfer_timeout: 15,1788 refungible_sponsor_transfer_timeout: 15,2093 refungible_sponsor_transfer_timeout: 15,1789 const_on_chain_schema_limit: 1024,2094 const_on_chain_schema_limit: 1024,1790 offchain_schema_limit: 1024,2095 offchain_schema_limit: 1024,1791 variable_on_chain_schema_limit: 1024,2096 variable_on_chain_schema_limit: 1024,1792 }));2097 }2098 ));179320991794 let collection_id = create_test_collection(&CollectionMode::NFT, 1);2100 let collection_id = create_test_collection(&CollectionMode::NFT, 1);179521011796 let origin1 = Origin::signed(1);2102 let origin1 = Origin::signed(1);1797 let too_big_const_data = CreateItemData::NFT(CreateNftData{2103 let too_big_const_data = CreateItemData::NFT(CreateNftData {1798 const_data: vec![1, 2, 3, 4],2104 const_data: vec![1, 2, 3, 4],1799 variable_data: vec![]2105 variable_data: vec![],1800 });2106 });180121071802 assert_noop!(TemplateModule::create_item(2108 assert_noop!(1803 origin1.clone(),2109 TemplateModule::create_item(origin1, collection_id, account(1), too_big_const_data),1804 collection_id,1805 1,1806 too_big_const_data1807 ), Error::<Test>::TokenConstDataLimitExceeded);2110 Error::<Test>::TokenConstDataLimitExceeded2111 );1808 });2112 });1809}2113}181021141811// Re fungible custom data size. Negative test variable_data.2115// Re fungible custom data size. Negative test variable_data.1812#[test]2116#[test]1813fn custom_data_size_re_fungible_variable_data_bound_neg() {2117fn custom_data_size_re_fungible_variable_data_bound_neg() {1814 new_test_ext().execute_with(|| {2118 new_test_ext().execute_with(|| {1815 assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits { 2119 assert_ok!(TemplateModule::set_chain_limits(2120 RawOrigin::Root.into(),2121 ChainLimits {1816 collection_numbers_limit: 10,2122 collection_numbers_limit: 10,1817 account_token_ownership_limit: 10,2123 account_token_ownership_limit: 10,1818 collections_admins_limit: 5,2124 collections_admins_limit: 5,1819 custom_data_limit: 2,2125 custom_data_limit: 2,1820 nft_sponsor_transfer_timeout: 15,2126 nft_sponsor_transfer_timeout: 15,1821 fungible_sponsor_transfer_timeout: 15,2127 fungible_sponsor_transfer_timeout: 15,1822 refungible_sponsor_transfer_timeout: 15,2128 refungible_sponsor_transfer_timeout: 15,1823 const_on_chain_schema_limit: 1024,2129 const_on_chain_schema_limit: 1024,1824 offchain_schema_limit: 1024,2130 offchain_schema_limit: 1024,1825 variable_on_chain_schema_limit: 1024,2131 variable_on_chain_schema_limit: 1024,1826 }));2132 }2133 ));182721341828 let collection_id = create_test_collection(&CollectionMode::NFT, 1);2135 let collection_id = create_test_collection(&CollectionMode::NFT, 1);182921361830 let origin1 = Origin::signed(1);2137 let origin1 = Origin::signed(1);1831 let too_big_const_data = CreateItemData::NFT(CreateNftData{2138 let too_big_const_data = CreateItemData::NFT(CreateNftData {1832 const_data: vec![],2139 const_data: vec![],1833 variable_data: vec![1, 2, 3, 4]2140 variable_data: vec![1, 2, 3, 4],1834 });2141 });183521421836 assert_noop!(TemplateModule::create_item(2143 assert_noop!(1837 origin1.clone(),2144 TemplateModule::create_item(origin1, collection_id, account(1), too_big_const_data),1838 collection_id,1839 1,1840 too_big_const_data1841 ), Error::<Test>::TokenVariableDataLimitExceeded);2145 Error::<Test>::TokenVariableDataLimitExceeded2146 );1842 });2147 });1843}2148}1844// #endregion2149// #endregion184521501846#[test]2151#[test]1847fn set_const_on_chain_schema() {2152fn set_const_on_chain_schema() {1848 new_test_ext().execute_with(|| {2153 new_test_ext().execute_with(|| {1849 default_limits();2154 default_limits();185021551851 let collection_id = create_test_collection(&CollectionMode::NFT, 1);2156 let collection_id = create_test_collection(&CollectionMode::NFT, 1);185221571853 let origin1 = Origin::signed(1);2158 let origin1 = Origin::signed(1);1854 assert_ok!(TemplateModule::set_const_on_chain_schema(origin1, collection_id, b"test const on chain schema".to_vec()));2159 assert_ok!(TemplateModule::set_const_on_chain_schema(2160 origin1,2161 collection_id,2162 b"test const on chain schema".to_vec()2163 ));185521641856 assert_eq!(TemplateModule::collection_id(collection_id).unwrap().const_on_chain_schema, b"test const on chain schema".to_vec());2165 assert_eq!(2166 TemplateModule::collection_id(collection_id)2167 .unwrap()2168 .const_on_chain_schema,2169 b"test const on chain schema".to_vec()2170 );1857 assert_eq!(TemplateModule::collection_id(collection_id).unwrap().variable_on_chain_schema, b"".to_vec());2171 assert_eq!(2172 TemplateModule::collection_id(collection_id)2173 .unwrap()2174 .variable_on_chain_schema,2175 b"".to_vec()2176 );1858 });2177 });1859}2178}186021791861#[test]2180#[test]1862fn set_variable_on_chain_schema() {2181fn set_variable_on_chain_schema() {1863 new_test_ext().execute_with(|| {2182 new_test_ext().execute_with(|| {1864 default_limits();2183 default_limits();1865 1866 let collection_id = create_test_collection(&CollectionMode::NFT, 1);186721841868 let origin1 = Origin::signed(1);2185 let collection_id = create_test_collection(&CollectionMode::NFT, 1);1869 assert_ok!(TemplateModule::set_variable_on_chain_schema(origin1, collection_id, b"test variable on chain schema".to_vec()));187021861871 assert_eq!(TemplateModule::collection_id(collection_id).unwrap().const_on_chain_schema, b"".to_vec());2187 let origin1 = Origin::signed(1);2188 assert_ok!(TemplateModule::set_variable_on_chain_schema(2189 origin1,2190 collection_id,2191 b"test variable on chain schema".to_vec()2192 ));21932194 assert_eq!(2195 TemplateModule::collection_id(collection_id)2196 .unwrap()2197 .const_on_chain_schema,2198 b"".to_vec()2199 );1872 assert_eq!(TemplateModule::collection_id(collection_id).unwrap().variable_on_chain_schema, b"test variable on chain schema".to_vec());2200 assert_eq!(2201 TemplateModule::collection_id(collection_id)2202 .unwrap()2203 .variable_on_chain_schema,2204 b"test variable on chain schema".to_vec()2205 );1873 });2206 });1874}2207}187522081876#[test]2209#[test]1877fn set_variable_meta_data_on_nft_token_stores_variable_meta_data() {2210fn set_variable_meta_data_on_nft_token_stores_variable_meta_data() {1878 new_test_ext().execute_with(|| {2211 new_test_ext().execute_with(|| {1879 default_limits();2212 default_limits();188022131881 let collection_id = create_test_collection(&CollectionMode::NFT, 1);2214 let collection_id = create_test_collection(&CollectionMode::NFT, 1);188222151883 let origin1 = Origin::signed(1);2216 let origin1 = Origin::signed(1);1884 1885 let data = default_nft_data();1886 create_test_item(1, &data.into());1887 1888 let variable_data = b"test set_variable_meta_data method.".to_vec();1889 assert_ok!(TemplateModule::set_variable_meta_data(origin1, collection_id, 1, variable_data.clone()));189022171891 assert_eq!(TemplateModule::nft_item_id(collection_id, 1).unwrap().variable_data, variable_data);2218 let data = default_nft_data();2219 create_test_item(1, &data.into());22202221 let variable_data = b"test set_variable_meta_data method.".to_vec();2222 assert_ok!(TemplateModule::set_variable_meta_data(2223 origin1,2224 collection_id,2225 1,2226 variable_data.clone()2227 ));22282229 assert_eq!(2230 TemplateModule::nft_item_id(collection_id, 1)2231 .unwrap()2232 .variable_data,2233 variable_data2234 );1892 });2235 });1893}2236}189422371895#[test]2238#[test]1896fn set_variable_meta_data_on_re_fungible_token_stores_variable_meta_data() {2239fn set_variable_meta_data_on_re_fungible_token_stores_variable_meta_data() {1897 new_test_ext().execute_with(|| {2240 new_test_ext().execute_with(|| {1898 default_limits();2241 default_limits();189922421900 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);2243 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);190122441902 let origin1 = Origin::signed(1);2245 let origin1 = Origin::signed(1);190322461904 let data = default_re_fungible_data();2247 let data = default_re_fungible_data();1905 create_test_item(1, &data.into());2248 create_test_item(1, &data.into());190622491907 let variable_data = b"test set_variable_meta_data method.".to_vec();2250 let variable_data = b"test set_variable_meta_data method.".to_vec();1908 assert_ok!(TemplateModule::set_variable_meta_data(origin1, collection_id, 1, variable_data.clone()));2251 assert_ok!(TemplateModule::set_variable_meta_data(2252 origin1,2253 collection_id,2254 1,2255 variable_data.clone()2256 ));190922571910 assert_eq!(TemplateModule::refungible_item_id(collection_id, 1).unwrap().variable_data, variable_data);2258 assert_eq!(2259 TemplateModule::refungible_item_id(collection_id, 1)2260 .unwrap()2261 .variable_data,2262 variable_data2263 );1911 });2264 });1912}2265}1913226619141915#[test]2267#[test]1916fn set_variable_meta_data_on_fungible_token_fails() {2268fn set_variable_meta_data_on_fungible_token_fails() {1917 new_test_ext().execute_with(|| {2269 new_test_ext().execute_with(|| {1918 default_limits();2270 default_limits();191922711920 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);2272 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);192122731922 let origin1 = Origin::signed(1);2274 let origin1 = Origin::signed(1);192322751924 let data = default_fungible_data();2276 let data = default_fungible_data();1925 create_test_item(1, &data.into());2277 create_test_item(1, &data.into());192622781927 let variable_data = b"test set_variable_meta_data method.".to_vec();2279 let variable_data = b"test set_variable_meta_data method.".to_vec();1928 assert_noop!(TemplateModule::set_variable_meta_data(origin1, collection_id, 1, variable_data.clone()), Error::<Test>::CantStoreMetadataInFungibleTokens);2280 assert_noop!(2281 TemplateModule::set_variable_meta_data(origin1, collection_id, 1, variable_data),2282 Error::<Test>::CantStoreMetadataInFungibleTokens2283 );1929 });2284 });1930}2285}193122861932#[test]2287#[test]1933fn set_variable_meta_data_on_nft_token_fails_for_big_data() {2288fn set_variable_meta_data_on_nft_token_fails_for_big_data() {1934 new_test_ext().execute_with(|| {2289 new_test_ext().execute_with(|| {1935 assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits { 2290 assert_ok!(TemplateModule::set_chain_limits(2291 RawOrigin::Root.into(),2292 ChainLimits {1936 collection_numbers_limit: default_collection_numbers_limit(),2293 collection_numbers_limit: default_collection_numbers_limit(),1937 account_token_ownership_limit: 10,2294 account_token_ownership_limit: 10,1938 collections_admins_limit: 5,2295 collections_admins_limit: 5,1939 custom_data_limit: 10,2296 custom_data_limit: 10,1940 nft_sponsor_transfer_timeout: 15,2297 nft_sponsor_transfer_timeout: 15,1941 fungible_sponsor_transfer_timeout: 15,2298 fungible_sponsor_transfer_timeout: 15,1942 refungible_sponsor_transfer_timeout: 15,2299 refungible_sponsor_transfer_timeout: 15,1943 const_on_chain_schema_limit: 1024,2300 const_on_chain_schema_limit: 1024,1944 offchain_schema_limit: 1024,2301 offchain_schema_limit: 1024,1945 variable_on_chain_schema_limit: 1024,2302 variable_on_chain_schema_limit: 1024,1946 }));2303 }2304 ));194723051948 let collection_id = create_test_collection(&CollectionMode::NFT, 1);2306 let collection_id = create_test_collection(&CollectionMode::NFT, 1);194923071950 let origin1 = Origin::signed(1);2308 let origin1 = Origin::signed(1);195123091952 let data = default_nft_data();2310 let data = default_nft_data();1953 create_test_item(1, &data.into());2311 create_test_item(1, &data.into());195423121955 let variable_data = b"test set_variable_meta_data method, bigger than limits.".to_vec();2313 let variable_data = b"test set_variable_meta_data method, bigger than limits.".to_vec();1956 assert_noop!(TemplateModule::set_variable_meta_data(origin1, collection_id, 1, variable_data), Error::<Test>::TokenVariableDataLimitExceeded);2314 assert_noop!(2315 TemplateModule::set_variable_meta_data(origin1, collection_id, 1, variable_data),2316 Error::<Test>::TokenVariableDataLimitExceeded2317 );1957 });2318 });1958}2319}195923201960#[test]2321#[test]1961fn set_variable_meta_data_on_re_fungible_token_fails_for_big_data() {2322fn set_variable_meta_data_on_re_fungible_token_fails_for_big_data() {1962 new_test_ext().execute_with(|| {2323 new_test_ext().execute_with(|| {1963 assert_ok!(TemplateModule::set_chain_limits(RawOrigin::Root.into(), ChainLimits { 2324 assert_ok!(TemplateModule::set_chain_limits(2325 RawOrigin::Root.into(),2326 ChainLimits {1964 collection_numbers_limit: default_collection_numbers_limit(),2327 collection_numbers_limit: default_collection_numbers_limit(),1965 account_token_ownership_limit: 10,2328 account_token_ownership_limit: 10,1966 collections_admins_limit: 5,2329 collections_admins_limit: 5,1967 custom_data_limit: 10,2330 custom_data_limit: 10,1968 nft_sponsor_transfer_timeout: 15,2331 nft_sponsor_transfer_timeout: 15,1969 fungible_sponsor_transfer_timeout: 15,2332 fungible_sponsor_transfer_timeout: 15,1970 refungible_sponsor_transfer_timeout: 15,2333 refungible_sponsor_transfer_timeout: 15,1971 const_on_chain_schema_limit: 1024,2334 const_on_chain_schema_limit: 1024,1972 offchain_schema_limit: 1024,2335 offchain_schema_limit: 1024,1973 variable_on_chain_schema_limit: 1024,2336 variable_on_chain_schema_limit: 1024,1974 }));2337 }19752338 ));197623391977 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);2340 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);197823411979 let origin1 = Origin::signed(1);2342 let origin1 = Origin::signed(1);198023431981 let data = default_re_fungible_data();2344 let data = default_re_fungible_data();1982 create_test_item(1, &data.into());2345 create_test_item(1, &data.into());198323461984 let variable_data = b"test set_variable_meta_data method, bigger than limits.".to_vec();2347 let variable_data = b"test set_variable_meta_data method, bigger than limits.".to_vec();1985 assert_noop!(TemplateModule::set_variable_meta_data(origin1, collection_id, 1, variable_data), Error::<Test>::TokenVariableDataLimitExceeded);2348 assert_noop!(2349 TemplateModule::set_variable_meta_data(origin1, collection_id, 1, variable_data),2350 Error::<Test>::TokenVariableDataLimitExceeded2351 );1986 });2352 });1987}2353}19882354pallets/scheduler/Cargo.tomldiffbeforeafterboth12[dependencies]12[dependencies]13serde = { version = "1.0.119", default-features = false }13serde = { version = "1.0.119", default-features = false }14codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }14codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }15frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }15frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }16frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }16frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }17sp-runtime = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }17sp-runtime = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }18sp-std = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }18sp-std = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }19sp-io = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }19sp-io = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }20frame-benchmarking = { default-features = false, version = '3.0.0', optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }20frame-benchmarking = { default-features = false, version = '3.0.0', optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }212122up-sponsorship = { default-features = false, path = "../../primitives/sponsorship", version = "0.1.0" }22up-sponsorship = { default-features = false, path = "../../primitives/sponsorship", version = "0.1.0" }23log = { version = "0.4.14", default-features = false }23log = { version = "0.4.14", default-features = false }242425[dev-dependencies]25[dev-dependencies]26sp-core = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }26sp-core = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }27substrate-test-utils = { version = "3.0.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }27substrate-test-utils = { version = "3.0.0", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }282829[features]29[features]30default = ["std"]30default = ["std"]pallets/scheduler/src/benchmarking.rsdiffbeforeafterbothno syntactic changes
pallets/scheduler/src/lib.rsdiffbeforeafterboth505051// Ensure we're `no_std` when compiling for Wasm.51// Ensure we're `no_std` when compiling for Wasm.52#![cfg_attr(not(feature = "std"), no_std)]52#![cfg_attr(not(feature = "std"), no_std)]53#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]535454mod benchmarking;55mod benchmarking;55pub mod weights;56pub mod weights;565757use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};58use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};58use codec::{Encode, Decode, Codec};59use codec::{Encode, Decode, Codec};59use sp_runtime::{RuntimeDebug, traits::{Zero, One, BadOrigin, Saturating}};60use sp_runtime::{61 RuntimeDebug,62 traits::{Zero, One, BadOrigin, Saturating},63};60use frame_support::{64use frame_support::{61 decl_module, decl_storage, decl_event, decl_error, IterableStorageMap,65 decl_module, decl_storage, decl_event, decl_error, IterableStorageMap,62 dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},66 dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},63 traits::{Get, schedule::{self, DispatchTime}, OriginTrait, EnsureOrigin, IsType},67 traits::{68 Get,69 schedule::{self, DispatchTime},70 OriginTrait, EnsureOrigin, IsType,71 },64 weights::{GetDispatchInfo, Weight},72 weights::{GetDispatchInfo, Weight},65};73};72/// should be added to our implied traits list.80/// should be added to our implied traits list.73///81///74/// `system::Config` should always be included in our implied traits.82/// `system::Config` should always be included in our implied traits.75/// // 83/// //76pub trait Config: system::Config84pub trait Config: system::Config {77{ 78402 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(412 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(403 s.origin.clone()413 s.origin.clone()404 ).into();414 ).into();405 let sender = ensure_signed(origin).unwrap_or(T::AccountId::default());415 let sender = ensure_signed(origin).unwrap_or_default();406 let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);416 let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);407 let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));417 let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));408 let r = s.call.clone().dispatch(sponsor.into());418 let r = s.call.clone().dispatch(sponsor.into());409 let maybe_id = s.maybe_id.clone();419 let maybe_id = s.maybe_id.clone();410 if let &Some((period, count)) = &s.maybe_periodic {420 if let Some((period, count)) = s.maybe_periodic {411 if count > 1 {421 if count > 1 {412 s.maybe_periodic = Some((period, count - 1));422 s.maybe_periodic = Some((period, count - 1));413 } else {423 } else {420 Lookup::<T>::insert(id, (next, next_index as u32));430 Lookup::<T>::insert(id, (next, next_index as u32));421 }431 }422 Agenda::<T>::append(next, Some(s));432 Agenda::<T>::append(next, Some(s));423 } else {433 } else if let Some(ref id) = s.maybe_id {424 if let Some(ref id) = s.maybe_id {425 Lookup::<T>::remove(id);434 Lookup::<T>::remove(id);426 }435 }427 }428 Self::deposit_event(RawEvent::Dispatched(436 Self::deposit_event(RawEvent::Dispatched(429 (now, index),437 (now, index),430 maybe_id,438 maybe_id,455463456 Agenda::<T>::translate::<464 Agenda::<T>::translate::<457 Vec<Option<ScheduledV1<<T as Config>::Call, T::BlockNumber>>>, _465 Vec<Option<ScheduledV1<<T as Config>::Call, T::BlockNumber>>>,466 _,458 >(|_, agenda| Some(467 >(|_, agenda| {468 Some(459 agenda469 agenda460 .into_iter()470 .into_iter()461 .map(|schedule| schedule.map(|schedule| ScheduledV2 {471 .map(|schedule| {472 schedule.map(|schedule| ScheduledV2 {462 maybe_id: schedule.maybe_id,473 maybe_id: schedule.maybe_id,463 priority: schedule.priority,474 priority: schedule.priority,466 origin: system::RawOrigin::Root.into(),477 origin: system::RawOrigin::Root.into(),467 _phantom: Default::default(),478 _phantom: Default::default(),468 }))479 })480 })469 .collect::<Vec<_>>()481 .collect::<Vec<_>>(),470 ));482 )483 });471484472 true485 true473 } else {486 } else {479 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {492 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {480 Agenda::<T>::translate::<493 Agenda::<T>::translate::<481 Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, OldOrigin, T::AccountId>>>, _494 Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, OldOrigin, T::AccountId>>>,495 _,482 >(|_, agenda| Some(496 >(|_, agenda| {497 Some(483 agenda498 agenda484 .into_iter()499 .into_iter()485 .map(|schedule| schedule.map(|schedule| Scheduled {500 .map(|schedule| {501 schedule.map(|schedule| Scheduled {486 maybe_id: schedule.maybe_id,502 maybe_id: schedule.maybe_id,487 priority: schedule.priority,503 priority: schedule.priority,490 origin: schedule.origin.into(),506 origin: schedule.origin.into(),491 _phantom: Default::default(),507 _phantom: Default::default(),492 }))508 })509 })493 .collect::<Vec<_>>()510 .collect::<Vec<_>>(),494 ));511 )512 });495 }513 }496514497 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {515 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {501 DispatchTime::At(x) => x,519 DispatchTime::At(x) => x,502 // The current block has already completed it's scheduled tasks, so520 // The current block has already completed it's scheduled tasks, so503 // Schedule the task at lest one block after this current block.521 // Schedule the task at lest one block after this current block.504 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one())522 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),505 };523 };506524507 if when <= now {525 if when <= now {508 return Err(Error::<T>::TargetBlockNumberInPast.into())526 return Err(Error::<T>::TargetBlockNumberInPast.into());509 }527 }510528511 Ok(when)529 Ok(when)567 Self::deposit_event(RawEvent::Canceled(when, index));589 Self::deposit_event(RawEvent::Canceled(when, index));568 Ok(())590 Ok(())569 } else {591 } else {570 Err(Error::<T>::NotFound)?592 Err(Error::<T>::NotFound.into())571 }593 }572 }594 }573595605 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {627 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {606 // ensure id it is unique628 // ensure id it is unique607 if Lookup::<T>::contains_key(&id) {629 if Lookup::<T>::contains_key(&id) {608 return Err(Error::<T>::FailedToSchedule)?630 return Err(Error::<T>::FailedToSchedule.into());609 }631 }610632611 let when = Self::resolve_time(when)?;633 let when = Self::resolve_time(when)?;644 call,645 maybe_periodic,646 origin,647 _phantom: Default::default(),621 };648 };622 Agenda::<T>::append(when, Some(s));649 Agenda::<T>::append(when, Some(s));623 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;650 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;653 Self::deposit_event(RawEvent::Canceled(when, index));680 Self::deposit_event(RawEvent::Canceled(when, index));654 Ok(())681 Ok(())655 } else {682 } else {656 Err(Error::<T>::NotFound)?683 Err(Error::<T>::NotFound.into())657 }684 }658 })685 })659 }686 }750}789}751790752#[cfg(test)]791#[cfg(test)]792#[allow(clippy::from_over_into)]753mod tests {793mod tests {754 use super::*;794 use super::*;755795887 type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;926 type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;888 type MaxScheduledPerBlock = MaxScheduledPerBlock;927 type MaxScheduledPerBlock = MaxScheduledPerBlock;889 type WeightInfo = ();928 type WeightInfo = ();929 type SponsorshipHandler = ();890 }930 }891931892 pub fn new_test_ext() -> sp_io::TestExternalities {932 pub fn new_test_ext() -> sp_io::TestExternalities {1523 );1524 }1759 }152517601526 impl Into<OriginCaller> for u32 {1761 impl From<u32> for OriginCaller {1527 fn into(self) -> OriginCaller {1762 fn from(value: u32) -> Self {1528 match self {1763 match value {1529 3u32 => system::RawOrigin::Root.into(),1764 3 => system::RawOrigin::Root.into(),1530 2u32 => system::RawOrigin::None.into(),1765 2 => system::RawOrigin::None.into(),1531 _ => unreachable!("test make no use of it"),1766 _ => unimplemented!(),1532 }1767 }1533 }1768 }1534 }1769 }pallets/scheduler/src/weights.rsdiffbeforeafterboth403941use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};40use frame_support::{41 traits::Get,42 weights::{Weight, constants::RocksDbWeight},43};42use sp_std::marker::PhantomData;44use sp_std::marker::PhantomData;434554pub struct SubstrateWeight<T>(PhantomData<T>);55pub struct SubstrateWeight<T>(PhantomData<T>);55impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {56impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {56 fn schedule(s: u32, ) -> Weight {57 fn schedule(s: u32) -> Weight {57 (35_029_000 as Weight)58 35_029_000_u6458 .saturating_add((77_000 as Weight).saturating_mul(s as Weight))59 .saturating_add(77_000_u64.saturating_mul(s as Weight))59 .saturating_add(T::DbWeight::get().reads(1 as Weight))60 .saturating_add(T::DbWeight::get().reads(1_u64))60 .saturating_add(T::DbWeight::get().writes(1 as Weight))61 .saturating_add(T::DbWeight::get().writes(1_u64))61 62 }62 }63 fn cancel(s: u32, ) -> Weight {63 fn cancel(s: u32) -> Weight {64 (31_419_000 as Weight)64 31_419_000_u6465 .saturating_add((4_015_000 as Weight).saturating_mul(s as Weight))65 .saturating_add(4_015_000_u64.saturating_mul(s as Weight))66 .saturating_add(T::DbWeight::get().reads(1 as Weight))66 .saturating_add(T::DbWeight::get().reads(1_u64))67 .saturating_add(T::DbWeight::get().writes(2 as Weight))67 .saturating_add(T::DbWeight::get().writes(2_u64))68 69 }68 }70 fn schedule_named(s: u32, ) -> Weight {69 fn schedule_named(s: u32) -> Weight {71 (44_752_000 as Weight)70 44_752_000_u6472 .saturating_add((123_000 as Weight).saturating_mul(s as Weight))71 .saturating_add(123_000_u64.saturating_mul(s as Weight))73 .saturating_add(T::DbWeight::get().reads(2 as Weight))72 .saturating_add(T::DbWeight::get().reads(2_u64))74 .saturating_add(T::DbWeight::get().writes(2 as Weight))73 .saturating_add(T::DbWeight::get().writes(2_u64))75 76 }74 }77 fn cancel_named(s: u32, ) -> Weight {75 fn cancel_named(s: u32) -> Weight {78 (35_712_000 as Weight)76 35_712_000_u6479 .saturating_add((4_008_000 as Weight).saturating_mul(s as Weight))77 .saturating_add(4_008_000_u64.saturating_mul(s as Weight))80 .saturating_add(T::DbWeight::get().reads(2 as Weight))78 .saturating_add(T::DbWeight::get().reads(2_u64))81 .saturating_add(T::DbWeight::get().writes(2 as Weight))79 .saturating_add(T::DbWeight::get().writes(2_u64))82 83 }80 }84 85}81}868287// For backwards compatibility and tests83// For backwards compatibility and tests88impl WeightInfo for () {84impl WeightInfo for () {89 fn schedule(s: u32, ) -> Weight {85 fn schedule(s: u32) -> Weight {90 (35_029_000 as Weight)86 35_029_000_u6491 .saturating_add((77_000 as Weight).saturating_mul(s as Weight))87 .saturating_add(77_000_u64.saturating_mul(s as Weight))92 .saturating_add(RocksDbWeight::get().reads(1 as Weight))88 .saturating_add(RocksDbWeight::get().reads(1_u64))93 .saturating_add(RocksDbWeight::get().writes(1 as Weight))89 .saturating_add(RocksDbWeight::get().writes(1_u64))94 95 }90 }96 fn cancel(s: u32, ) -> Weight {91 fn cancel(s: u32) -> Weight {97 (31_419_000 as Weight)92 31_419_000_u6498 .saturating_add((4_015_000 as Weight).saturating_mul(s as Weight))93 .saturating_add(4_015_000_u64.saturating_mul(s as Weight))99 .saturating_add(RocksDbWeight::get().reads(1 as Weight))94 .saturating_add(RocksDbWeight::get().reads(1_u64))100 .saturating_add(RocksDbWeight::get().writes(2 as Weight))95 .saturating_add(RocksDbWeight::get().writes(2_u64))101 102 }96 }103 fn schedule_named(s: u32, ) -> Weight {97 fn schedule_named(s: u32) -> Weight {104 (44_752_000 as Weight)98 44_752_000_u64105 .saturating_add((123_000 as Weight).saturating_mul(s as Weight))99 .saturating_add(123_000_u64.saturating_mul(s as Weight))106 .saturating_add(RocksDbWeight::get().reads(2 as Weight))100 .saturating_add(RocksDbWeight::get().reads(2_u64))107 .saturating_add(RocksDbWeight::get().writes(2 as Weight))101 .saturating_add(RocksDbWeight::get().writes(2_u64))108 109 }102 }110 fn cancel_named(s: u32, ) -> Weight {103 fn cancel_named(s: u32) -> Weight {111 (35_712_000 as Weight)104 35_712_000_u64112 .saturating_add((4_008_000 as Weight).saturating_mul(s as Weight))105 .saturating_add(4_008_000_u64.saturating_mul(s as Weight))113 .saturating_add(RocksDbWeight::get().reads(2 as Weight))106 .saturating_add(RocksDbWeight::get().reads(2_u64))114 .saturating_add(RocksDbWeight::get().writes(2 as Weight))107 .saturating_add(RocksDbWeight::get().writes(2_u64))115 116 }108 }117 primitives/nft/Cargo.tomldiffbeforeafterboth11[dependencies]11[dependencies]12codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ['derive'] }12codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ['derive'] }13serde = { version = "1.0.119", features = ['derive'], default-features = false }13serde = { version = "1.0.119", features = ['derive'], default-features = false }14frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }14frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }15frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }15frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }16pallet-contracts = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }16pallet-contracts = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }17sp-core = { version = "3.0.0", default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }17sp-core = { version = "3.0.0", default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }18sp-runtime = { version = "3.0.0", default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }18sp-runtime = { version = "3.0.0", default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.7' }191920[features]20[features]21default = ["std"]21default = ["std"]primitives/nft/src/lib.rsdiffbeforeafterboth324pub use serde::{Serialize, Deserialize};3pub use serde::{Serialize, Deserialize};546use frame_system;7use sp_runtime::sp_std::prelude::Vec;5use sp_runtime::sp_std::prelude::Vec;8use codec::{Decode, Encode};6use codec::{Decode, Encode};9pub use frame_support::{7pub use frame_support::{48 }45 }49}46}504751impl Into<u8> for CollectionMode {48impl CollectionMode {52 fn into(self) -> u8 {49 pub fn id(&self) -> u8 {53 match self {50 match self {54 CollectionMode::Invalid => 0,51 CollectionMode::Invalid => 0,55 CollectionMode::NFT => 1,52 CollectionMode::NFT => 1,146 pub offchain_schema: Vec<u8>,141 pub offchain_schema: Vec<u8>,147 pub schema_version: SchemaVersion,142 pub schema_version: SchemaVersion,148 pub sponsorship: SponsorshipState<T::AccountId>,143 pub sponsorship: SponsorshipState<T::AccountId>,149 pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions 144 pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions150 pub variable_on_chain_schema: Vec<u8>, //145 pub variable_on_chain_schema: Vec<u8>, //151 pub const_on_chain_schema: Vec<u8>, //146 pub const_on_chain_schema: Vec<u8>, //152}147}180 pub account_token_ownership_limit: u32,174 pub account_token_ownership_limit: u32,181 pub sponsored_data_size: u32,175 pub sponsored_data_size: u32,182 /// None - setVariableMetadata is not sponsored176 /// None - setVariableMetadata is not sponsored183 /// Some(v) - setVariableMetadata is sponsored 177 /// Some(v) - setVariableMetadata is sponsored184 /// if there is v block between txs178 /// if there is v block between txs185 pub sponsored_data_rate_limit: Option<BlockNumber>,179 pub sponsored_data_rate_limit: Option<BlockNumber>,186 pub token_limit: u32,180 pub token_limit: u32,200 sponsored_data_rate_limit: None,194 sponsored_data_rate_limit: None,201 sponsor_transfer_timeout: 14400,195 sponsor_transfer_timeout: 14400,202 owner_can_transfer: true,196 owner_can_transfer: true,203 owner_can_destroy: true197 owner_can_destroy: true,204 }198 }205 }199 }206}200}255}248}256249257impl CreateItemData {250impl CreateItemData {258 pub fn len(&self) -> usize {251 pub fn data_size(&self) -> usize {259 let len = match self {252 match self {260 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),253 CreateItemData::NFT(data) => data.variable_data.len() + data.const_data.len(),261 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),254 CreateItemData::ReFungible(data) => data.variable_data.len() + data.const_data.len(),262 _ => 0255 _ => 0,263 };256 }264 265 return len;266 }257 }267}258}268259runtime/Cargo.tomldiffbeforeafterboth95default-features = false95default-features = false96git = 'https://github.com/paritytech/substrate.git'96git = 'https://github.com/paritytech/substrate.git'97optional = true97optional = true98branch = 'polkadot-v0.9.3'98branch = 'polkadot-v0.9.7'99version = '3.0.0'99version = '3.0.0'100100101[dependencies.frame-executive]101[dependencies.frame-executive]102default-features = false102default-features = false103git = 'https://github.com/paritytech/substrate.git'103git = 'https://github.com/paritytech/substrate.git'104branch = 'polkadot-v0.9.3'104branch = 'polkadot-v0.9.7'105version = '3.0.0'105version = '3.0.0'106106107[dependencies.frame-support]107[dependencies.frame-support]108default-features = false108default-features = false109git = 'https://github.com/paritytech/substrate.git'109git = 'https://github.com/paritytech/substrate.git'110branch = 'polkadot-v0.9.3'110branch = 'polkadot-v0.9.7'111version = '3.0.0'111version = '3.0.0'112112113[dependencies.frame-system]113[dependencies.frame-system]114default-features = false114default-features = false115git = 'https://github.com/paritytech/substrate.git'115git = 'https://github.com/paritytech/substrate.git'116branch = 'polkadot-v0.9.3'116branch = 'polkadot-v0.9.7'117version = '3.0.0'117version = '3.0.0'118118119[dependencies.frame-system-benchmarking]119[dependencies.frame-system-benchmarking]120default-features = false120default-features = false121git = 'https://github.com/paritytech/substrate.git'121git = 'https://github.com/paritytech/substrate.git'122optional = true122optional = true123branch = 'polkadot-v0.9.3'123branch = 'polkadot-v0.9.7'124version = '3.0.0'124version = '3.0.0'125125126[dependencies.frame-system-rpc-runtime-api]126[dependencies.frame-system-rpc-runtime-api]127default-features = false127default-features = false128git = 'https://github.com/paritytech/substrate.git'128git = 'https://github.com/paritytech/substrate.git'129branch = 'polkadot-v0.9.3'129branch = 'polkadot-v0.9.7'130version = '3.0.0'130version = '3.0.0'131131132[dependencies.hex-literal]132[dependencies.hex-literal]142[dependencies.pallet-aura]142[dependencies.pallet-aura]143default-features = false143default-features = false144git = 'https://github.com/paritytech/substrate.git'144git = 'https://github.com/paritytech/substrate.git'145branch = 'polkadot-v0.9.3'145branch = 'polkadot-v0.9.7'146version = '3.0.0'146version = '3.0.0'147147148[dependencies.pallet-balances]148[dependencies.pallet-balances]149default-features = false149default-features = false150git = 'https://github.com/paritytech/substrate.git'150git = 'https://github.com/paritytech/substrate.git'151branch = 'polkadot-v0.9.3'151branch = 'polkadot-v0.9.7'152version = '3.0.0'152version = '3.0.0'153153154# Contracts specific packages154# Contracts specific packages155[dependencies.pallet-contracts]155[dependencies.pallet-contracts]156git = 'https://github.com/paritytech/substrate.git'156git = 'https://github.com/paritytech/substrate.git'157default-features = false157default-features = false158branch = 'polkadot-v0.9.3'158branch = 'polkadot-v0.9.7'159version = '3.0.0'159version = '3.0.0'160160161[dependencies.pallet-contracts-primitives]161[dependencies.pallet-contracts-primitives]162git = 'https://github.com/paritytech/substrate.git'162git = 'https://github.com/paritytech/substrate.git'163default-features = false163default-features = false164branch = 'polkadot-v0.9.3'164branch = 'polkadot-v0.9.7'165version = '3.0.0'165version = '3.0.0'166166167[dependencies.pallet-contracts-rpc-runtime-api]167[dependencies.pallet-contracts-rpc-runtime-api]168git = 'https://github.com/paritytech/substrate.git'168git = 'https://github.com/paritytech/substrate.git'169default-features = false169default-features = false170branch = 'polkadot-v0.9.3'170branch = 'polkadot-v0.9.7'171version = '3.0.0'171version = '3.0.0'172172173[dependencies.pallet-randomness-collective-flip]173[dependencies.pallet-randomness-collective-flip]174default-features = false174default-features = false175git = 'https://github.com/paritytech/substrate.git'175git = 'https://github.com/paritytech/substrate.git'176branch = 'polkadot-v0.9.3'176branch = 'polkadot-v0.9.7'177version = '3.0.0'177version = '3.0.0'178178179[dependencies.pallet-sudo]179[dependencies.pallet-sudo]180default-features = false180default-features = false181git = 'https://github.com/paritytech/substrate.git'181git = 'https://github.com/paritytech/substrate.git'182branch = 'polkadot-v0.9.3'182branch = 'polkadot-v0.9.7'183version = '3.0.0'183version = '3.0.0'184184185[dependencies.pallet-timestamp]185[dependencies.pallet-timestamp]186default-features = false186default-features = false187git = 'https://github.com/paritytech/substrate.git'187git = 'https://github.com/paritytech/substrate.git'188branch = 'polkadot-v0.9.3'188branch = 'polkadot-v0.9.7'189version = '3.0.0'189version = '3.0.0'190190191[dependencies.pallet-transaction-payment]191[dependencies.pallet-transaction-payment]192default-features = false192default-features = false193git = 'https://github.com/paritytech/substrate.git'193git = 'https://github.com/paritytech/substrate.git'194branch = 'polkadot-v0.9.3'194branch = 'polkadot-v0.9.7'195version = '3.0.0'195version = '3.0.0'196196197[dependencies.pallet-transaction-payment-rpc-runtime-api]197[dependencies.pallet-transaction-payment-rpc-runtime-api]198default-features = false198default-features = false199git = 'https://github.com/paritytech/substrate.git'199git = 'https://github.com/paritytech/substrate.git'200branch = 'polkadot-v0.9.3'200branch = 'polkadot-v0.9.7'201version = '3.0.0'201version = '3.0.0'202202203[dependencies.pallet-treasury]203[dependencies.pallet-treasury]204default-features = false204default-features = false205git = 'https://github.com/paritytech/substrate.git'205git = 'https://github.com/paritytech/substrate.git'206branch = 'polkadot-v0.9.3'206branch = 'polkadot-v0.9.7'207version = '3.0.0'207version = '3.0.0'208208209[dependencies.pallet-vesting]209[dependencies.pallet-vesting]210default-features = false210default-features = false211git = 'https://github.com/paritytech/substrate.git'211git = 'https://github.com/paritytech/substrate.git'212branch = 'polkadot-v0.9.3'212branch = 'polkadot-v0.9.7'213version = '3.0.0'213version = '3.0.0'214214215[dependencies.sp-arithmetic]215[dependencies.sp-arithmetic]216default-features = false216default-features = false217git = 'https://github.com/paritytech/substrate.git'217git = 'https://github.com/paritytech/substrate.git'218branch = 'polkadot-v0.9.3'218branch = 'polkadot-v0.9.7'219version = '3.0.0'219version = '3.0.0'220220221[dependencies.sp-api]221[dependencies.sp-api]222default-features = false222default-features = false223git = 'https://github.com/paritytech/substrate.git'223git = 'https://github.com/paritytech/substrate.git'224branch = 'polkadot-v0.9.3'224branch = 'polkadot-v0.9.7'225version = '3.0.0'225version = '3.0.0'226226227[dependencies.sp-block-builder]227[dependencies.sp-block-builder]228default-features = false228default-features = false229git = 'https://github.com/paritytech/substrate.git'229git = 'https://github.com/paritytech/substrate.git'230branch = 'polkadot-v0.9.3'230branch = 'polkadot-v0.9.7'231version = '3.0.0'231version = '3.0.0'232232233[dependencies.sp-core]233[dependencies.sp-core]234default-features = false234default-features = false235git = 'https://github.com/paritytech/substrate.git'235git = 'https://github.com/paritytech/substrate.git'236branch = 'polkadot-v0.9.3'236branch = 'polkadot-v0.9.7'237version = '3.0.0'237version = '3.0.0'238238239[dependencies.sp-consensus-aura]239[dependencies.sp-consensus-aura]240default-features = false240default-features = false241git = 'https://github.com/paritytech/substrate.git'241git = 'https://github.com/paritytech/substrate.git'242branch = 'polkadot-v0.9.3'242branch = 'polkadot-v0.9.7'243version = '0.9.0'243version = '0.9.0'244244245[dependencies.sp-inherents]245[dependencies.sp-inherents]246default-features = false246default-features = false247git = 'https://github.com/paritytech/substrate.git'247git = 'https://github.com/paritytech/substrate.git'248branch = 'polkadot-v0.9.3'248branch = 'polkadot-v0.9.7'249version = '3.0.0'249version = '3.0.0'250250251[dependencies.sp-io]251[dependencies.sp-io]252default-features = false252default-features = false253git = 'https://github.com/paritytech/substrate.git'253git = 'https://github.com/paritytech/substrate.git'254branch = 'polkadot-v0.9.3'254branch = 'polkadot-v0.9.7'255version = '3.0.0'255version = '3.0.0'256256257[dependencies.sp-offchain]257[dependencies.sp-offchain]258default-features = false258default-features = false259git = 'https://github.com/paritytech/substrate.git'259git = 'https://github.com/paritytech/substrate.git'260branch = 'polkadot-v0.9.3'260branch = 'polkadot-v0.9.7'261version = '3.0.0'261version = '3.0.0'262262263[dependencies.sp-runtime]263[dependencies.sp-runtime]264default-features = false264default-features = false265git = 'https://github.com/paritytech/substrate.git'265git = 'https://github.com/paritytech/substrate.git'266branch = 'polkadot-v0.9.3'266branch = 'polkadot-v0.9.7'267version = '3.0.0'267version = '3.0.0'268268269[dependencies.sp-session]269[dependencies.sp-session]270default-features = false270default-features = false271git = 'https://github.com/paritytech/substrate.git'271git = 'https://github.com/paritytech/substrate.git'272branch = 'polkadot-v0.9.3'272branch = 'polkadot-v0.9.7'273version = '3.0.0'273version = '3.0.0'274274275[dependencies.sp-std]275[dependencies.sp-std]276default-features = false276default-features = false277git = 'https://github.com/paritytech/substrate.git'277git = 'https://github.com/paritytech/substrate.git'278branch = 'polkadot-v0.9.3'278branch = 'polkadot-v0.9.7'279version = '3.0.0'279version = '3.0.0'280280281[dependencies.sp-transaction-pool]281[dependencies.sp-transaction-pool]282default-features = false282default-features = false283git = 'https://github.com/paritytech/substrate.git'283git = 'https://github.com/paritytech/substrate.git'284branch = 'polkadot-v0.9.3'284branch = 'polkadot-v0.9.7'285version = '3.0.0'285version = '3.0.0'286286287[dependencies.sp-version]287[dependencies.sp-version]288default-features = false288default-features = false289git = 'https://github.com/paritytech/substrate.git'289git = 'https://github.com/paritytech/substrate.git'290branch = 'polkadot-v0.9.3'290branch = 'polkadot-v0.9.7'291version = '3.0.0'291version = '3.0.0'292292293[dependencies.smallvec]293[dependencies.smallvec]299[dependencies.parachain-info]299[dependencies.parachain-info]300default-features = false300default-features = false301git = 'https://github.com/paritytech/cumulus.git'301git = 'https://github.com/paritytech/cumulus.git'302branch = 'polkadot-v0.9.3'302branch = 'polkadot-v0.9.7'303version = '0.1.0'303version = '0.1.0'304304305[dependencies.cumulus-pallet-aura-ext]305[dependencies.cumulus-pallet-aura-ext]306git = 'https://github.com/paritytech/cumulus.git'306git = 'https://github.com/paritytech/cumulus.git'307branch = 'polkadot-v0.9.3'307branch = 'polkadot-v0.9.7'308default-features = false308default-features = false309309310[dependencies.cumulus-pallet-parachain-system]310[dependencies.cumulus-pallet-parachain-system]311git = 'https://github.com/paritytech/cumulus.git'311git = 'https://github.com/paritytech/cumulus.git'312branch = 'polkadot-v0.9.3'312branch = 'polkadot-v0.9.7'313default-features = false313default-features = false314314315[dependencies.cumulus-primitives-core]315[dependencies.cumulus-primitives-core]316git = 'https://github.com/paritytech/cumulus.git'316git = 'https://github.com/paritytech/cumulus.git'317branch = 'polkadot-v0.9.3'317branch = 'polkadot-v0.9.7'318default-features = false318default-features = false319319320[dependencies.cumulus-pallet-xcm]320[dependencies.cumulus-pallet-xcm]321git = 'https://github.com/paritytech/cumulus.git'321git = 'https://github.com/paritytech/cumulus.git'322branch = 'polkadot-v0.9.3'322branch = 'polkadot-v0.9.7'323default-features = false323default-features = false324324325[dependencies.cumulus-pallet-dmp-queue]325[dependencies.cumulus-pallet-dmp-queue]326git = 'https://github.com/paritytech/cumulus.git'326git = 'https://github.com/paritytech/cumulus.git'327branch = 'polkadot-v0.9.3'327branch = 'polkadot-v0.9.7'328default-features = false328default-features = false329329330[dependencies.cumulus-pallet-xcmp-queue]330[dependencies.cumulus-pallet-xcmp-queue]331git = 'https://github.com/paritytech/cumulus.git'331git = 'https://github.com/paritytech/cumulus.git'332branch = 'polkadot-v0.9.3'332branch = 'polkadot-v0.9.7'333default-features = false333default-features = false334334335[dependencies.cumulus-primitives-utility]335[dependencies.cumulus-primitives-utility]336git = 'https://github.com/paritytech/cumulus.git'336git = 'https://github.com/paritytech/cumulus.git'337branch = 'polkadot-v0.9.3'337branch = 'polkadot-v0.9.7'338default-features = false338default-features = false339340[dependencies.cumulus-primitives-timestamp]341git = 'https://github.com/paritytech/cumulus.git'342branch = 'polkadot-v0.9.7'343default-features = false339344340################################################################################345################################################################################341# Polkadot dependencies346# Polkadot dependencies342347343[dependencies.polkadot-parachain]348[dependencies.polkadot-parachain]344git = 'https://github.com/paritytech/polkadot'349git = 'https://github.com/paritytech/polkadot'345branch = 'release-v0.9.3'350branch = 'release-v0.9.7'346default-features = false351default-features = false347352348[dependencies.xcm]353[dependencies.xcm]349git = 'https://github.com/paritytech/polkadot'354git = 'https://github.com/paritytech/polkadot'350branch = 'release-v0.9.3'355branch = 'release-v0.9.7'351default-features = false356default-features = false352357353[dependencies.xcm-builder]358[dependencies.xcm-builder]354git = 'https://github.com/paritytech/polkadot'359git = 'https://github.com/paritytech/polkadot'355branch = 'release-v0.9.3'360branch = 'release-v0.9.7'356default-features = false361default-features = false357362358[dependencies.xcm-executor]363[dependencies.xcm-executor]359git = 'https://github.com/paritytech/polkadot'364git = 'https://github.com/paritytech/polkadot'360branch = 'release-v0.9.3'365branch = 'release-v0.9.7'361default-features = false366default-features = false362367363[dependencies.pallet-xcm]368[dependencies.pallet-xcm]364git = 'https://github.com/paritytech/polkadot'369git = 'https://github.com/paritytech/polkadot'365branch = 'release-v0.9.3'370branch = 'release-v0.9.7'366default-features = false371default-features = false367372368373379pallet-nft-transaction-payment = { path = '../pallets/nft-transaction-payment', default-features = false, version = '3.0.0' }384pallet-nft-transaction-payment = { path = '../pallets/nft-transaction-payment', default-features = false, version = '3.0.0' }380pallet-nft-charge-transaction = { path = '../pallets/nft-charge-transaction', default-features = false, version = '3.0.0' }385pallet-nft-charge-transaction = { path = '../pallets/nft-charge-transaction', default-features = false, version = '3.0.0' }381386382pallet-evm = { default-features = false, version = "4.0.0-dev", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }387pallet-evm = { default-features = false, version = "5.0.0-dev", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }383pallet-ethereum = { default-features = false, version = "2.0.0-dev", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }388pallet-ethereum = { default-features = false, version = "3.0.0-dev", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }384fp-rpc = { default-features = false, version = "2.0.0", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }389fp-rpc = { default-features = false, version = "2.0.0", git = "https://github.com/usetech-llc/frontier.git", branch = "injected-transactions-parachain" }385390386################################################################################391################################################################################runtime/build.rsdiffbeforeafterbothno syntactic changes
runtime/src/chain_extension.rsdiffbeforeafterboth108108109 pallet_nft::Module::<C>::submit_logs(collection)?;109 pallet_nft::Module::<C>::submit_logs(collection)?;110 Ok(RetVal::Converging(0))110 Ok(RetVal::Converging(0))111 },111 }112 1 => {112 1 => {113 // Create Item113 // Create Item114 let mut env = env.buf_in_buf_out();114 let mut env = env.buf_in_buf_out();115 let input: NFTExtCreateItem<E> = env.read_as()?;115 let input: NFTExtCreateItem<E> = env.read_as()?;116 env.charge_weight(NftWeightInfoOf::<C>::create_item(input.data.len()))?;116 env.charge_weight(NftWeightInfoOf::<C>::create_item(input.data.data_size()))?;117117118 let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;118 let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;119119126126127 pallet_nft::Module::<C>::submit_logs(collection)?;127 pallet_nft::Module::<C>::submit_logs(collection)?;128 Ok(RetVal::Converging(0))128 Ok(RetVal::Converging(0))129 },129 }130 2 => {130 2 => {131 // Create multiple items131 // Create multiple items132 let mut env = env.buf_in_buf_out();132 let mut env = env.buf_in_buf_out();133 let input: NFTExtCreateMultipleItems<E> = env.read_as()?;133 let input: NFTExtCreateMultipleItems<E> = env.read_as()?;134 env.charge_weight(NftWeightInfoOf::<C>::create_item(134 env.charge_weight(NftWeightInfoOf::<C>::create_item(135 input.data.iter()135 input.data.iter().map(|i| i.data_size()).sum(),136 .map(|i| i.len())137 .sum()138 ))?;136 ))?;139137148146149 pallet_nft::Module::<C>::submit_logs(collection)?;147 pallet_nft::Module::<C>::submit_logs(collection)?;150 Ok(RetVal::Converging(0))148 Ok(RetVal::Converging(0))151 },149 }152 3 => {150 3 => {153 // Approve151 // Approve154 let mut env = env.buf_in_buf_out();152 let mut env = env.buf_in_buf_out();167165168 pallet_nft::Module::<C>::submit_logs(collection)?;166 pallet_nft::Module::<C>::submit_logs(collection)?;169 Ok(RetVal::Converging(0))167 Ok(RetVal::Converging(0))170 },168 }171 4 => {169 4 => {172 // Transfer from170 // Transfer from173 let mut env = env.buf_in_buf_out();171 let mut env = env.buf_in_buf_out();187185188 pallet_nft::Module::<C>::submit_logs(collection)?;186 pallet_nft::Module::<C>::submit_logs(collection)?;189 Ok(RetVal::Converging(0))187 Ok(RetVal::Converging(0))190 },188 }191 5 => {189 5 => {192 // Set variable metadata190 // Set variable metadata193 let mut env = env.buf_in_buf_out();191 let mut env = env.buf_in_buf_out();205203206 pallet_nft::Module::<C>::submit_logs(collection)?;204 pallet_nft::Module::<C>::submit_logs(collection)?;207 Ok(RetVal::Converging(0))205 Ok(RetVal::Converging(0))208 },206 }209 6 => {207 6 => {210 // Toggle whitelist208 // Toggle whitelist211 let mut env = env.buf_in_buf_out();209 let mut env = env.buf_in_buf_out();224 pallet_nft::Module::<C>::submit_logs(collection)?;222 pallet_nft::Module::<C>::submit_logs(collection)?;225 Ok(RetVal::Converging(0))223 Ok(RetVal::Converging(0))226 }224 }227 _ => {225 _ => Err(DispatchError::Other("unknown chain_extension func_id")),228 Err(DispatchError::Other("unknown chain_extension func_id"))229 }230 }226 }231 }227 }232}228}runtime/src/lib.rsdiffbeforeafterboth8#![cfg_attr(not(feature = "std"), no_std)]8#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]10#![recursion_limit = "1024"]1111#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]12// Make the WASM binary available.13// Make the WASM binary available.13#[cfg(feature = "std")]14#[cfg(feature = "std")]14include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));35use sp_version::NativeVersion;35use sp_version::NativeVersion;36use sp_version::RuntimeVersion;36use sp_version::RuntimeVersion;37pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo};37pub use pallet_transaction_payment::{38 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,39};38// A few exports that help ease life for downstream crates.40// A few exports that help ease life for downstream crates.39pub use pallet_balances::Call as BalancesCall;41pub use pallet_balances::Call as BalancesCall;48 ConsensusEngineId,49 traits::{47 traits::{50 All, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier, OnUnbalanced, Randomness, FindAuthor48 All, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,49 OnUnbalanced, Randomness, FindAuthor,51 },50 },52 weights::{51 weights::{53 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},52 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},54 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,53 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,55 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients54 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,56 },55 },57};56};58use nft_data_structs::*;57use nft_data_structs::*;64 limits::{BlockWeights, BlockLength},62 limits::{BlockWeights, BlockLength},65};63};66use sp_arithmetic::{traits::{BaseArithmetic, Unsigned}};64use sp_arithmetic::{65 traits::{BaseArithmetic, Unsigned},66};67use smallvec::smallvec;67use smallvec::smallvec;68use codec::{Encode, Decode};68use codec::{Encode, Decode};69use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};69use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};70use fp_rpc::TransactionStatus;70use fp_rpc::TransactionStatus;71use sp_core::crypto::Public;71use sp_core::crypto::Public;72use sp_runtime::{72use sp_runtime::{73 traits::{ 73 traits::{Dispatchable},74 Dispatchable,75 },76};74};77use pallet_contracts::chain_extension::UncheckedFrom;75use pallet_contracts::chain_extension::UncheckedFrom;255 type BlockGasLimit = BlockGasLimit;250 type BlockGasLimit = BlockGasLimit;256 type FeeCalculator = ();251 type FeeCalculator = ();257 type GasWeightMapping = ();252 type GasWeightMapping = ();253 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping;258 type CallOrigin = EnsureAddressTruncated;254 type CallOrigin = EnsureAddressTruncated;259 type WithdrawOrigin = EnsureAddressTruncated;255 type WithdrawOrigin = EnsureAddressTruncated;260 type AddressMapping = HashedAddressMapping<Self::Hashing>;256 type AddressMapping = HashedAddressMapping<Self::Hashing>;272{273 fn find_author<'a, I>(digests: I) -> Option<H160> where268 fn find_author<'a, I>(digests: I) -> Option<H160>269 where274 I: 'a + IntoIterator<Item=(ConsensusEngineId, &'a [u8])>270 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,275 {271 {276 if let Some(author_index) = F::find_author(digests) {272 if let Some(author_index) = F::find_author(digests) {277 let authority_id = Aura::authorities()[author_index as usize].clone();273 let authority_id = Aura::authorities()[author_index as usize].clone();292 type EvmSubmitLog = pallet_evm::Pallet<Runtime>;288 type EvmSubmitLog = pallet_evm::Pallet<Runtime>;293}289}290291impl pallet_randomness_collective_flip::Config for Runtime {}294292295impl system::Config for Runtime {293impl system::Config for Runtime {296 /// The data to be stored in an account.294 /// The data to be stored in an account.360358361impl pallet_balances::Config for Runtime {359impl pallet_balances::Config for Runtime {362 type MaxLocks = MaxLocks;360 type MaxLocks = MaxLocks;361 type MaxReserves = ();362 type ReserveIdentifier = [u8; 8];363 /// The type for recording an account's balance.363 /// The type for recording an account's balance.364 type Balance = Balance;364 type Balance = Balance;365 /// The ubiquitous event type.365 /// The ubiquitous event type.439439440impl<T> WeightToFeePolynomial for LinearFee<T> where440impl<T> WeightToFeePolynomial for LinearFee<T>441where441 T: BaseArithmetic + From<u32> + Copy + Unsigned442 T: BaseArithmetic + From<u32> + Copy + Unsigned,442{443{443 type Balance = T;444 type Balance = T;444445689 type Event = Event;690 type Event = Event;690 type WeightInfo = nft_weights::WeightInfo;691 type WeightInfo = nft_weights::WeightInfo;691692692 type EvmWithdrawOrigin = EnsureAddressTruncated;693 type EvmBackwardsAddressMapping = pallet_nft::MapBackwardsAddressTruncated;693 type EvmBackwardsAddressMapping = pallet_nft::MapBackwardsAddressTruncated;694 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;694 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;695 type CrossAccountId = pallet_nft::BasicCrossAccountId<Self>;695 type CrossAccountId = pallet_nft::BasicCrossAccountId<Self>;728 Call: IsSubType<pallet_nft::Call<Runtime>>, 727 Call: IsSubType<pallet_nft::Call<Runtime>>,729 Call: IsSubType<pallet_contracts::Call<Runtime>>,728 Call: IsSubType<pallet_contracts::Call<Runtime>>,730 AccountId: AsRef<[u8]>,729 AccountId: AsRef<[u8]>,731 AccountId: UncheckedFrom<Hash>730 AccountId: UncheckedFrom<Hash>,732 {731 {733 pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)732 pallet_nft_transaction_payment::Module::<Runtime>::withdraw_type(who, call)734 }733 }980 gas_limit.low_u64(),987 gas_limit.low_u64(),981 gas_price,988 gas_price,982 nonce,989 nonce,983 config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),990 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),984 ).map_err(|err| err.into())991 ).map_err(|err| err.into())985 }992 }9869931008 gas_limit.low_u64(),1015 gas_limit.low_u64(),1009 gas_price,1016 gas_price,1010 nonce,1017 nonce,1011 config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),1018 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1012 ).map_err(|err| err.into())1019 ).map_err(|err| err.into())1013 }1020 }101410211151 }1158 }1152}1159}11601161struct CheckInherents;11621163impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1164 fn check_inherents(1165 block: &Block,1166 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1167 ) -> sp_inherents::CheckInherentsResult {1168 let relay_chain_slot = relay_state_proof1169 .read_slot()1170 .expect("Could not read the relay chain slot from the proof");11711172 let inherent_data =1173 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1174 relay_chain_slot,1175 sp_std::time::Duration::from_secs(6),1176 )1177 .create_inherent_data()1178 .expect("Could not create the timestamp inherent data");11791180 inherent_data.check_extrinsics(&block)1181 }1182}115311831154cumulus_pallet_parachain_system::register_validate_block!(1184cumulus_pallet_parachain_system::register_validate_block!(1155 Runtime,1185 Runtime = Runtime,1156 cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1186 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1187 CheckInherents = CheckInherents,1157);1188);11581189runtime/src/nft_weights.rsdiffbeforeafterboth8pub struct WeightInfo;8pub struct WeightInfo;9impl pallet_nft::WeightInfo for WeightInfo {9impl pallet_nft::WeightInfo for WeightInfo {10 fn create_collection() -> Weight {10 fn create_collection() -> Weight {11 (70_000_000 as Weight)11 70_000_000_u6412 .saturating_add(DbWeight::get().reads(7 as Weight))12 .saturating_add(DbWeight::get().reads(7_u64))13 .saturating_add(DbWeight::get().writes(5 as Weight))13 .saturating_add(DbWeight::get().writes(5_u64))14 }14 }15 fn destroy_collection() -> Weight {15 fn destroy_collection() -> Weight {16 (90_000_000 as Weight)16 90_000_000_u6417 .saturating_add(DbWeight::get().reads(2 as Weight))17 .saturating_add(DbWeight::get().reads(2_u64))18 .saturating_add(DbWeight::get().writes(5 as Weight))18 .saturating_add(DbWeight::get().writes(5_u64))19 }19 }20 fn add_to_white_list() -> Weight {20 fn add_to_white_list() -> Weight {21 (30_000_000 as Weight)21 30_000_000_u6422 .saturating_add(DbWeight::get().reads(3 as Weight))22 .saturating_add(DbWeight::get().reads(3_u64))23 .saturating_add(DbWeight::get().writes(1 as Weight))23 .saturating_add(DbWeight::get().writes(1_u64))24 }24 }25 fn remove_from_white_list() -> Weight {25 fn remove_from_white_list() -> Weight {26 (35_000_000 as Weight)26 35_000_000_u6427 .saturating_add(DbWeight::get().reads(3 as Weight))27 .saturating_add(DbWeight::get().reads(3_u64))28 .saturating_add(DbWeight::get().writes(1 as Weight))28 .saturating_add(DbWeight::get().writes(1_u64))29 }29 }30 fn set_public_access_mode() -> Weight {30 fn set_public_access_mode() -> Weight {31 (27_000_000 as Weight)31 27_000_000_u6432 .saturating_add(DbWeight::get().reads(1 as Weight))32 .saturating_add(DbWeight::get().reads(1_u64))33 .saturating_add(DbWeight::get().writes(1 as Weight))33 .saturating_add(DbWeight::get().writes(1_u64))34 }34 }35 fn set_mint_permission() -> Weight {35 fn set_mint_permission() -> Weight {36 (27_000_000 as Weight)36 27_000_000_u6437 .saturating_add(DbWeight::get().reads(1 as Weight))37 .saturating_add(DbWeight::get().reads(1_u64))38 .saturating_add(DbWeight::get().writes(1 as Weight))38 .saturating_add(DbWeight::get().writes(1_u64))39 }39 }40 fn change_collection_owner() -> Weight {40 fn change_collection_owner() -> Weight {41 (27_000_000 as Weight)41 27_000_000_u6442 .saturating_add(DbWeight::get().reads(1 as Weight))42 .saturating_add(DbWeight::get().reads(1_u64))43 .saturating_add(DbWeight::get().writes(1 as Weight))43 .saturating_add(DbWeight::get().writes(1_u64))44 }44 }45 fn add_collection_admin() -> Weight {45 fn add_collection_admin() -> Weight {46 (32_000_000 as Weight)46 32_000_000_u6447 .saturating_add(DbWeight::get().reads(3 as Weight))47 .saturating_add(DbWeight::get().reads(3_u64))48 .saturating_add(DbWeight::get().writes(1 as Weight))48 .saturating_add(DbWeight::get().writes(1_u64))49 }49 }50 fn remove_collection_admin() -> Weight {50 fn remove_collection_admin() -> Weight {51 (50_000_000 as Weight)51 50_000_000_u6452 .saturating_add(DbWeight::get().reads(2 as Weight))52 .saturating_add(DbWeight::get().reads(2_u64))53 .saturating_add(DbWeight::get().writes(1 as Weight))53 .saturating_add(DbWeight::get().writes(1_u64))54 }54 }55 fn set_collection_sponsor() -> Weight {55 fn set_collection_sponsor() -> Weight {56 (32_000_000 as Weight)56 32_000_000_u6457 .saturating_add(DbWeight::get().reads(2 as Weight))57 .saturating_add(DbWeight::get().reads(2_u64))58 .saturating_add(DbWeight::get().writes(1 as Weight))58 .saturating_add(DbWeight::get().writes(1_u64))59 } 59 }60 fn confirm_sponsorship() -> Weight {60 fn confirm_sponsorship() -> Weight {61 (22_000_000 as Weight)61 22_000_000_u6462 .saturating_add(DbWeight::get().reads(1 as Weight))62 .saturating_add(DbWeight::get().reads(1_u64))63 .saturating_add(DbWeight::get().writes(1 as Weight))63 .saturating_add(DbWeight::get().writes(1_u64))64 } 64 }65 fn remove_collection_sponsor() -> Weight {65 fn remove_collection_sponsor() -> Weight {66 (24_000_000 as Weight)66 24_000_000_u6467 .saturating_add(DbWeight::get().reads(1 as Weight))67 .saturating_add(DbWeight::get().reads(1_u64))68 .saturating_add(DbWeight::get().writes(1 as Weight))68 .saturating_add(DbWeight::get().writes(1_u64))69 } 69 }70 fn create_item(s: usize, ) -> Weight {70 fn create_item(s: usize) -> Weight {71 (130_000_000 as Weight)71 130_000_000_u6472 .saturating_add((2135 as Weight).saturating_mul(s as Weight).saturating_mul(500 as Weight)) // 500 is temparary multiplier, fee for storage72 .saturating_add(2135_u64.saturating_mul(s as Weight).saturating_mul(500_u64)) // 500 is temparary multiplier, fee for storage73 .saturating_add(DbWeight::get().reads(10 as Weight))73 .saturating_add(DbWeight::get().reads(10_u64))74 .saturating_add(DbWeight::get().writes(8 as Weight))74 .saturating_add(DbWeight::get().writes(8_u64))75 } 75 }76 fn burn_item() -> Weight {76 fn burn_item() -> Weight {77 (170_000_000 as Weight)77 170_000_000_u6478 .saturating_add(DbWeight::get().reads(9 as Weight))78 .saturating_add(DbWeight::get().reads(9_u64))79 .saturating_add(DbWeight::get().writes(7 as Weight))79 .saturating_add(DbWeight::get().writes(7_u64))80 } 80 }81 fn transfer() -> Weight {81 fn transfer() -> Weight {82 (125_000_000 as Weight)82 125_000_000_u6483 .saturating_add(DbWeight::get().reads(7 as Weight))83 .saturating_add(DbWeight::get().reads(7_u64))84 .saturating_add(DbWeight::get().writes(7 as Weight))84 .saturating_add(DbWeight::get().writes(7_u64))85 } 85 }86 fn approve() -> Weight {86 fn approve() -> Weight {87 (45_000_000 as Weight)87 45_000_000_u6488 .saturating_add(DbWeight::get().reads(3 as Weight))88 .saturating_add(DbWeight::get().reads(3_u64))89 .saturating_add(DbWeight::get().writes(1 as Weight))89 .saturating_add(DbWeight::get().writes(1_u64))90 }90 }91 fn transfer_from() -> Weight {91 fn transfer_from() -> Weight {92 (150_000_000 as Weight)92 150_000_000_u6493 .saturating_add(DbWeight::get().reads(9 as Weight))93 .saturating_add(DbWeight::get().reads(9_u64))94 .saturating_add(DbWeight::get().writes(8 as Weight))94 .saturating_add(DbWeight::get().writes(8_u64))95 }95 }96 fn set_offchain_schema() -> Weight {96 fn set_offchain_schema() -> Weight {97 (33_000_000 as Weight)97 33_000_000_u6498 .saturating_add(DbWeight::get().reads(2 as Weight))98 .saturating_add(DbWeight::get().reads(2_u64))99 .saturating_add(DbWeight::get().writes(1 as Weight))99 .saturating_add(DbWeight::get().writes(1_u64))100 }100 }101 fn set_const_on_chain_schema() -> Weight {101 fn set_const_on_chain_schema() -> Weight {102 (11_100_000 as Weight)102 11_100_000_u64103 .saturating_add(DbWeight::get().reads(2 as Weight))103 .saturating_add(DbWeight::get().reads(2_u64))104 .saturating_add(DbWeight::get().writes(1 as Weight))104 .saturating_add(DbWeight::get().writes(1_u64))105 }105 }106 fn set_variable_on_chain_schema() -> Weight {106 fn set_variable_on_chain_schema() -> Weight {107 (11_100_000 as Weight)107 11_100_000_u64108 .saturating_add(DbWeight::get().reads(2 as Weight))108 .saturating_add(DbWeight::get().reads(2_u64))109 .saturating_add(DbWeight::get().writes(1 as Weight))109 .saturating_add(DbWeight::get().writes(1_u64))110 }110 }111 fn set_variable_meta_data() -> Weight {111 fn set_variable_meta_data() -> Weight {112 (17_500_000 as Weight)112 17_500_000_u64113 .saturating_add(DbWeight::get().reads(2 as Weight))113 .saturating_add(DbWeight::get().reads(2_u64))114 .saturating_add(DbWeight::get().writes(1 as Weight))114 .saturating_add(DbWeight::get().writes(1_u64))115 }115 }116 fn enable_contract_sponsoring() -> Weight {116 fn enable_contract_sponsoring() -> Weight {117 (13_000_000 as Weight)117 13_000_000_u64118 .saturating_add(DbWeight::get().reads(1 as Weight))118 .saturating_add(DbWeight::get().reads(1_u64))119 .saturating_add(DbWeight::get().writes(1 as Weight))119 .saturating_add(DbWeight::get().writes(1_u64))120 }120 }121 fn set_schema_version() -> Weight {121 fn set_schema_version() -> Weight {122 (8_500_000 as Weight)122 8_500_000_u64123 .saturating_add(DbWeight::get().reads(2 as Weight))123 .saturating_add(DbWeight::get().reads(2_u64))124 .saturating_add(DbWeight::get().writes(1 as Weight))124 .saturating_add(DbWeight::get().writes(1_u64))125 }125 }126 fn set_chain_limits() -> Weight {126 fn set_chain_limits() -> Weight {127 (1_300_000 as Weight)127 1_300_000_u64128 .saturating_add(DbWeight::get().reads(0 as Weight))128 .saturating_add(DbWeight::get().reads(0_u64))129 .saturating_add(DbWeight::get().writes(1 as Weight))129 .saturating_add(DbWeight::get().writes(1_u64))130 }130 }131 fn set_contract_sponsoring_rate_limit() -> Weight {131 fn set_contract_sponsoring_rate_limit() -> Weight {132 (3_500_000 as Weight)132 3_500_000_u64133 .saturating_add(DbWeight::get().reads(0 as Weight))133 .saturating_add(DbWeight::get().reads(0_u64))134 .saturating_add(DbWeight::get().writes(2 as Weight))134 .saturating_add(DbWeight::get().writes(2_u64))135 } 135 }136 fn set_variable_meta_data_sponsoring_rate_limit() -> Weight {136 fn set_variable_meta_data_sponsoring_rate_limit() -> Weight {137 (3_500_000 as Weight)137 3_500_000_u64138 .saturating_add(DbWeight::get().reads(1 as Weight))138 .saturating_add(DbWeight::get().reads(1_u64))139 .saturating_add(DbWeight::get().writes(2 as Weight))139 .saturating_add(DbWeight::get().writes(2_u64))140 }140 }141 fn toggle_contract_white_list() -> Weight {141 fn toggle_contract_white_list() -> Weight {142 (3_000_000 as Weight)142 3_000_000_u64143 .saturating_add(DbWeight::get().reads(0 as Weight))143 .saturating_add(DbWeight::get().reads(0_u64))144 .saturating_add(DbWeight::get().writes(2 as Weight))144 .saturating_add(DbWeight::get().writes(2_u64))145 } 145 }146 fn add_to_contract_white_list() -> Weight {146 fn add_to_contract_white_list() -> Weight {147 (3_000_000 as Weight)147 3_000_000_u64148 .saturating_add(DbWeight::get().reads(0 as Weight))148 .saturating_add(DbWeight::get().reads(0_u64))149 .saturating_add(DbWeight::get().writes(2 as Weight))149 .saturating_add(DbWeight::get().writes(2_u64))150 } 150 }151 fn remove_from_contract_white_list() -> Weight {151 fn remove_from_contract_white_list() -> Weight {152 (3_200_000 as Weight)152 3_200_000_u64153 .saturating_add(DbWeight::get().reads(0 as Weight))153 .saturating_add(DbWeight::get().reads(0_u64))154 .saturating_add(DbWeight::get().writes(2 as Weight))154 .saturating_add(DbWeight::get().writes(2_u64))155 }155 }156 fn set_collection_limits() -> Weight {156 fn set_collection_limits() -> Weight {157 (8_900_000 as Weight)157 8_900_000_u64158 .saturating_add(DbWeight::get().reads(2 as Weight))158 .saturating_add(DbWeight::get().reads(2_u64))159 .saturating_add(DbWeight::get().writes(1 as Weight))159 .saturating_add(DbWeight::get().writes(1_u64))160 }160 }161}161}162162runtime_types.jsondiffbeforeafterboth11 "WhiteList"11 "WhiteList"12 ]12 ]13 },13 },14 "CallSpec": {15 "Module": "u32",16 "Method": "u32"17 },14 "DecimalPoints": "u8",18 "DecimalPoints": "u8",15 "CollectionMode": {19 "CollectionMode": {16 "_enum": {20 "_enum": {tests/.eslintrc.jsondiffbeforeafterbothno changes
tests/package.jsondiffbeforeafterboth14 "mocha": "^8.3.2",14 "mocha": "^8.3.2",15 "ts-node": "^9.1.1",15 "ts-node": "^9.1.1",16 "tslint": "^6.1.3",16 "tslint": "^6.1.3",17 "typescript": "^4.2.4"17 "typescript": "^4.2.4",18 "eslint": "^7.28.0",19 "@types/node": "^14.14.12",20 "@typescript-eslint/eslint-plugin": "^3.4.0",21 "@typescript-eslint/parser": "^3.4.0"18 },22 },19 "scripts": {23 "scripts": {24 "lint": "eslint --ext .ts,.js src/",25 "fix": "eslint --ext .ts,.js src/ --fix",20 "test": "mocha --timeout 9999999 -r ts-node/register ./**/*.test.ts",26 "test": "mocha --timeout 9999999 -r ts-node/register ./**/*.test.ts",21 "testEth": "mocha --timeout 9999999 -r ts-node/register ./**/eth/**/*.test.ts",27 "testEth": "mocha --timeout 9999999 -r ts-node/register ./**/eth/**/*.test.ts",22 "load": "mocha --timeout 9999999 -r ts-node/register ./**/*.load.ts",28 "load": "mocha --timeout 9999999 -r ts-node/register ./**/*.load.ts",tests/src/addToContractWhiteList.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import chai from "chai";6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";8import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';9import privateKey from "./substrate/privateKey";9import privateKey from './substrate/privateKey';10import {10import {11 deployFlipper11 deployFlipper,12} from "./util/contracthelpers";12} from './util/contracthelpers';13import {13import {14 getGenericResult, normalizeAccountId14 getGenericResult,15} from "./util/helpers"15} from './util/helpers';161617chai.use(chaiAsPromised);17chai.use(chaiAsPromised);18const expect = chai.expect;18const expect = chai.expect;191920describe('Integration Test addToContractWhiteList', () => {20describe('Integration Test addToContractWhiteList', () => {212122 it(`Add an address to a contract white list`, async () => {22 it('Add an address to a contract white list', async () => {23 await usingApi(async api => {23 await usingApi(async api => {24 const bob = privateKey("//Bob");24 const bob = privateKey('//Bob');25 const [contract, deployer] = await deployFlipper(api);25 const [contract, deployer] = await deployFlipper(api);262627 const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();27 const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();35 });35 });36 });36 });373738 it(`Adding same address to white list repeatedly should not produce errors`, async () => {38 it('Adding same address to white list repeatedly should not produce errors', async () => {39 await usingApi(async api => {39 await usingApi(async api => {40 const bob = privateKey("//Bob");40 const bob = privateKey('//Bob');41 const [contract, deployer] = await deployFlipper(api);41 const [contract, deployer] = await deployFlipper(api);424243 const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();43 const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();585859describe('Negative Integration Test addToContractWhiteList', () => {59describe('Negative Integration Test addToContractWhiteList', () => {606061 it(`Add an address to a white list of a non-contract`, async () => {61 it('Add an address to a white list of a non-contract', async () => {62 await usingApi(async api => {62 await usingApi(async api => {63 const alice = privateKey("//Bob");63 const alice = privateKey('//Bob');64 const bob = privateKey("//Bob");64 const bob = privateKey('//Bob');65 const charlieGuineaPig = privateKey("//Charlie");65 const charlieGuineaPig = privateKey('//Charlie');666667 const whiteListedBefore = (await api.query.nft.contractWhiteList(charlieGuineaPig.address, bob.address)).toJSON();67 const whiteListedBefore = (await api.query.nft.contractWhiteList(charlieGuineaPig.address, bob.address)).toJSON();68 const addTx = api.tx.nft.addToContractWhiteList(charlieGuineaPig.address, bob.address);68 const addTx = api.tx.nft.addToContractWhiteList(charlieGuineaPig.address, bob.address);74 });74 });75 });75 });767677 it(`Add to a contract white list using a non-owner address`, async () => {77 it('Add to a contract white list using a non-owner address', async () => {78 await usingApi(async api => {78 await usingApi(async api => {79 const bob = privateKey("//Bob");79 const bob = privateKey('//Bob');80 const [contract, deployer] = await deployFlipper(api);80 const [contract] = await deployFlipper(api);818182 const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();82 const whiteListedBefore = (await api.query.nft.contractWhiteList(contract.address, bob.address)).toJSON();83 const addTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);83 const addTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);tests/src/addToWhiteList.test.tsdiffbeforeafterboth27describe('Integration Test ext. addToWhiteList()', () => {
27describe('Integration Test ext. addToWhiteList()', () => {28
2829 before(async () => {
29 before(async () => {30 await usingApi(async (api) => {
30 await usingApi(async () => {31 Alice = privateKey('//Alice');
31 Alice = privateKey('//Alice');32 Bob = privateKey('//Bob');
32 Bob = privateKey('//Bob');33 });
33 });tests/src/approve.test.tsdiffbeforeafterboth82 let Charlie: IKeyringPair;82 let Charlie: IKeyringPair;838384 before(async () => {84 before(async () => {85 await usingApi(async (api) => {85 await usingApi(async () => {86 Alice = privateKey('//Alice');86 Alice = privateKey('//Alice');87 Bob = privateKey('//Bob');87 Bob = privateKey('//Bob');88 Charlie = privateKey('//Charlie');88 Charlie = privateKey('//Charlie');tests/src/block-production.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import usingApi from "./substrate/substrate-api";6import usingApi from './substrate/substrate-api';7import { expect } from "chai";7import { expect } from 'chai';8import { ApiPromise } from "@polkadot/api";8import { ApiPromise } from '@polkadot/api';9910const BlockTimeMs = 12000;10const BlockTimeMs = 12000;11const ToleranceMs = 1000;11const ToleranceMs = 1000;121213/* eslint no-async-promise-executor: "off" */13async function getBlocks(api: ApiPromise): Promise<number[]> {14function getBlocks(api: ApiPromise): Promise<number[]> {14 return new Promise<number[]>(async (resolve, reject) => {15 return new Promise<number[]>(async (resolve, reject) => {15 const blockNumbers: number[] = [];16 const blockNumbers: number[] = [];16 setTimeout(() => reject('Block production test failed due to timeout.'), BlockTimeMs + ToleranceMs);17 setTimeout(() => reject('Block production test failed due to timeout.'), BlockTimeMs + ToleranceMs);27describe('Block Production smoke test', () => {28describe('Block Production smoke test', () => {28 it('Node produces new blocks', async () => {29 it('Node produces new blocks', async () => {29 await usingApi(async (api) => {30 await usingApi(async (api) => {30 let blocks: number[] | undefined = await getBlocks(api);31 const blocks: number[] | undefined = await getBlocks(api);31 expect(blocks[0]).to.be.lessThan(blocks[1]);32 expect(blocks[0]).to.be.lessThan(blocks[1]);32 });33 });33 });34 });tests/src/burnItem.test.tsdiffbeforeafterboth4//4//556import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';6import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';7import { Keyring } from "@polkadot/api";7import { Keyring } from '@polkadot/api';8import { IKeyringPair } from "@polkadot/types/types";8import { IKeyringPair } from '@polkadot/types/types';9import { 9import { 10 createCollectionExpectSuccess, 10 createCollectionExpectSuccess, 11 createItemExpectSuccess,11 createItemExpectSuccess,12 getGenericResult,12 getGenericResult,13 destroyCollectionExpectSuccess,13 destroyCollectionExpectSuccess,14 normalizeAccountId14 normalizeAccountId,15} from './util/helpers';15} from './util/helpers';16import { nullPublicKey } from "./accounts";171618import chai from 'chai';17import chai from 'chai';19import chaiAsPromised from 'chai-as-promised';18import chaiAsPromised from 'chai-as-promised';252426describe('integration test: ext. burnItem():', () => {25describe('integration test: ext. burnItem():', () => {27 before(async () => {26 before(async () => {28 await usingApi(async (api) => {27 await usingApi(async () => {29 const keyring = new Keyring({ type: 'sr25519' });28 const keyring = new Keyring({ type: 'sr25519' });30 alice = keyring.addFromUri(`//Alice`);29 alice = keyring.addFromUri('//Alice');31 bob = keyring.addFromUri(`//Bob`);30 bob = keyring.addFromUri('//Bob');32 });31 });33 });32 });3433139138140describe('Negative integration test: ext. burnItem():', () => {139describe('Negative integration test: ext. burnItem():', () => {141 before(async () => {140 before(async () => {142 await usingApi(async (api) => {141 await usingApi(async () => {143 const keyring = new Keyring({ type: 'sr25519' });142 const keyring = new Keyring({ type: 'sr25519' });144 alice = keyring.addFromUri(`//Alice`);143 alice = keyring.addFromUri('//Alice');145 bob = keyring.addFromUri(`//Bob`);144 bob = keyring.addFromUri('//Bob');146 });145 });147 });146 });148147tests/src/change-collection-owner.test.tsdiffbeforeafterboth6import chai from 'chai';6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import privateKey from './substrate/privateKey';8import privateKey from './substrate/privateKey';9import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";9import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';10import { createCollectionExpectSuccess, createCollectionExpectFailure, normalizeAccountId } from "./util/helpers";10import { createCollectionExpectSuccess, normalizeAccountId } from './util/helpers';111112chai.use(chaiAsPromised);12chai.use(chaiAsPromised);13const expect = chai.expect;13const expect = chai.expect;32});32});333334describe('Negative Integration Test changeCollectionOwner(collection_id, new_owner):', () => {34describe('Negative Integration Test changeCollectionOwner(collection_id, new_owner):', () => {35 it(`Not owner can't change owner.`, async () => {35 it('Not owner can\'t change owner.', async () => {36 await usingApi(async api => {36 await usingApi(async api => {37 const collectionId = await createCollectionExpectSuccess();37 const collectionId = await createCollectionExpectSuccess();38 const alice = privateKey('//Alice');38 const alice = privateKey('//Alice');48 await createCollectionExpectSuccess();48 await createCollectionExpectSuccess();49 });49 });50 });50 });51 it(`Can't change owner of not existing collection.`, async () => {51 it('Can\'t change owner of not existing collection.', async () => {52 await usingApi(async api => {52 await usingApi(async api => {53 const collectionId = (1<<32) - 1;53 const collectionId = (1<<32) - 1;54 const alice = privateKey('//Alice');54 const alice = privateKey('//Alice');tests/src/check-event/createItemEvent.test.tsdiffbeforeafterboth10import chaiAsPromised from 'chai-as-promised';10import chaiAsPromised from 'chai-as-promised';11import privateKey from '../substrate/privateKey';11import privateKey from '../substrate/privateKey';12import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';12import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';13import { createCollectionExpectSuccess, createItemExpectSuccess, nftEventMessage } from '../util/helpers';13import { createCollectionExpectSuccess, nftEventMessage } from '../util/helpers';141415chai.use(chaiAsPromised);15chai.use(chaiAsPromised);16const expect = chai.expect;16const expect = chai.expect;tests/src/check-event/createMultipleItemsEvent.test.tsdiffbeforeafterboth10import chaiAsPromised from 'chai-as-promised';10import chaiAsPromised from 'chai-as-promised';11import privateKey from '../substrate/privateKey';11import privateKey from '../substrate/privateKey';12import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';12import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';13import { createCollectionExpectSuccess, createItemExpectSuccess, nftEventMessage } from '../util/helpers';13import { createCollectionExpectSuccess, nftEventMessage } from '../util/helpers';141415chai.use(chaiAsPromised);15chai.use(chaiAsPromised);16const expect = chai.expect;16const expect = chai.expect;tests/src/collision-tests/admVsOwnerChanges.test.tsdiffbeforeafterboth1import { IKeyringPair } from '@polkadot/types/types';
1import { IKeyringPair } from '@polkadot/types/types';2import chai from 'chai';
2import chai from 'chai';3import chaiAsPromised from 'chai-as-promised';
3import chaiAsPromised from 'chai-as-promised';4import { alicesPublicKey, bobsPublicKey } from '../accounts';
5import getBalance from '../substrate/get-balance';
6import privateKey from '../substrate/privateKey';
4import privateKey from '../substrate/privateKey';7import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
5import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';8import waitNewBlocks from '../substrate/wait-new-blocks';
9import {
6import {10 createCollectionExpectSuccess,
7 createCollectionExpectSuccess,11 createItemExpectSuccess,
8 createItemExpectSuccess,12 setCollectionSponsorExpectSuccess,
13} from '../util/helpers';
9} from '../util/helpers';14
1015chai.use(chaiAsPromised);
11chai.use(chaiAsPromised);tests/src/collision-tests/admVsOwnerData.test.tsdiffbeforeafterboth1import { IKeyringPair } from '@polkadot/types/types';
1import { IKeyringPair } from '@polkadot/types/types';2import chai from 'chai';
2import chai from 'chai';3import chaiAsPromised from 'chai-as-promised';
3import chaiAsPromised from 'chai-as-promised';4import { alicesPublicKey, bobsPublicKey } from '../accounts';
5import getBalance from '../substrate/get-balance';
6import privateKey from '../substrate/privateKey';
4import privateKey from '../substrate/privateKey';7import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
5import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';8import waitNewBlocks from '../substrate/wait-new-blocks';
9import {
6import {10 createCollectionExpectSuccess,
7 createCollectionExpectSuccess,11 createItemExpectSuccess,
8 createItemExpectSuccess,12 setCollectionSponsorExpectSuccess,
13} from '../util/helpers';
9} from '../util/helpers';14
1015chai.use(chaiAsPromised);
11chai.use(chaiAsPromised);16const expect = chai.expect;
12const expect = chai.expect;17let Alice: IKeyringPair;
13let Alice: IKeyringPair;18let Bob: IKeyringPair;
14let Bob: IKeyringPair;19let Ferdie: IKeyringPair;
1520
21before(async () => {
16before(async () => {22 await usingApi(async () => {
17 await usingApi(async () => {23 Alice = privateKey('//Alice');
18 Alice = privateKey('//Alice');24 Bob = privateKey('//Bob');
19 Bob = privateKey('//Bob');25 Ferdie = privateKey('//Ferdie');
26 });
20 });27});
21});28
22tests/src/collision-tests/admVsOwnerTake.test.tsdiffbeforeafterboth1import { IKeyringPair } from '@polkadot/types/types';
1import { IKeyringPair } from '@polkadot/types/types';2import chai from 'chai';
2import chai from 'chai';3import chaiAsPromised from 'chai-as-promised';
3import chaiAsPromised from 'chai-as-promised';4import { alicesPublicKey, bobsPublicKey } from '../accounts';
5import getBalance from '../substrate/get-balance';
6import privateKey from '../substrate/privateKey';
4import privateKey from '../substrate/privateKey';7import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
5import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';8import waitNewBlocks from '../substrate/wait-new-blocks';
9import {
6import {10 createCollectionExpectSuccess,
7 createCollectionExpectSuccess,11 createItemExpectSuccess,
8 createItemExpectSuccess,12 setCollectionSponsorExpectSuccess,
13} from '../util/helpers';
9} from '../util/helpers';14
1015chai.use(chaiAsPromised);
11chai.use(chaiAsPromised);44 burnItem.signAndSend(Alice),
39 burnItem.signAndSend(Alice),45 ]);
40 ]);46 await timeoutPromise(10000);
41 await timeoutPromise(10000);47 let itemBurn: boolean = false;
42 let itemBurn = false;48 itemBurn = (await (api.query.nft.nftItemList(collectionId, itemId))).toJSON() as boolean;
43 itemBurn = (await (api.query.nft.nftItemList(collectionId, itemId))).toJSON() as boolean;49 // tslint:disable-next-line: no-unused-expression
44 // tslint:disable-next-line: no-unused-expression50 expect(itemBurn).to.be.null;
45 expect(itemBurn).to.be.null;tests/src/collision-tests/adminDestroyCollection.test.tsdiffbeforeafterboth1import { IKeyringPair } from '@polkadot/types/types';1import { IKeyringPair } from '@polkadot/types/types';2import BN from 'bn.js';3import chai from 'chai';2import chai from 'chai';4import chaiAsPromised from 'chai-as-promised';3import chaiAsPromised from 'chai-as-promised';5import privateKey from '../substrate/privateKey';4import privateKey from '../substrate/privateKey';6import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';5import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';7import {6import {8 createCollectionExpectSuccess,7 createCollectionExpectSuccess,9} from '../util/helpers';8} from '../util/helpers';10911chai.use(chaiAsPromised);10chai.use(chaiAsPromised);12const expect = chai.expect;11const expect = chai.expect;13interface ITokenDataType {14 Owner: number[];15 ConstData: number[];16 VariableData: number[];17}18let Alice: IKeyringPair;12let Alice: IKeyringPair;19let Bob: IKeyringPair;13let Bob: IKeyringPair;20let Ferdie: IKeyringPair;14let Ferdie: IKeyringPair;21let Charlie: IKeyringPair;22let Eve: IKeyringPair;23let Dave: IKeyringPair;241525before(async () => {16before(async () => {26 await usingApi(async () => {17 await usingApi(async () => {27 Alice = privateKey('//Alice');18 Alice = privateKey('//Alice');28 Bob = privateKey('//Bob');19 Bob = privateKey('//Bob');29 Ferdie = privateKey('//Ferdie');20 Ferdie = privateKey('//Ferdie');30 Charlie = privateKey('//Charlie');31 Eve = privateKey('//Eve');32 Dave = privateKey('//Dave');33 });21 });34});22});352351 destroyCollection.signAndSend(Alice),38 destroyCollection.signAndSend(Alice),52 ]);39 ]);53 await timeoutPromise(10000);40 await timeoutPromise(10000);54 let whiteList: boolean = false;41 let whiteList = false;55 whiteList = (await api.query.nft.whiteList(collectionId, Ferdie.address)).toJSON() as boolean;42 whiteList = (await api.query.nft.whiteList(collectionId, Ferdie.address)).toJSON() as boolean;56 // tslint:disable-next-line: no-unused-expression43 // tslint:disable-next-line: no-unused-expression57 expect(whiteList).to.be.false;44 expect(whiteList).to.be.false;tests/src/collision-tests/adminLimitsOff.test.tsdiffbeforeafterboth101011chai.use(chaiAsPromised);11chai.use(chaiAsPromised);12const expect = chai.expect;12const expect = chai.expect;13interface ITokenDataType {14 Owner: number[];15 ConstData: number[];16 VariableData: number[];17}18let Alice: IKeyringPair;13let Alice: IKeyringPair;19let Bob: IKeyringPair;14let Bob: IKeyringPair;20let Ferdie: IKeyringPair;15let Ferdie: IKeyringPair;51 await submitTransactionAsync(Alice, changeAdminTx3);46 await submitTransactionAsync(Alice, changeAdminTx3);524753 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));48 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));54 //55 const addAdmOne = api.tx.nft.addCollectionAdmin(collectionId, Ferdie.address);49 const addAdmOne = api.tx.nft.addCollectionAdmin(collectionId, Ferdie.address);56 const addAdmTwo = api.tx.nft.addCollectionAdmin(collectionId, Charlie.address);50 const addAdmTwo = api.tx.nft.addCollectionAdmin(collectionId, Charlie.address);57 await Promise.all51 await Promise.all([tests/src/collision-tests/adminRightsOff.test.tsdiffbeforeafterboth3import chai from 'chai';3import chai from 'chai';4import chaiAsPromised from 'chai-as-promised';4import chaiAsPromised from 'chai-as-promised';5import privateKey from '../substrate/privateKey';5import privateKey from '../substrate/privateKey';6import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';6import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';7import {7import {8 createCollectionExpectSuccess,8 createCollectionExpectSuccess,9} from '../util/helpers';9} from '../util/helpers';101011chai.use(chaiAsPromised);11chai.use(chaiAsPromised);12const expect = chai.expect;12const expect = chai.expect;13interface ITokenDataType {14 Owner: number[];15 ConstData: number[];16 VariableData: number[];17}18let Alice: IKeyringPair;13let Alice: IKeyringPair;19let Bob: IKeyringPair;14let Bob: IKeyringPair;20let Ferdie: IKeyringPair;21let Charlie: IKeyringPair;22let Eve: IKeyringPair;23let Dave: IKeyringPair;241525before(async () => {16before(async () => {26 await usingApi(async () => {17 await usingApi(async () => {27 Alice = privateKey('//Alice');18 Alice = privateKey('//Alice');28 Bob = privateKey('//Bob');19 Bob = privateKey('//Bob');29 Ferdie = privateKey('//Ferdie');30 Charlie = privateKey('//Charlie');31 Eve = privateKey('//Eve');32 Dave = privateKey('//Dave');33 });20 });34});21});352242 await submitTransactionAsync(Alice, changeAdminTx);29 await submitTransactionAsync(Alice, changeAdminTx);43 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));30 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));44 await timeoutPromise(10000);31 await timeoutPromise(10000);45 //46 const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];32 const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];47 const addItemAdm = api.tx.nft.createMultipleItems(collectionId, Bob.address, args);33 const addItemAdm = api.tx.nft.createMultipleItems(collectionId, Bob.address, args);48 const removeAdm = api.tx.nft.removeCollectionAdmin(collectionId, Bob.address);34 const removeAdm = api.tx.nft.removeCollectionAdmin(collectionId, Bob.address);tests/src/collision-tests/setSponsorNewOwner.test.tsdiffbeforeafterboth1import { IKeyringPair } from '@polkadot/types/types';1import { IKeyringPair } from '@polkadot/types/types';2import BN from 'bn.js';3import chai from 'chai';2import chai from 'chai';4import chaiAsPromised from 'chai-as-promised';3import chaiAsPromised from 'chai-as-promised';5import privateKey from '../substrate/privateKey';4import privateKey from '../substrate/privateKey';6import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';5import usingApi from '../substrate/substrate-api';7import {6import {8 createCollectionExpectSuccess, createItemExpectSuccess, setCollectionSponsorExpectSuccess,7 createCollectionExpectSuccess, setCollectionSponsorExpectSuccess,9} from '../util/helpers';8} from '../util/helpers';10911chai.use(chaiAsPromised);10chai.use(chaiAsPromised);12const expect = chai.expect;11const expect = chai.expect;13interface ITokenDataType {14 Owner: number[];15 ConstData: number[];16 VariableData: number[];17}18let Alice: IKeyringPair;12let Alice: IKeyringPair;19let Bob: IKeyringPair;13let Bob: IKeyringPair;20let Ferdie: IKeyringPair;14let Ferdie: IKeyringPair;35 await setCollectionSponsorExpectSuccess(collectionId, Bob.address);29 await setCollectionSponsorExpectSuccess(collectionId, Bob.address);36 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));30 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));37 await timeoutPromise(10000);31 await timeoutPromise(10000);38 //39 const confirmSponsorship = api.tx.nft.confirmSponsorship(collectionId);32 const confirmSponsorship = api.tx.nft.confirmSponsorship(collectionId);40 const changeCollectionOwner = api.tx.nft.changeCollectionOwner(collectionId, Ferdie.address);33 const changeCollectionOwner = api.tx.nft.changeCollectionOwner(collectionId, Ferdie.address);41 await Promise.all34 await Promise.all([tests/src/collision-tests/sponsorPayments.test.tsdiffbeforeafterboth5import getBalance from '../substrate/get-balance';
5import getBalance from '../substrate/get-balance';6import privateKey from '../substrate/privateKey';
6import privateKey from '../substrate/privateKey';7import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
7import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';8import waitNewBlocks from '../substrate/wait-new-blocks';
9import {
8import {10 confirmSponsorshipExpectSuccess,
9 confirmSponsorshipExpectSuccess,11 createCollectionExpectSuccess,
10 createCollectionExpectSuccess,17const expect = chai.expect;
16const expect = chai.expect;18let Alice: IKeyringPair;
17let Alice: IKeyringPair;19let Bob: IKeyringPair;
18let Bob: IKeyringPair;20let Ferdie: IKeyringPair;
1921
22before(async () => {
20before(async () => {23 await usingApi(async () => {
21 await usingApi(async () => {24 Alice = privateKey('//Alice');
22 Alice = privateKey('//Alice');25 Bob = privateKey('//Bob');
23 Bob = privateKey('//Bob');26 Ferdie = privateKey('//Ferdie');
27 });
24 });28});
25});29
2638 const itemId = await createItemExpectSuccess(Bob, collectionId, 'NFT');
35 const itemId = await createItemExpectSuccess(Bob, collectionId, 'NFT');39 await setCollectionSponsorExpectSuccess(collectionId, Bob.address);
36 await setCollectionSponsorExpectSuccess(collectionId, Bob.address);40 await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
37 await confirmSponsorshipExpectSuccess(collectionId, '//Bob');41 //
3842 const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);
39 const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);43 const sendItem = api.tx.nft.transfer(Alice.address, collectionId, itemId, 1);
40 const sendItem = api.tx.nft.transfer(Alice.address, collectionId, itemId, 1);44 const revokeSponsor = api.tx.nft.removeCollectionSponsor(collectionId);
41 const revokeSponsor = api.tx.nft.removeCollectionSponsor(collectionId);tests/src/collision-tests/tokenLimitsOff.test.tsdiffbeforeafterboth131314chai.use(chaiAsPromised);14chai.use(chaiAsPromised);15const expect = chai.expect;15const expect = chai.expect;16interface ITokenDataType {17 Owner: number[];18 ConstData: number[];19 VariableData: number[];20}21let Alice: IKeyringPair;16let Alice: IKeyringPair;22let Bob: IKeyringPair;17let Bob: IKeyringPair;23let Ferdie: IKeyringPair;18let Ferdie: IKeyringPair;63 expect(subTxTesult.success).to.be.true;58 expect(subTxTesult.success).to.be.true;64 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));59 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));65 await timeoutPromise(10000);60 await timeoutPromise(10000);66 //6167 const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];62 const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];68 const mintItemOne = api.tx.nft63 const mintItemOne = api.tx.nft69 .createMultipleItems(collectionId, Ferdie.address, args);64 .createMultipleItems(collectionId, Ferdie.address, args);tests/src/collision-tests/turnsOffMinting.test.tsdiffbeforeafterboth2import chai from 'chai';
2import chai from 'chai';3import chaiAsPromised from 'chai-as-promised';
3import chaiAsPromised from 'chai-as-promised';4import privateKey from '../substrate/privateKey';
4import privateKey from '../substrate/privateKey';5import usingApi, { submitTransactionAsync } from '../substrate/substrate-api';
5import usingApi from '../substrate/substrate-api';6import waitNewBlocks from '../substrate/wait-new-blocks';
7import {
6import {8 addToWhiteListExpectSuccess,
7 addToWhiteListExpectSuccess,9 createCollectionExpectSuccess,
8 createCollectionExpectSuccess,13chai.use(chaiAsPromised);
12chai.use(chaiAsPromised);14const expect = chai.expect;
13const expect = chai.expect;15let Alice: IKeyringPair;
14let Alice: IKeyringPair;16let Bob: IKeyringPair;
17let Ferdie: IKeyringPair;
15let Ferdie: IKeyringPair;18
1619before(async () => {
17before(async () => {20 await usingApi(async () => {
18 await usingApi(async () => {21 Alice = privateKey('//Alice');
19 Alice = privateKey('//Alice');22 Bob = privateKey('//Bob');
23 Ferdie = privateKey('//Ferdie');
20 Ferdie = privateKey('//Ferdie');24 });
21 });25});
22});32 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));
29 const timeoutPromise = (timeout: number) => new Promise((resolve) => setTimeout(resolve, timeout));33 await setMintPermissionExpectSuccess(Alice, collectionId, true);
30 await setMintPermissionExpectSuccess(Alice, collectionId, true);34 await addToWhiteListExpectSuccess(Alice, collectionId, Ferdie.address);
31 await addToWhiteListExpectSuccess(Alice, collectionId, Ferdie.address);35 //
3236 const mintItem = api.tx.nft.createItem(collectionId, Ferdie.address, 'NFT');
33 const mintItem = api.tx.nft.createItem(collectionId, Ferdie.address, 'NFT');37 const offMinting = api.tx.nft.setMintPermission(collectionId, false);
34 const offMinting = api.tx.nft.setMintPermission(collectionId, false);38 await Promise.all
35 await Promise.all([39 ([
40 mintItem.signAndSend(Ferdie),
36 mintItem.signAndSend(Ferdie),41 offMinting.signAndSend(Alice),
37 offMinting.signAndSend(Alice),42 ]);
38 ]);43 let itemList: boolean = false;
39 let itemList = false;44 itemList = (await (api.query.nft.nftItemList(collectionId, mintItem))).toJSON() as boolean;
40 itemList = (await (api.query.nft.nftItemList(collectionId, mintItem))).toJSON() as boolean;45 // tslint:disable-next-line: no-unused-expression
41 // tslint:disable-next-line: no-unused-expression46 expect(itemList).to.be.null;
42 expect(itemList).to.be.null;tests/src/config.tsdiffbeforeafterboth6import process from 'process';6import process from 'process';778const config = {8const config = {9 substrateUrl: process.env.substrateUrl || 'ws://127.0.0.1:9944'9 substrateUrl: process.env.substrateUrl || 'ws://127.0.0.1:9844',10}10};111112export default config;12export default config;tests/src/config_docker.tsdiffbeforeafterboth778const config = {8const config = {9 substrateUrl: process.env.substrateUrl || 'ws://172.17.0.1:9944'9 substrateUrl: process.env.substrateUrl || 'ws://172.17.0.1:9944',10}10};111112export default config;12export default config;tests/src/confirmSponsorship.test.tsdiffbeforeafterboth556import chai from 'chai';6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";8import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';9import { 9import { 10 createCollectionExpectSuccess, 10 createCollectionExpectSuccess, 11 setCollectionSponsorExpectSuccess, 11 setCollectionSponsorExpectSuccess, 12 destroyCollectionExpectSuccess, 12 destroyCollectionExpectSuccess, 13 setCollectionSponsorExpectFailure,14 confirmSponsorshipExpectSuccess,13 confirmSponsorshipExpectSuccess,15 confirmSponsorshipExpectFailure,14 confirmSponsorshipExpectFailure,16 createItemExpectSuccess,15 createItemExpectSuccess,20 enablePublicMintingExpectSuccess,19 enablePublicMintingExpectSuccess,21 addToWhiteListExpectSuccess,20 addToWhiteListExpectSuccess,22 normalizeAccountId,21 normalizeAccountId,23} from "./util/helpers";22} from './util/helpers';24import { Keyring } from "@polkadot/api";23import { Keyring } from '@polkadot/api';25import { IKeyringPair } from "@polkadot/types/types";24import { IKeyringPair } from '@polkadot/types/types';26import type { AccountId } from '@polkadot/types/interfaces';27import { BigNumber } from 'bignumber.js';25import { BigNumber } from 'bignumber.js';282629chai.use(chaiAsPromised);27chai.use(chaiAsPromised);36describe('integration test: ext. confirmSponsorship():', () => {34describe('integration test: ext. confirmSponsorship():', () => {373538 before(async () => {36 before(async () => {39 await usingApi(async (api) => {37 await usingApi(async () => {40 const keyring = new Keyring({ type: 'sr25519' });38 const keyring = new Keyring({ type: 'sr25519' });41 alice = keyring.addFromUri(`//Alice`);39 alice = keyring.addFromUri('//Alice');42 bob = keyring.addFromUri(`//Bob`);40 bob = keyring.addFromUri('//Bob');43 charlie = keyring.addFromUri(`//Charlie`);41 charlie = keyring.addFromUri('//Charlie');44 });42 });45 });43 });4644163 await addToWhiteListExpectSuccess(alice, collectionId, zeroBalance.address);161 await addToWhiteListExpectSuccess(alice, collectionId, zeroBalance.address);164162165 // Mint token using unused address as signer163 // Mint token using unused address as signer166 const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT', zeroBalance.address);164 await createItemExpectSuccess(zeroBalance, collectionId, 'NFT', zeroBalance.address);167165168 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());166 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());169167195 const badTransaction = async function () { 193 const badTransaction = async function () { 196 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);194 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);197 };195 };198 await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");196 await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');199 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());197 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());200198201 // Try again after Zero gets some balance - now it should succeed199 // Try again after Zero gets some balance - now it should succeed229227230 const AsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());228 const AsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());231232 const badTransaction = async function () { 233 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);229 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);234 };235236 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());230 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());237231271 const badTransaction = async function () { 265 const badTransaction = async function () { 272 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);266 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);273 };267 };274 await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");268 await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');275 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());269 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());276270277 // Try again after Zero gets some balance - now it should succeed271 // Try again after Zero gets some balance - now it should succeed317 const badTransaction = async function () { 311 const badTransaction = async function () { 318 await createItemExpectSuccess(zeroBalance, collectionId, 'NFT', zeroBalance.address);312 await createItemExpectSuccess(zeroBalance, collectionId, 'NFT', zeroBalance.address);319 };313 };320 await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");314 await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');321 console.error = consoleError;315 console.error = consoleError;322 console.log = consoleLog;316 console.log = consoleLog;323 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());317 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());335329336describe('(!negative test!) integration test: ext. removeCollectionSponsor():', () => {330describe('(!negative test!) integration test: ext. removeCollectionSponsor():', () => {337 before(async () => {331 before(async () => {338 await usingApi(async (api) => {332 await usingApi(async () => {339 const keyring = new Keyring({ type: 'sr25519' });333 const keyring = new Keyring({ type: 'sr25519' });340 alice = keyring.addFromUri(`//Alice`);334 alice = keyring.addFromUri('//Alice');341 bob = keyring.addFromUri(`//Bob`);335 bob = keyring.addFromUri('//Bob');342 charlie = keyring.addFromUri(`//Charlie`);336 charlie = keyring.addFromUri('//Charlie');343 });337 });344 });338 });345339346 it('(!negative test!) Confirm sponsorship for a collection that never existed', async () => {340 it('(!negative test!) Confirm sponsorship for a collection that never existed', async () => {347 // Find the collection that never existed341 // Find the collection that never existed348 const collectionId = 0;342 let collectionId = 0;349 await usingApi(async (api) => {343 await usingApi(async (api) => {350 const collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;344 collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;351 });345 });352346353 await confirmSponsorshipExpectFailure(collectionId, '//Bob');347 await confirmSponsorshipExpectFailure(collectionId, '//Bob');tests/src/connection.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import usingApi from "./substrate/substrate-api";6import usingApi from './substrate/substrate-api';7import { WsProvider } from '@polkadot/api';7import { WsProvider } from '@polkadot/api';8import * as chai from 'chai';8import * as chai from 'chai';9import chaiAsPromised from 'chai-as-promised';9import chaiAsPromised from 'chai-as-promised';29 const neverConnectProvider = new WsProvider('ws://255.255.255.255:9944');29 const neverConnectProvider = new WsProvider('ws://255.255.255.255:9944');30 await expect((async () => {30 await expect((async () => {31 await usingApi(async api => {31 await usingApi(async api => {32 const health = await api.rpc.system.health();32 await api.rpc.system.health();33 }, { provider: neverConnectProvider });33 }, { provider: neverConnectProvider });34 })()).to.be.eventually.rejected;34 })()).to.be.eventually.rejected;3535tests/src/contracts.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import chai from "chai";6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";8import usingApi, { submitTransactionAsync } from './substrate/substrate-api';9import fs from "fs";9import fs from 'fs';10import { Abi, ContractPromise as Contract } from "@polkadot/api-contract";10import { Abi, ContractPromise as Contract } from '@polkadot/api-contract';11import privateKey from "./substrate/privateKey";11import privateKey from './substrate/privateKey';12import {12import {13 deployFlipper,13 deployFlipper,14 getFlipValue,14 getFlipValue,15 deployTransferContract,15 deployTransferContract,16} from "./util/contracthelpers";16} from './util/contracthelpers';171718import {18import {19 addToWhiteListExpectSuccess,19 addToWhiteListExpectSuccess,25 getGenericResult,25 getGenericResult,26 normalizeAccountId,26 normalizeAccountId,27 isWhitelisted,27 isWhitelisted,28 transferFromExpectSuccess28 transferFromExpectSuccess,29} from "./util/helpers";29} from './util/helpers';3030313132chai.use(chaiAsPromised);32chai.use(chaiAsPromised);37const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';37const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';383839describe('Contracts', () => {39describe('Contracts', () => {40 it(`Can deploy smart contract Flipper, instantiate it and call it's get and flip messages.`, async () => {40 it('Can deploy smart contract Flipper, instantiate it and call it\'s get and flip messages.', async () => {41 await usingApi(async api => {41 await usingApi(async api => {42 const [contract, deployer] = await deployFlipper(api);42 const [contract, deployer] = await deployFlipper(api);43 const initialGetResponse = await getFlipValue(contract, deployer);43 const initialGetResponse = await getFlipValue(contract, deployer);444445 const bob = privateKey("//Bob");45 const bob = privateKey('//Bob');46 const flip = contract.tx.flip(value, gasLimit);46 const flip = contract.tx.flip(value, gasLimit);47 await submitTransactionAsync(bob, flip);47 await submitTransactionAsync(bob, flip);484865describe.only('Chain extensions', () => {65describe.only('Chain extensions', () => {66 it('Transfer CE', async () => {66 it('Transfer CE', async () => {67 await usingApi(async api => {67 await usingApi(async api => {68 const alice = privateKey("//Alice");68 const alice = privateKey('//Alice');69 const bob = privateKey("//Bob");69 const bob = privateKey('//Bob');707071 // Prep work71 // Prep work72 const collectionId = await createCollectionExpectSuccess();72 const collectionId = await createCollectionExpectSuccess();73 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');73 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');74 const [contract, deployer] = await deployTransferContract(api);74 const [contract] = await deployTransferContract(api);75 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);75 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);76 await submitTransactionAsync(alice, changeAdminTx);76 await submitTransactionAsync(alice, changeAdminTx);777796 const bob = privateKey('//Bob');96 const bob = privateKey('//Bob');979798 const collectionId = await createCollectionExpectSuccess();98 const collectionId = await createCollectionExpectSuccess();99 const [contract, deployer] = await deployTransferContract(api);99 const [contract] = await deployTransferContract(api);100 await enablePublicMintingExpectSuccess(alice, collectionId);100 await enablePublicMintingExpectSuccess(alice, collectionId);101 await enableWhiteListExpectSuccess(alice, collectionId);101 await enableWhiteListExpectSuccess(alice, collectionId);102 await addToWhiteListExpectSuccess(alice, collectionId, contract.address);102 await addToWhiteListExpectSuccess(alice, collectionId, contract.address);124 const bob = privateKey('//Bob');124 const bob = privateKey('//Bob');125125126 const collectionId = await createCollectionExpectSuccess();126 const collectionId = await createCollectionExpectSuccess();127 const [contract, deployer] = await deployTransferContract(api);127 const [contract] = await deployTransferContract(api);128 await enablePublicMintingExpectSuccess(alice, collectionId);128 await enablePublicMintingExpectSuccess(alice, collectionId);129 await enableWhiteListExpectSuccess(alice, collectionId);129 await enableWhiteListExpectSuccess(alice, collectionId);130 await addToWhiteListExpectSuccess(alice, collectionId, contract.address);130 await addToWhiteListExpectSuccess(alice, collectionId, contract.address);169 const charlie = privateKey('//Charlie');169 const charlie = privateKey('//Charlie');170170171 const collectionId = await createCollectionExpectSuccess();171 const collectionId = await createCollectionExpectSuccess();172 const [contract, deployer] = await deployTransferContract(api);172 const [contract] = await deployTransferContract(api);173 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address.toString());173 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address.toString());174174175 const transferTx = contract.tx.approve(value, gasLimit, bob.address, collectionId, tokenId, 1);175 const transferTx = contract.tx.approve(value, gasLimit, bob.address, collectionId, tokenId, 1);188 const charlie = privateKey('//Charlie');188 const charlie = privateKey('//Charlie');189189190 const collectionId = await createCollectionExpectSuccess();190 const collectionId = await createCollectionExpectSuccess();191 const [contract, deployer] = await deployTransferContract(api);191 const [contract] = await deployTransferContract(api);192 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);192 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);193 await approveExpectSuccess(collectionId, tokenId, bob, contract.address.toString(), 1);193 await approveExpectSuccess(collectionId, tokenId, bob, contract.address.toString(), 1);194194197 const result = getGenericResult(events);197 const result = getGenericResult(events);198 expect(result.success).to.be.true;198 expect(result.success).to.be.true;199199200 const token: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap()200 const token: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap();201 expect(token.Owner.toString()).to.be.equal(charlie.address);201 expect(token.Owner.toString()).to.be.equal(charlie.address);202 });202 });203 });203 });207 const alice = privateKey('//Alice');207 const alice = privateKey('//Alice');208208209 const collectionId = await createCollectionExpectSuccess();209 const collectionId = await createCollectionExpectSuccess();210 const [contract, deployer] = await deployTransferContract(api);210 const [contract] = await deployTransferContract(api);211 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address.toString());211 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address.toString());212212213 const transferTx = contract.tx.setVariableMetaData(value, gasLimit, collectionId, tokenId, '0x121314');213 const transferTx = contract.tx.setVariableMetaData(value, gasLimit, collectionId, tokenId, '0x121314');214 const events = await submitTransactionAsync(alice, transferTx);214 const events = await submitTransactionAsync(alice, transferTx);215 const result = getGenericResult(events);215 const result = getGenericResult(events);216 expect(result.success).to.be.true;216 expect(result.success).to.be.true;217217218 const token: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap()218 const token: any = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap();219 expect(token.VariableData.toString()).to.be.equal('0x121314');219 expect(token.VariableData.toString()).to.be.equal('0x121314');220 });220 });221 });221 });226 const bob = privateKey('//Bob');226 const bob = privateKey('//Bob');227227228 const collectionId = await createCollectionExpectSuccess();228 const collectionId = await createCollectionExpectSuccess();229 const [contract, deployer] = await deployTransferContract(api);229 const [contract] = await deployTransferContract(api);230 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);230 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, contract.address);231 await submitTransactionAsync(alice, changeAdminTx); 231 await submitTransactionAsync(alice, changeAdminTx); 232232tests/src/createItem.test.tsdiffbeforeafterboth4//
4//5
56import { default as usingApi } from './substrate/substrate-api';
6import { default as usingApi } from './substrate/substrate-api';7import { Keyring } from "@polkadot/api";
7import { Keyring } from '@polkadot/api';8import { IKeyringPair } from "@polkadot/types/types";
8import { IKeyringPair } from '@polkadot/types/types';9import {
9import { 10 createCollectionExpectSuccess,
10 createCollectionExpectSuccess, 11 createItemExpectSuccess
11 createItemExpectSuccess,12} from './util/helpers';
12} from './util/helpers';13
1314let alice: IKeyringPair;
14let alice: IKeyringPair;15
1516describe('integration test: ext. createItem():', () => {
16describe('integration test: ext. createItem():', () => {17 before(async () => {
17 before(async () => {18 await usingApi(async (api) => {
18 await usingApi(async () => {19 const keyring = new Keyring({ type: 'sr25519' });
19 const keyring = new Keyring({ type: 'sr25519' });20 alice = keyring.addFromUri(`//Alice`);
20 alice = keyring.addFromUri('//Alice');21 });
21 });22 });
22 });23
23tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth556import chai from 'chai';6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";8import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';9import { alicesPublicKey, bobsPublicKey } from "./accounts";9import { alicesPublicKey, bobsPublicKey } from './accounts';10import privateKey from "./substrate/privateKey";10import privateKey from './substrate/privateKey';11import { BigNumber } from 'bignumber.js';11import { BigNumber } from 'bignumber.js';12import { IKeyringPair } from '@polkadot/types/types';12import { IKeyringPair } from '@polkadot/types/types';13import { 13import { 14 createCollectionExpectSuccess, 14 createCollectionExpectSuccess, 15 createItemExpectSuccess,15 createItemExpectSuccess,16 getGenericResult,16 getGenericResult,17 transferExpectSuccess17 transferExpectSuccess,18} from './util/helpers';18} from './util/helpers';191920import { default as waitNewBlocks } from './substrate/wait-new-blocks';20import { default as waitNewBlocks } from './substrate/wait-new-blocks';23chai.use(chaiAsPromised);23chai.use(chaiAsPromised);24const expect = chai.expect;24const expect = chai.expect;252526const Treasury = "5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z";26const Treasury = '5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z';27const saneMinimumFee = 0.05;27const saneMinimumFee = 0.05;28const saneMaximumFee = 0.5;28const saneMaximumFee = 0.5;29const createCollectionDeposit = 100;29const createCollectionDeposit = 100;333334// Skip the inflation block pauses if the block is close to inflation block 34// Skip the inflation block pauses if the block is close to inflation block 35// until the inflation happens35// until the inflation happens36/*eslint no-async-promise-executor: "off"*/36function skipInflationBlock(api: ApiPromise): Promise<void> {37function skipInflationBlock(api: ApiPromise): Promise<void> {37 const promise = new Promise<void>(async (resolve, reject) => {38 const promise = new Promise<void>(async (resolve) => {38 const blockInterval = parseInt((await api.consts.inflation.inflationBlockInterval).toString());39 const blockInterval = parseInt((await api.consts.inflation.inflationBlockInterval).toString());39 const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {40 const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {40 const currentBlock = parseInt(head.number.toString());41 const currentBlock = parseInt(head.number.toString());525353describe('integration test: Fees must be credited to Treasury:', () => {54describe('integration test: Fees must be credited to Treasury:', () => {54 before(async () => {55 before(async () => {55 await usingApi(async (api) => {56 await usingApi(async () => {56 alice = privateKey('//Alice');57 alice = privateKey('//Alice');57 bob = privateKey('//Bob');58 bob = privateKey('//Bob');58 });59 });tests/src/destroyCollection.test.tsdiffbeforeafterboth7import chai from 'chai';7import chai from 'chai';8import chaiAsPromised from 'chai-as-promised';8import chaiAsPromised from 'chai-as-promised';9import privateKey from './substrate/privateKey';9import privateKey from './substrate/privateKey';10import { default as usingApi } from "./substrate/substrate-api";10import { default as usingApi } from './substrate/substrate-api';11import { createCollectionExpectSuccess, destroyCollectionExpectSuccess, destroyCollectionExpectFailure, setCollectionLimitsExpectSuccess } from "./util/helpers";11import { createCollectionExpectSuccess, destroyCollectionExpectSuccess, destroyCollectionExpectFailure, setCollectionLimitsExpectSuccess } from './util/helpers';121213chai.use(chaiAsPromised);13chai.use(chaiAsPromised);141431 let alice: IKeyringPair;31 let alice: IKeyringPair;323233 before(async () => {33 before(async () => {34 await usingApi(async (api) => {34 await usingApi(async () => {35 alice = privateKey('//Alice');35 alice = privateKey('//Alice');36 });36 });37 });37 });tests/src/enableContractSponsoring.test.tsdiffbeforeafterboth818182 it('fails when called by non-owning user', async () => {82 it('fails when called by non-owning user', async () => {83 await usingApi(async (api) => {83 await usingApi(async (api) => {84 const [flipper, _] = await deployFlipper(api);84 const [flipper] = await deployFlipper(api);858586 await enableContractSponsoringExpectFailure(alice, flipper.address, true);86 await enableContractSponsoringExpectFailure(alice, flipper.address, true);87 });87 });tests/src/eth/fungible.test.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//51import privateKey from "../substrate/privateKey";6import privateKey from '../substrate/privateKey';2import { approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess } from "../util/helpers";7import { approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess } from '../util/helpers';3import { collectionIdToAddress, createEthAccount, itWeb3, normalizeEvents, recordEvents, subToEth, transferBalanceToEth } from "./util/helpers"8import { collectionIdToAddress, createEthAccount, itWeb3, normalizeEvents, recordEvents, subToEth, transferBalanceToEth } from './util/helpers';4import fungibleAbi from './fungibleAbi.json';9import fungibleAbi from './fungibleAbi.json';5import { expect } from "chai";10import { expect } from 'chai';6117describe('Information getting', () => {12describe('Information getting', () => {8 itWeb3('totalSupply', async ({ web3 }) => {13 itWeb3('totalSupply', async ({ web3 }) => {170 value: '50',175 value: '50',171 }176 },172 },177 },173 ])178 ]);174 }179 }175180176 {181 {tests/src/eth/metadata.test.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//51import { expect } from "chai";6import { expect } from 'chai';2import privateKey from "../substrate/privateKey";7import privateKey from '../substrate/privateKey';3import { createCollectionExpectSuccess } from "../util/helpers";8import { createCollectionExpectSuccess } from '../util/helpers';4import { collectionIdToAddress, createEthAccount, itWeb3, transferBalanceToEth } from "./util/helpers";9import { collectionIdToAddress, createEthAccount, itWeb3, transferBalanceToEth } from './util/helpers';5import fungibleMetadataAbi from './fungibleMetadataAbi.json';10import fungibleMetadataAbi from './fungibleMetadataAbi.json';6117describe('Common metadata', () => {12describe('Common metadata', () => {49 const decimals = await contract.methods.decimals().call({ from: caller });54 const decimals = await contract.methods.decimals().call({ from: caller });505551 expect(+decimals).to.equal(6);56 expect(+decimals).to.equal(6);52 })57 });53})58});tests/src/eth/nonFungible.test.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//51import privateKey from "../substrate/privateKey";6import privateKey from '../substrate/privateKey';2import { approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess } from "../util/helpers";7import { approveExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess } from '../util/helpers';3import { collectionIdToAddress, createEthAccount, itWeb3, normalizeEvents, recordEvents, subToEth, transferBalanceToEth } from "./util/helpers"8import { collectionIdToAddress, createEthAccount, itWeb3, normalizeEvents, recordEvents, subToEth, transferBalanceToEth } from './util/helpers';4import nonFungibleAbi from './nonFungibleAbi.json';9import nonFungibleAbi from './nonFungibleAbi.json';5import { expect } from "chai";10import { expect } from 'chai';6117describe('Information getting', () => {12describe('Information getting', () => {8 itWeb3('totalSupply', async ({ web3 }) => {13 itWeb3('totalSupply', async ({ web3 }) => {170 tokenId: tokenId.toString(),175 tokenId: tokenId.toString(),171 }176 },172 },177 },173 ])178 ]);174 }179 }175180176 {181 {tests/src/eth/util/helpers.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//51import { ApiPromise } from "@polkadot/api";6import { ApiPromise } from '@polkadot/api';2import { addressToEvm, evmToAddress } from "@polkadot/util-crypto";7import { addressToEvm, evmToAddress } from '@polkadot/util-crypto';3import Web3 from "web3";8import Web3 from 'web3';4import usingApi, { submitTransactionAsync } from "../../substrate/substrate-api";9import usingApi, { submitTransactionAsync } from '../../substrate/substrate-api';5import { IKeyringPair } from '@polkadot/types/types';10import { IKeyringPair } from '@polkadot/types/types';6import { expect } from "chai";11import { expect } from 'chai';7import { getGenericResult } from "../../util/helpers";12import { getGenericResult } from '../../util/helpers';8139let web3Connected = false;14let web3Connected = false;10export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {15export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {11 if (web3Connected) throw new Error('do not nest usingWeb3 calls');16 if (web3Connected) throw new Error('do not nest usingWeb3 calls');12 web3Connected = true;17 web3Connected = true;131814 const provider = new Web3.providers.WebsocketProvider("http://localhost:9944");19 const provider = new Web3.providers.WebsocketProvider('http://localhost:9944');15 const web3 = new Web3(provider);20 const web3 = new Web3(provider);162117 try {22 try {63itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { skip: true });68itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, { skip: true });646965export async function generateSubstrateEthPair(web3: Web3) {70export async function generateSubstrateEthPair(web3: Web3) {66 let account = web3.eth.accounts.create();71 const account = web3.eth.accounts.create();67 const evm = evmToAddress(account.address);72 evmToAddress(account.address);68}73}697470type NormalizedEvent = {75type NormalizedEvent = {758076export function normalizeEvents(events: any): NormalizedEvent[] {81export function normalizeEvents(events: any): NormalizedEvent[] {77 const output = [];82 const output = [];78 for (let key of Object.keys(events)) {83 for (const key of Object.keys(events)) {79 if (key.match(/^[0-9]+$/)) {84 if (key.match(/^[0-9]+$/)) {80 output.push(events[key]);85 output.push(events[key]);81 } else if (Array.isArray(events[key])) {86 } else if (Array.isArray(events[key])) {87 output.sort((a, b) => a.logIndex - b.logIndex);92 output.sort((a, b) => a.logIndex - b.logIndex);88 return output.map(({ address, event, returnValues }) => {93 return output.map(({ address, event, returnValues }) => {89 const args: { [key: string]: string } = {};94 const args: { [key: string]: string } = {};90 for (let key of Object.keys(returnValues)) {95 for (const key of Object.keys(returnValues)) {91 if (!key.match(/^[0-9]+$/)) {96 if (!key.match(/^[0-9]+$/)) {92 args[key] = returnValues[key];97 args[key] = returnValues[key];93 }98 }tests/src/inflation.test.tsdiffbeforeafterboth556import chai from 'chai';6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import { default as usingApi } from "./substrate/substrate-api";8import { default as usingApi } from './substrate/substrate-api';9import privateKey from "./substrate/privateKey";10import { BigNumber } from 'bignumber.js';9import { BigNumber } from 'bignumber.js';11import { IKeyringPair } from '@polkadot/types/types';121013chai.use(chaiAsPromised);11chai.use(chaiAsPromised);14const expect = chai.expect;12const expect = chai.expect;1516let alice: IKeyringPair;17let bob: IKeyringPair;181319describe('integration test: Inflation', () => {14describe('integration test: Inflation', () => {20 before(async () => {21 await usingApi(async (api) => {22 alice = privateKey('//Alice');23 bob = privateKey('//Bob');24 });25 });2627 it('First year inflation is 10%', async () => {15 it('First year inflation is 10%', async () => {28 await usingApi(async (api) => {16 await usingApi(async (api) => {tests/src/overflow.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { IKeyringPair } from "@polkadot/types/types";6import { IKeyringPair } from '@polkadot/types/types';7import chai from 'chai';7import chai from 'chai';8import chaiAsPromised from "chai-as-promised";8import chaiAsPromised from 'chai-as-promised';9import privateKey from "./substrate/privateKey";9import privateKey from './substrate/privateKey';10import usingApi from "./substrate/substrate-api";10import usingApi from './substrate/substrate-api';11import { approveExpectFail, approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, getAllowance, getFungibleBalance, transferExpectFail, transferExpectSuccess, transferFromExpectFail, transferFromExpectSuccess, U128_MAX } from "./util/helpers";11import { approveExpectFail, approveExpectSuccess, createCollectionExpectSuccess, createFungibleItemExpectSuccess, getAllowance, getFungibleBalance, transferExpectFail, transferExpectSuccess, transferFromExpectFail, transferFromExpectSuccess, U128_MAX } from './util/helpers';121213chai.use(chaiAsPromised);13chai.use(chaiAsPromised);14const expect = chai.expect;14const expect = chai.expect;tests/src/pallet-presence.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { ApiPromise } from "@polkadot/api";6import { ApiPromise } from '@polkadot/api';7import { expect } from "chai";7import { expect } from 'chai';8import usingApi from "./substrate/substrate-api";8import usingApi from './substrate/substrate-api';9910function getModuleNames(api: ApiPromise): string[] {10function getModuleNames(api: ApiPromise): string[] {11 return api.runtimeMetadata.asLatest.modules.map(m => m.name.toString().toLowerCase());11 return api.runtimeMetadata.asLatest.modules.map(m => m.name.toString().toLowerCase());tests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth556import chai from 'chai';6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";8import { default as usingApi, submitTransactionExpectFailAsync } from './substrate/substrate-api';9import { 9import { 10 createCollectionExpectSuccess, 10 createCollectionExpectSuccess, 11 setCollectionSponsorExpectSuccess, 11 setCollectionSponsorExpectSuccess, 12 destroyCollectionExpectSuccess, 12 destroyCollectionExpectSuccess, 13 setCollectionSponsorExpectFailure,14 confirmSponsorshipExpectSuccess,13 confirmSponsorshipExpectSuccess,15 confirmSponsorshipExpectFailure,14 confirmSponsorshipExpectFailure,16 createItemExpectSuccess,15 createItemExpectSuccess,17 findUnusedAddress,16 findUnusedAddress,18 getGenericResult,19 enableWhiteListExpectSuccess,20 enablePublicMintingExpectSuccess,21 addToWhiteListExpectSuccess,22 removeCollectionSponsorExpectSuccess,17 removeCollectionSponsorExpectSuccess,23 removeCollectionSponsorExpectFailure,18 removeCollectionSponsorExpectFailure,24 normalizeAccountId,19 normalizeAccountId,25} from "./util/helpers";20} from './util/helpers';26import { Keyring } from "@polkadot/api";21import { Keyring } from '@polkadot/api';27import { IKeyringPair } from "@polkadot/types/types";22import { IKeyringPair } from '@polkadot/types/types';28import type { AccountId } from '@polkadot/types/interfaces';29import { BigNumber } from 'bignumber.js';23import { BigNumber } from 'bignumber.js';302431chai.use(chaiAsPromised);25chai.use(chaiAsPromised);32const expect = chai.expect;26const expect = chai.expect;332734let alice: IKeyringPair;28let alice: IKeyringPair;35let bob: IKeyringPair;29let bob: IKeyringPair;36let charlie: IKeyringPair;373038describe('integration test: ext. removeCollectionSponsor():', () => {31describe('integration test: ext. removeCollectionSponsor():', () => {393240 before(async () => {33 before(async () => {41 await usingApi(async (api) => {34 await usingApi(async () => {42 const keyring = new Keyring({ type: 'sr25519' });35 const keyring = new Keyring({ type: 'sr25519' });43 alice = keyring.addFromUri(`//Alice`);36 alice = keyring.addFromUri('//Alice');44 bob = keyring.addFromUri(`//Bob`);37 bob = keyring.addFromUri('//Bob');45 charlie = keyring.addFromUri(`//Charlie`);46 });38 });47 });39 });484065 const badTransaction = async function () { 57 const badTransaction = async function () { 66 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);58 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);67 };59 };68 await expect(badTransaction()).to.be.rejectedWith("Inability to pay some fees");60 await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');69 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());61 const BsponsorBalance = new BigNumber((await api.query.system.account(bob.address)).data.free.toString());706271 expect(BsponsorBalance.isEqualTo(AsponsorBalance)).to.be.true;63 expect(BsponsorBalance.isEqualTo(AsponsorBalance)).to.be.true;958796describe('(!negative test!) integration test: ext. removeCollectionSponsor():', () => {88describe('(!negative test!) integration test: ext. removeCollectionSponsor():', () => {97 before(async () => {89 before(async () => {98 await usingApi(async (api) => {90 await usingApi(async () => {99 const keyring = new Keyring({ type: 'sr25519' });91 const keyring = new Keyring({ type: 'sr25519' });100 alice = keyring.addFromUri(`//Alice`);92 alice = keyring.addFromUri('//Alice');101 bob = keyring.addFromUri(`//Bob`);93 bob = keyring.addFromUri('//Bob');102 charlie = keyring.addFromUri(`//Charlie`);103 });94 });104 });95 });10596106 it('(!negative test!) Remove sponsor for a collection that never existed', async () => {97 it('(!negative test!) Remove sponsor for a collection that never existed', async () => {107 // Find the collection that never existed98 // Find the collection that never existed108 const collectionId = 0;99 let collectionId = 0;109 await usingApi(async (api) => {100 await usingApi(async (api) => {110 const collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;101 collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;111 });102 });112103113 await removeCollectionSponsorExpectFailure(collectionId);104 await removeCollectionSponsorExpectFailure(collectionId);tests/src/removeFromContractWhiteList.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import privateKey from "./substrate/privateKey";6import privateKey from './substrate/privateKey';7import usingApi from "./substrate/substrate-api";7import usingApi from './substrate/substrate-api';8import { deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess } from "./util/contracthelpers";8import { deployFlipper, toggleFlipValueExpectFailure, toggleFlipValueExpectSuccess } from './util/contracthelpers';9import { addToContractWhiteListExpectSuccess, isWhitelistedInContract, removeFromContractWhiteListExpectFailure, removeFromContractWhiteListExpectSuccess, toggleContractWhitelistExpectSuccess } from "./util/helpers";9import { addToContractWhiteListExpectSuccess, isWhitelistedInContract, removeFromContractWhiteListExpectFailure, removeFromContractWhiteListExpectSuccess, toggleContractWhitelistExpectSuccess } from './util/helpers';10import { IKeyringPair } from '@polkadot/types/types';10import { IKeyringPair } from '@polkadot/types/types';11import { expect } from "chai";11import { expect } from 'chai';121213describe('Integration Test removeFromContractWhiteList', () => {13describe('Integration Test removeFromContractWhiteList', () => {14 let bob: IKeyringPair;14 let bob: IKeyringPair;737374 it('fails when executed by non owner', async () => {74 it('fails when executed by non owner', async () => {75 await usingApi(async (api) => {75 await usingApi(async (api) => {76 const [flipper, _] = await deployFlipper(api);76 const [flipper] = await deployFlipper(api);777778 await removeFromContractWhiteListExpectFailure(alice, flipper.address.toString(), bob.address);78 await removeFromContractWhiteListExpectFailure(alice, flipper.address.toString(), bob.address);79 });79 });tests/src/removeFromWhiteList.test.tsdiffbeforeafterboth16 findNotExistingCollection,16 findNotExistingCollection,17 removeFromWhiteListExpectFailure,17 removeFromWhiteListExpectFailure,18 disableWhiteListExpectSuccess,18 disableWhiteListExpectSuccess,19 normalizeAccountId19 normalizeAccountId,20} from './util/helpers';20} from './util/helpers';21import { IKeyringPair } from '@polkadot/types/types';21import { IKeyringPair } from '@polkadot/types/types';22import privateKey from './substrate/privateKey';22import privateKey from './substrate/privateKey';29 let bob: IKeyringPair;29 let bob: IKeyringPair;303031 before(async () => {31 before(async () => {32 await usingApi(async (api) => {32 await usingApi(async () => {33 alice = privateKey('//Alice');33 alice = privateKey('//Alice');34 bob = privateKey('//Bob');34 bob = privateKey('//Bob');35 });35 });63 let bob: IKeyringPair;63 let bob: IKeyringPair;646465 before(async () => {65 before(async () => {66 await usingApi(async (api) => {66 await usingApi(async () => {67 alice = privateKey('//Alice');67 alice = privateKey('//Alice');68 bob = privateKey('//Bob');68 bob = privateKey('//Bob');69 });69 });tests/src/rpc.load.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { expect, assert } from "chai";7import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";6import usingApi, { submitTransactionAsync } from './substrate/substrate-api';8import { IKeyringPair } from "@polkadot/types/types";7import { IKeyringPair } from '@polkadot/types/types';9import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from "@polkadot/api-contract";8import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from '@polkadot/api-contract';10import { ApiPromise, Keyring } from "@polkadot/api";9import { ApiPromise, Keyring } from '@polkadot/api';11import { ApiTypes, SubmittableExtrinsic } from "@polkadot/api/types";12import { BigNumber } from 'bignumber.js';10import { BigNumber } from 'bignumber.js';13import { findUnusedAddress } from './util/helpers'11import { findUnusedAddress } from './util/helpers';14import fs from "fs";12import fs from 'fs';15import privateKey from "./substrate/privateKey";13import privateKey from './substrate/privateKey';161417const value = 0;15const value = 0;18const gasLimit = 500000n * 1000000n;16const gasLimit = 500000n * 1000000n;19const endowment = `1000000000000000`;17const endowment = '1000000000000000';20182119/*eslint no-async-promise-executor: "off"*/22function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<Blueprint> {20function deployBlueprint(alice: IKeyringPair, code: CodePromise): Promise<Blueprint> {23 return new Promise<Blueprint>(async (resolve, reject) => {21 return new Promise<Blueprint>(async (resolve) => {24 const unsub = await code22 const unsub = await code25 .createBlueprint()23 .createBlueprint()26 .signAndSend(alice, (result) => {24 .signAndSend(alice, (result) => {29 resolve(result.blueprint);27 resolve(result.blueprint);30 unsub();28 unsub();31 }29 }32 })30 });33 });31 });34}32}353334/*eslint no-async-promise-executor: "off"*/36function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {35function deployContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {37 return new Promise<any>(async (resolve, reject) => {36 return new Promise<any>(async (resolve) => {38 const unsub = await blueprint.tx37 const unsub = await blueprint.tx39 .new(endowment, gasLimit)38 .new(endowment, gasLimit)40 .signAndSend(alice, (result) => {39 .signAndSend(alice, (result) => {525153 // Transfer balance to it52 // Transfer balance to it54 const keyring = new Keyring({ type: 'sr25519' });53 const keyring = new Keyring({ type: 'sr25519' });55 const alice = keyring.addFromUri(`//Alice`);54 const alice = keyring.addFromUri('//Alice');56 let amount = new BigNumber(endowment);55 let amount = new BigNumber(endowment);57 amount = amount.plus(1e15);56 amount = amount.plus(1e15);58 const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());57 const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());81 const result = await contract.query.get(deployer.address, value, gasLimit);80 const result = await contract.query.get(deployer.address, value, gasLimit);828183 if(!result.result.isSuccess) {82 if(!result.result.isSuccess) {84 throw `Failed to get value`;83 throw 'Failed to get value';85 }84 }86 return result.result.asSuccess.data;85 return result.result.asSuccess.data;87}86}96 let rate = 0;95 let rate = 0;97 const checkPoint = 1000;96 const checkPoint = 1000;9798 /* eslint no-constant-condition: "off" */98 while (true) {99 while (true) {99 await api.rpc.system.chain();100 await api.rpc.system.chain();100 count++;101 count++;101 process.stdout.write(`RPC reads: ${count} times at rate ${rate} r/s \r`);102 process.stdout.write(`RPC reads: ${count} times at rate ${rate} r/s \r`);102 103 103 if (count % checkPoint == 0) {104 if (count % checkPoint == 0) {104 hrTime = process.hrtime();105 hrTime = process.hrtime();105 let microsec2 = hrTime[0] * 1000000 + hrTime[1] / 1000;106 const microsec2 = hrTime[0] * 1000000 + hrTime[1] / 1000;106 rate = 1000000*checkPoint/(microsec2 - microsec1);107 rate = 1000000*checkPoint/(microsec2 - microsec1);107 microsec1 = microsec2;108 microsec1 = microsec2;108 }109 }117 const [contract, deployer] = await deployLoadTester(api);118 const [contract, deployer] = await deployLoadTester(api);118119119 // Fill smart contract up with data120 // Fill smart contract up with data120 const bob = privateKey("//Bob");121 const bob = privateKey('//Bob');121 const tx = contract.tx.bloat(value, gasLimit, 200);122 const tx = contract.tx.bloat(value, gasLimit, 200);122 await submitTransactionAsync(bob, tx);123 await submitTransactionAsync(bob, tx);123124128 let rate = 0;129 let rate = 0;129 const checkPoint = 10;130 const checkPoint = 10;131132 /* eslint no-constant-condition: "off" */130 while (true) {133 while (true) {131 await getScData(contract, deployer);134 await getScData(contract, deployer);132 count++;135 count++;133 process.stdout.write(`SC reads: ${count} times at rate ${rate} r/s \r`);136 process.stdout.write(`SC reads: ${count} times at rate ${rate} r/s \r`);134 137 135 if (count % checkPoint == 0) {138 if (count % checkPoint == 0) {136 hrTime = process.hrtime();139 hrTime = process.hrtime();137 let microsec2 = hrTime[0] * 1000000 + hrTime[1] / 1000;140 const microsec2 = hrTime[0] * 1000000 + hrTime[1] / 1000;138 rate = 1000000*checkPoint/(microsec2 - microsec1);141 rate = 1000000*checkPoint/(microsec2 - microsec1);139 microsec1 = microsec2;142 microsec1 = microsec2;140 }143 }tests/src/scheduler.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { IKeyringPair } from '@polkadot/types/types';7import chai from 'chai';6import chai from 'chai';8import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';9import privateKey from './substrate/privateKey';8import privateKey from './substrate/privateKey';10import usingApi from './substrate/substrate-api';9import usingApi from './substrate/substrate-api';11import {10import {12 createItemExpectSuccess,11 createItemExpectSuccess,13 createCollectionExpectSuccess,12 createCollectionExpectSuccess,14 destroyCollectionExpectSuccess,15 findNotExistingCollection,16 queryCollectionExpectSuccess,17 setOffchainSchemaExpectFailure,18 setOffchainSchemaExpectSuccess,19 transferExpectSuccess,20 scheduleTransferExpectSuccess,13 scheduleTransferExpectSuccess,21 setCollectionSponsorExpectSuccess,14 setCollectionSponsorExpectSuccess,22 confirmSponsorshipExpectSuccess15 confirmSponsorshipExpectSuccess,23} from './util/helpers';16} from './util/helpers';24251726chai.use(chaiAsPromised);18chai.use(chaiAsPromised);27const expect = chai.expect;2829const DATA = [1, 2, 3, 4];301931describe('Integration Test scheduler base transaction', () => {20describe('Integration Test scheduler base transaction', () => {32 let alice: IKeyringPair;3334 before(async () => {35 await usingApi(async () => {36 alice = privateKey('//Alice');37 });38 });3940 it('User can transfer owned token with delay (scheduler)', async () => {21 it('User can transfer owned token with delay (scheduler)', async () => {41 await usingApi(async (api) => {22 await usingApi(async () => {42 const Alice = privateKey('//Alice');23 const Alice = privateKey('//Alice');43 const Bob = privateKey('//Bob');24 const Bob = privateKey('//Bob');44 // nft25 // nft54 55});34});5657// describe('Negative Integration Test setOffchainSchema', () => {58// let alice: IKeyringPair;59// let bob: IKeyringPair;6061// let validCollectionId: number;6263// before(async () => {64// await usingApi(async () => {65// alice = privateKey('//Alice');66// bob = privateKey('//Bob');6768// validCollectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });69// });70// });7172// it('fails on not existing collection id', async () => {73// const nonExistingCollectionId = await usingApi(findNotExistingCollection);7475// await setOffchainSchemaExpectFailure(alice, nonExistingCollectionId, DATA);76// });7778// it('fails on destroyed collection id', async () => {79// const destroyedCollectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });80// await destroyCollectionExpectSuccess(destroyedCollectionId);8182// await setOffchainSchemaExpectFailure(alice, destroyedCollectionId, DATA);83// });8485// it('fails on too long data', async () => {86// const tooLongData = new Array(4097).fill(0xff);8788// await setOffchainSchemaExpectFailure(alice, validCollectionId, tooLongData);89// });9091// it('fails on execution by non-owner', async () => {92// await setOffchainSchemaExpectFailure(bob, validCollectionId, DATA);93// });94// });9535tests/src/setCollectionLimits.test.tsdiffbeforeafterboth73 it('Set the same token limit twice', async () => {73 it('Set the same token limit twice', async () => {74 await usingApi(async (api: ApiPromise) => {74 await usingApi(async (api: ApiPromise) => {757576 let collectionLimits = {76 const collectionLimits = {77 AccountTokenOwnershipLimit: accountTokenOwnershipLimit,77 AccountTokenOwnershipLimit: accountTokenOwnershipLimit,78 SponsoredMintSize: sponsoredDataSize,78 SponsoredMintSize: sponsoredDataSize,79 TokenLimit: tokenLimit,79 TokenLimit: tokenLimit,206 });206 });207207208 it('Setting the higher token limit fails', async () => {208 it('Setting the higher token limit fails', async () => {209 await usingApi(async (api: ApiPromise) => {209 await usingApi(async () => {210210211 const collectionId = await createCollectionExpectSuccess();211 const collectionId = await createCollectionExpectSuccess();212 let collectionLimits = {212 const collectionLimits = {213 AccountTokenOwnershipLimit: accountTokenOwnershipLimit,213 AccountTokenOwnershipLimit: accountTokenOwnershipLimit,214 SponsoredMintSize: sponsoredDataSize,214 SponsoredMintSize: sponsoredDataSize,215 TokenLimit: tokenLimit,215 TokenLimit: tokenLimit,tests/src/setCollectionSponsor.test.tsdiffbeforeafterboth556import chai from 'chai';6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import { default as usingApi } from "./substrate/substrate-api";8import { default as usingApi } from './substrate/substrate-api';9import { createCollectionExpectSuccess, setCollectionSponsorExpectSuccess, destroyCollectionExpectSuccess, setCollectionSponsorExpectFailure } from "./util/helpers";9import { createCollectionExpectSuccess, setCollectionSponsorExpectSuccess, destroyCollectionExpectSuccess, setCollectionSponsorExpectFailure } from './util/helpers';10import { Keyring } from "@polkadot/api";10import { Keyring } from '@polkadot/api';11import { IKeyringPair } from "@polkadot/types/types";11import { IKeyringPair } from '@polkadot/types/types';121213chai.use(chaiAsPromised);13chai.use(chaiAsPromised);14const expect = chai.expect;151416let bob: IKeyringPair;15let bob: IKeyringPair;171618describe('integration test: ext. setCollectionSponsor():', () => {17describe('integration test: ext. setCollectionSponsor():', () => {191820 before(async () => {19 before(async () => {21 await usingApi(async (api) => {20 await usingApi(async () => {22 const keyring = new Keyring({ type: 'sr25519' });21 const keyring = new Keyring({ type: 'sr25519' });23 bob = keyring.addFromUri(`//Bob`);22 bob = keyring.addFromUri('//Bob');24 });23 });25 });24 });262546 const collectionId = await createCollectionExpectSuccess();45 const collectionId = await createCollectionExpectSuccess();474648 const keyring = new Keyring({ type: 'sr25519' });47 const keyring = new Keyring({ type: 'sr25519' });49 const charlie = keyring.addFromUri(`//Charlie`);48 const charlie = keyring.addFromUri('//Charlie');50 await setCollectionSponsorExpectSuccess(collectionId, bob.address);49 await setCollectionSponsorExpectSuccess(collectionId, bob.address);51 await setCollectionSponsorExpectSuccess(collectionId, charlie.address);50 await setCollectionSponsorExpectSuccess(collectionId, charlie.address);52 });51 });53});52});545355describe('(!negative test!) integration test: ext. setCollectionSponsor():', () => {54describe('(!negative test!) integration test: ext. setCollectionSponsor():', () => {56 before(async () => {55 before(async () => {57 await usingApi(async (api) => {56 await usingApi(async () => {58 const keyring = new Keyring({ type: 'sr25519' });57 const keyring = new Keyring({ type: 'sr25519' });59 bob = keyring.addFromUri(`//Bob`);58 bob = keyring.addFromUri('//Bob');60 });59 });61 });60 });626166 });65 });67 it('(!negative test!) Add sponsor to a collection that never existed', async () => {66 it('(!negative test!) Add sponsor to a collection that never existed', async () => {68 // Find the collection that never existed67 // Find the collection that never existed69 const collectionId = 0;68 let collectionId = 0;70 await usingApi(async (api) => {69 await usingApi(async (api) => {71 const collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;70 collectionId = parseInt((await api.query.nft.createdCollectionCount()).toString()) + 1;72 });71 });737274 await setCollectionSponsorExpectFailure(collectionId, bob.address);73 await setCollectionSponsorExpectFailure(collectionId, bob.address);tests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth23let largeShema: any;23let largeShema: any;242425before(async () => {25before(async () => {26 await usingApi(async (api) => {26 await usingApi(async () => {27 const keyring = new Keyring({ type: 'sr25519' });27 const keyring = new Keyring({ type: 'sr25519' });28 Alice = keyring.addFromUri('//Alice');28 Alice = keyring.addFromUri('//Alice');29 Bob = keyring.addFromUri('//Bob');29 Bob = keyring.addFromUri('//Bob');tests/src/setContractSponsoringRateLimit.test.tsdiffbeforeafterboth595960 it('fails when called by non-owning user', async () => {60 it('fails when called by non-owning user', async () => {61 await usingApi(async (api) => {61 await usingApi(async (api) => {62 const [flipper, _] = await deployFlipper(api);62 const [flipper] = await deployFlipper(api);636364 await setContractSponsoringRateLimitExpectFailure(alice, flipper.address, 1);64 await setContractSponsoringRateLimitExpectFailure(alice, flipper.address, 1);65 });65 });tests/src/setPublicAccessMode.test.tsdiffbeforeafterboth4//
4//5
56// https://unique-network.readthedocs.io/en/latest/jsapi.html#setschemaversion
6// https://unique-network.readthedocs.io/en/latest/jsapi.html#setschemaversion7import { ApiPromise, Keyring } from '@polkadot/api';
7import { ApiPromise } from '@polkadot/api';8import { IKeyringPair } from '@polkadot/types/types';
8import { IKeyringPair } from '@polkadot/types/types';9import chai from 'chai';
9import chai from 'chai';10import chaiAsPromised from 'chai-as-promised';
10import chaiAsPromised from 'chai-as-promised';19 enableWhiteListExpectSuccess,
19 enableWhiteListExpectSuccess,20 normalizeAccountId,
20 normalizeAccountId,21} from './util/helpers';
21} from './util/helpers';22import { utf16ToStr } from './util/util';
2223
24chai.use(chaiAsPromised);
23chai.use(chaiAsPromised);25const expect = chai.expect;
24const expect = chai.expect;29
2830describe('Integration Test setPublicAccessMode(): ', () => {
29describe('Integration Test setPublicAccessMode(): ', () => {31 before(async () => {
30 before(async () => {32 await usingApi(async (api) => {
31 await usingApi(async () => {33 Alice = privateKey('//Alice');
32 Alice = privateKey('//Alice');34 Bob = privateKey('//Bob');
33 Bob = privateKey('//Bob');35 });
34 });36 });
35 });37
3638 it('Run extrinsic with collection id parameters, set the whitelist mode for the collection', async () => {
37 it('Run extrinsic with collection id parameters, set the whitelist mode for the collection', async () => {39 await usingApi(async (api: ApiPromise) => {
38 await usingApi(async () => {40 const collectionId: number = await createCollectionExpectSuccess();
39 const collectionId: number = await createCollectionExpectSuccess();41 await enableWhiteListExpectSuccess(Alice, collectionId);
40 await enableWhiteListExpectSuccess(Alice, collectionId);42 await enablePublicMintingExpectSuccess(Alice, collectionId);
41 await enablePublicMintingExpectSuccess(Alice, collectionId);77 });
76 });78
7779 it('Re-set the list mode already set in quantity', async () => {
78 it('Re-set the list mode already set in quantity', async () => {80 await usingApi(async (api: ApiPromise) => {
79 await usingApi(async () => {81 const collectionId: number = await createCollectionExpectSuccess();
80 const collectionId: number = await createCollectionExpectSuccess();82 await enableWhiteListExpectSuccess(Alice, collectionId);
81 await enableWhiteListExpectSuccess(Alice, collectionId);83 await enableWhiteListExpectSuccess(Alice, collectionId);
82 await enableWhiteListExpectSuccess(Alice, collectionId);tests/src/setSchemaVersion.test.tsdiffbeforeafterboth103 it('execute setSchemaVersion with not correct schema version', async () => {103 it('execute setSchemaVersion with not correct schema version', async () => {104 await usingApi(async (api: ApiPromise) => {104 await usingApi(async (api: ApiPromise) => {105 const consoleError = console.error;105 const consoleError = console.error;106 console.error = (message: string) => {};106 console.error = () => {};107 try {107 try {108 tx = api.tx.nft.setSchemaVersion(collectionIdForTesting, 'Test');108 tx = api.tx.nft.setSchemaVersion(collectionIdForTesting, 'Test');109 await submitTransactionAsync(alice, tx);109 await submitTransactionAsync(alice, tx);tests/src/setVariableMetaData.test.tsdiffbeforeafterboth49});49});505051describe('Negative Integration Test setVariableMetaData', () => {51describe('Negative Integration Test setVariableMetaData', () => {52 let data = [1];52 const data = [1];535354 let alice: IKeyringPair;54 let alice: IKeyringPair;55 let bob: IKeyringPair;55 let bob: IKeyringPair;696970 it('fails on not existing collection id', async () => {70 it('fails on not existing collection id', async () => {71 await usingApi(async api => {71 await usingApi(async api => {72 let nonExistingCollectionId = await findNotExistingCollection(api);72 const nonExistingCollectionId = await findNotExistingCollection(api);73 await setVariableMetaDataExpectFailure(alice, nonExistingCollectionId, 1, data);73 await setVariableMetaDataExpectFailure(alice, nonExistingCollectionId, 1, data);74 });74 });75 });75 });tests/src/setVariableOnChainSchema.test.tsdiffbeforeafterboth23let largeSchema: any;23let largeSchema: any;242425before(async () => {25before(async () => {26 await usingApi(async (api) => {26 await usingApi(async () => {27 const keyring = new Keyring({ type: 'sr25519' });27 const keyring = new Keyring({ type: 'sr25519' });28 Alice = keyring.addFromUri('//Alice');28 Alice = keyring.addFromUri('//Alice');29 Bob = keyring.addFromUri('//Bob');29 Bob = keyring.addFromUri('//Bob');tests/src/substrate/privateKey.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { Keyring } from "@polkadot/api";6import { Keyring } from '@polkadot/api';7import { IKeyringPair } from "@polkadot/types/types";7import { IKeyringPair } from '@polkadot/types/types';889export default function privateKey(account: string): IKeyringPair {9export default function privateKey(account: string): IKeyringPair {10 const keyring = new Keyring({ type: 'sr25519' });10 const keyring = new Keyring({ type: 'sr25519' });tests/src/substrate/promisify-substrate.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { ApiPromise } from "@polkadot/api";6import { ApiPromise } from '@polkadot/api';778type PromiseType<T> = T extends PromiseLike<infer TInner> ? TInner : T;8type PromiseType<T> = T extends PromiseLike<infer TInner> ? TInner : T;99tests/src/substrate/substrate-api.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { WsProvider, ApiPromise } from "@polkadot/api";6import { WsProvider, ApiPromise } from '@polkadot/api';7import { EventRecord } from '@polkadot/types/interfaces/system/types';7import { EventRecord } from '@polkadot/types/interfaces/system/types';8import { ExtrinsicStatus } from '@polkadot/types/interfaces/author/types';8import { ExtrinsicStatus } from '@polkadot/types/interfaces/author/types';9import { IKeyringPair } from "@polkadot/types/types";9import { IKeyringPair } from '@polkadot/types/types';101011import config from "../config";11import config from '../config';12import promisifySubstrate from "./promisify-substrate";12import promisifySubstrate from './promisify-substrate';13import { ApiOptions, SubmittableExtrinsic, ApiTypes } from "@polkadot/api/types";13import { ApiOptions, SubmittableExtrinsic, ApiTypes } from '@polkadot/api/types';14import rtt from "../../../runtime_types.json";14import rtt from '../../../runtime_types.json';151516function defaultApiOptions(): ApiOptions {16function defaultApiOptions(): ApiOptions {17 const wsProvider = new WsProvider(config.substrateUrl);17 const wsProvider = new WsProvider(config.substrateUrl);18 return { provider: wsProvider, types: rtt };18 return {19 provider: wsProvider, types: rtt, signedExtensions: {20 ContractHelpers: {21 extrinsic: {},22 payload: {},23 },24 },25 };19}26}202721export default async function usingApi<T = void>(action: (api: ApiPromise) => Promise<T>, settings: ApiOptions | undefined = undefined): Promise<T> {28export default async function usingApi<T = void>(action: (api: ApiPromise) => Promise<T>, settings: ApiOptions | undefined = undefined): Promise<T> {22 settings = settings || defaultApiOptions();29 settings = settings || defaultApiOptions();23 let api: ApiPromise = new ApiPromise(settings);30 const api: ApiPromise = new ApiPromise(settings);24 let result: T = null as unknown as T;31 let result: T = null as unknown as T;253226 // TODO: Remove, this is temporary: Filter unneeded API output 33 // TODO: Remove, this is temporary: Filter unneeded API output 27 // (Jaco promised it will be removed in the next version)34 // (Jaco promised it will be removed in the next version)28 const consoleErr = console.error;35 const consoleErr = console.error;29 console.error = (message: string) => {36 console.error = (message: string) => {30 if (message.includes("StorageChangeSet:: WebSocket is not connected") || message.includes("2021-")) {}37 if (!message.includes('StorageChangeSet:: WebSocket is not connected') || message.includes('2021-'))31 else consoleErr(message);38 consoleErr(message);32 };39 };334034 try {41 try {727973export function80export function74submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {81submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {82 /* eslint no-async-promise-executor: "off" */75 return new Promise(async (resolve, reject) => {83 return new Promise(async (resolve, reject) => {76 try {84 try {77 await transaction.signAndSend(sender, ({ events = [], status }) => {85 await transaction.signAndSend(sender, ({ events = [], status }) => {97 console.error = () => {};105 console.error = () => {};98 console.log = () => {};106 console.log = () => {};99107108 /* eslint no-async-promise-executor: "off" */100 return new Promise<EventRecord[]>(async function(res, rej) {109 return new Promise<EventRecord[]>(async function(res, rej) {101 const resolve = (rec: EventRecord[]) => {110 const resolve = (rec: EventRecord[]) => {102 setTimeout(() => {111 setTimeout(() => {tests/src/substrate/wait-new-blocks.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import { ApiPromise } from "@polkadot/api";6import { ApiPromise } from '@polkadot/api';778/* eslint no-async-promise-executor: "off" */8export default function waitNewBlocks(api: ApiPromise, blocksCount: number = 1): Promise<void> {9export default function waitNewBlocks(api: ApiPromise, blocksCount = 1): Promise<void> {9 const promise = new Promise<void>(async (resolve, reject) => {10 const promise = new Promise<void>(async (resolve) => {10 11 11 const unsubscribe = await api.rpc.chain.subscribeNewHeads(head => {12 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {12 if(blocksCount > 0) {13 if (blocksCount > 0) {13 blocksCount--;14 blocksCount--;14 }else {15 } else {tests/src/toggleContractWhiteList.test.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import chai from "chai";6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from "./substrate/substrate-api";8import usingApi, { submitTransactionAsync, submitTransactionExpectFailAsync } from './substrate/substrate-api';9import privateKey from "./substrate/privateKey";9import privateKey from './substrate/privateKey';10import {10import {11 deployFlipper,11 deployFlipper,12 getFlipValue12 getFlipValue,13} from "./util/contracthelpers";13} from './util/contracthelpers';14import {14import {15 getGenericResult15 getGenericResult,16} from "./util/helpers"16} from './util/helpers';171718chai.use(chaiAsPromised);18chai.use(chaiAsPromised);19const expect = chai.expect;19const expect = chai.expect;232324describe('Integration Test toggleContractWhiteList', () => {24describe('Integration Test toggleContractWhiteList', () => {252526 it(`Enable white list contract mode`, async () => {26 it('Enable white list contract mode', async () => {27 await usingApi(async api => {27 await usingApi(async api => {28 const [contract, deployer] = await deployFlipper(api);28 const [contract, deployer] = await deployFlipper(api);292938 });38 });39 });39 });404041 it(`Only whitelisted account can call contract`, async () => {41 it('Only whitelisted account can call contract', async () => {42 await usingApi(async api => {42 await usingApi(async api => {43 const bob = privateKey("//Bob");43 const bob = privateKey('//Bob');444445 const [contract, deployer] = await deployFlipper(api);45 const [contract, deployer] = await deployFlipper(api);464647 let flipValueBefore = await getFlipValue(contract, deployer);47 let flipValueBefore = await getFlipValue(contract, deployer);48 const flip = contract.tx.flip(value, gasLimit);48 const flip = contract.tx.flip(value, gasLimit);49 await submitTransactionAsync(bob, flip);49 await submitTransactionAsync(bob, flip);50 const flipValueAfter = await getFlipValue(contract,deployer);50 const flipValueAfter = await getFlipValue(contract,deployer);51 expect(flipValueAfter).to.be.eq(!flipValueBefore, `Anyone can call new contract.`);51 expect(flipValueAfter).to.be.eq(!flipValueBefore, 'Anyone can call new contract.');525253 const deployerCanFlip = async () => {53 const deployerCanFlip = async () => {54 let flipValueBefore = await getFlipValue(contract, deployer);54 const flipValueBefore = await getFlipValue(contract, deployer);55 const deployerFlip = contract.tx.flip(value, gasLimit);55 const deployerFlip = contract.tx.flip(value, gasLimit);56 await submitTransactionAsync(deployer, deployerFlip);56 await submitTransactionAsync(deployer, deployerFlip);57 const aliceFlip1Response = await getFlipValue(contract, deployer);57 const aliceFlip1Response = await getFlipValue(contract, deployer);58 expect(aliceFlip1Response).to.be.eq(!flipValueBefore, `Deployer always can flip.`);58 expect(aliceFlip1Response).to.be.eq(!flipValueBefore, 'Deployer always can flip.');59 };59 };60 await deployerCanFlip();60 await deployerCanFlip();616162 flipValueBefore = await getFlipValue(contract, deployer);62 flipValueBefore = await getFlipValue(contract, deployer);63 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);63 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);64 const enableResult = await submitTransactionAsync(deployer, enableWhiteListTx);64 await submitTransactionAsync(deployer, enableWhiteListTx);65 const flipWithEnabledWhiteList = contract.tx.flip(value, gasLimit);65 const flipWithEnabledWhiteList = contract.tx.flip(value, gasLimit);66 await expect(submitTransactionExpectFailAsync(bob, flipWithEnabledWhiteList)).to.be.rejected;66 await expect(submitTransactionExpectFailAsync(bob, flipWithEnabledWhiteList)).to.be.rejected;67 const flipValueAfterEnableWhiteList = await getFlipValue(contract, deployer);67 const flipValueAfterEnableWhiteList = await getFlipValue(contract, deployer);68 expect(flipValueAfterEnableWhiteList).to.be.eq(flipValueBefore, `Enabling whitelist doesn't make it possible to call contract for everyone.`);68 expect(flipValueAfterEnableWhiteList).to.be.eq(flipValueBefore, 'Enabling whitelist doesn\'t make it possible to call contract for everyone.');696970 await deployerCanFlip();70 await deployerCanFlip();717172 flipValueBefore = await getFlipValue(contract, deployer);72 flipValueBefore = await getFlipValue(contract, deployer);73 const addBobToWhiteListTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);73 const addBobToWhiteListTx = api.tx.nft.addToContractWhiteList(contract.address, bob.address);74 const addBobResult = await submitTransactionAsync(deployer, addBobToWhiteListTx);74 await submitTransactionAsync(deployer, addBobToWhiteListTx);75 const flipWithWhitelistedBob = contract.tx.flip(value, gasLimit);75 const flipWithWhitelistedBob = contract.tx.flip(value, gasLimit);76 await submitTransactionAsync(bob, flipWithWhitelistedBob);76 await submitTransactionAsync(bob, flipWithWhitelistedBob);77 const flipAfterWhiteListed = await getFlipValue(contract,deployer);77 const flipAfterWhiteListed = await getFlipValue(contract,deployer);78 expect(flipAfterWhiteListed).to.be.eq(!flipValueBefore, `Bob was whitelisted, now he can flip.`);78 expect(flipAfterWhiteListed).to.be.eq(!flipValueBefore, 'Bob was whitelisted, now he can flip.');797980 await deployerCanFlip();80 await deployerCanFlip();818182 flipValueBefore = await getFlipValue(contract, deployer);82 flipValueBefore = await getFlipValue(contract, deployer);83 const removeBobFromWhiteListTx = api.tx.nft.removeFromContractWhiteList(contract.address, bob.address);83 const removeBobFromWhiteListTx = api.tx.nft.removeFromContractWhiteList(contract.address, bob.address);84 const removeBobResult = await submitTransactionAsync(deployer, removeBobFromWhiteListTx);84 await submitTransactionAsync(deployer, removeBobFromWhiteListTx);85 const bobRemoved = contract.tx.flip(value, gasLimit);85 const bobRemoved = contract.tx.flip(value, gasLimit);86 await expect(submitTransactionExpectFailAsync(bob, bobRemoved)).to.be.rejected;86 await expect(submitTransactionExpectFailAsync(bob, bobRemoved)).to.be.rejected;87 const afterBobRemoved = await getFlipValue(contract, deployer);87 const afterBobRemoved = await getFlipValue(contract, deployer);88 expect(afterBobRemoved).to.be.eq(flipValueBefore, `Bob can't call contract, now when he is removeed from white list.`);88 expect(afterBobRemoved).to.be.eq(flipValueBefore, 'Bob can\'t call contract, now when he is removeed from white list.');898990 await deployerCanFlip();90 await deployerCanFlip();919192 flipValueBefore = await getFlipValue(contract, deployer);92 flipValueBefore = await getFlipValue(contract, deployer);93 const disableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, false);93 const disableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, false);94 const disableWhiteListResult = await submitTransactionAsync(deployer, disableWhiteListTx);94 await submitTransactionAsync(deployer, disableWhiteListTx);95 const whiteListDisabledFlip = contract.tx.flip(value, gasLimit);95 const whiteListDisabledFlip = contract.tx.flip(value, gasLimit);96 await submitTransactionAsync(bob, whiteListDisabledFlip);96 await submitTransactionAsync(bob, whiteListDisabledFlip);97 const afterWhiteListDisabled = await getFlipValue(contract,deployer);97 const afterWhiteListDisabled = await getFlipValue(contract,deployer);98 expect(afterWhiteListDisabled).to.be.eq(!flipValueBefore, `Anyone can call contract with disabled whitelist.`);98 expect(afterWhiteListDisabled).to.be.eq(!flipValueBefore, 'Anyone can call contract with disabled whitelist.');9999100 });100 });101 });101 });102102103 it(`Enabling white list repeatedly should not produce errors`, async () => {103 it('Enabling white list repeatedly should not produce errors', async () => {104 await usingApi(async api => {104 await usingApi(async api => {105 const [contract, deployer] = await deployFlipper(api);105 const [contract, deployer] = await deployFlipper(api);106106123123124describe('Negative Integration Test toggleContractWhiteList', () => {124describe('Negative Integration Test toggleContractWhiteList', () => {125125126 it(`Enable white list for a non-contract`, async () => {126 it('Enable white list for a non-contract', async () => {127 await usingApi(async api => {127 await usingApi(async api => {128 const alice = privateKey("//Alice");128 const alice = privateKey('//Alice');129 const bobGuineaPig = privateKey("//Bob");129 const bobGuineaPig = privateKey('//Bob');130130131 const enabledBefore = (await api.query.nft.contractWhiteListEnabled(bobGuineaPig.address)).toJSON();131 const enabledBefore = (await api.query.nft.contractWhiteListEnabled(bobGuineaPig.address)).toJSON();132 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(bobGuineaPig.address, true);132 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(bobGuineaPig.address, true);138 });138 });139 });139 });140140141 it(`Enable white list using a non-owner address`, async () => {141 it('Enable white list using a non-owner address', async () => {142 await usingApi(async api => {142 await usingApi(async api => {143 const bob = privateKey("//Bob");143 const bob = privateKey('//Bob');144 const [contract, deployer] = await deployFlipper(api);144 const [contract] = await deployFlipper(api);145145146 const enabledBefore = (await api.query.nft.contractWhiteListEnabled(contract.address)).toJSON();146 const enabledBefore = (await api.query.nft.contractWhiteListEnabled(contract.address)).toJSON();147 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);147 const enableWhiteListTx = api.tx.nft.toggleContractWhiteList(contract.address, true);tests/src/transfer.nload.tsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//51import { ApiPromise } from "@polkadot/api";6import { ApiPromise } from '@polkadot/api';2import { IKeyringPair } from '@polkadot/types/types';7import { IKeyringPair } from '@polkadot/types/types';3import privateKey from "./substrate/privateKey";8import privateKey from './substrate/privateKey';4import usingApi, { submitTransactionAsync } from "./substrate/substrate-api";9import usingApi, { submitTransactionAsync } from './substrate/substrate-api';5import waitNewBlocks from "./substrate/wait-new-blocks";10import waitNewBlocks from './substrate/wait-new-blocks';6import { findUnusedAddresses } from "./util/helpers";11import { findUnusedAddresses } from './util/helpers';7import * as cluster from 'cluster';12import * as cluster from 'cluster';8import os from 'os';13import os from 'os';91426}31}273228async function distributeBalance(source: IKeyringPair, api: ApiPromise, totalAmount: bigint, stages: number) {33async function distributeBalance(source: IKeyringPair, api: ApiPromise, totalAmount: bigint, stages: number) {29 let accounts = [source];34 const accounts = [source];30 // we don't need source in output array35 // we don't need source in output array31 const failedAccounts = [0];36 const failedAccounts = [0];323736 increaseCounter('requests', finalUserAmount);41 increaseCounter('requests', finalUserAmount);374238 for (let stage = 0; stage < stages; stage++) {43 for (let stage = 0; stage < stages; stage++) {39 let usersWithBalance = 2 ** stage;44 const usersWithBalance = 2 ** stage;40 let amount = totalAmount / (2n ** BigInt(stage)) - FEE * BigInt(stage);45 const amount = totalAmount / (2n ** BigInt(stage)) - FEE * BigInt(stage);41 // console.log(`Stage ${stage}/${stages}, ${usersWithBalance} => ${usersWithBalance * 2} = ${amount}`);46 // console.log(`Stage ${stage}/${stages}, ${usersWithBalance} => ${usersWithBalance * 2} = ${amount}`);42 let txs = [];47 const txs = [];43 for (let i = 0; i < usersWithBalance; i++) {48 for (let i = 0; i < usersWithBalance; i++) {44 let newUser = accounts[i + usersWithBalance];49 const newUser = accounts[i + usersWithBalance];45 // console.log(`${accounts[i].address} => ${newUser.address} = ${amountToSplit}`);50 // console.log(`${accounts[i].address} => ${newUser.address} = ${amountToSplit}`);46 const tx = api.tx.balances.transfer(newUser.address, amount);51 const tx = api.tx.balances.transfer(newUser.address, amount);47 txs.push(submitTransactionAsync(accounts[i], tx).catch(e => {52 txs.push(submitTransactionAsync(accounts[i], tx).catch(() => {48 failedAccounts.push(i + usersWithBalance);53 failedAccounts.push(i + usersWithBalance);49 increaseCounter('txFailed', 1);54 increaseCounter('txFailed', 1);50 }));55 }));53 await Promise.all(txs);58 await Promise.all(txs);54 }59 }556056 for (let account of failedAccounts.reverse()) {61 for (const account of failedAccounts.reverse()) {57 accounts.splice(account, 1);62 accounts.splice(account, 1);58 }63 }59 return accounts;64 return accounts;62if (cluster.isMaster) {67if (cluster.isMaster) {63 let testDone = false;68 let testDone = false;64 usingApi(async (api) => {69 usingApi(async (api) => {65 let prevCounters: { [key: string]: number } = {};70 const prevCounters: { [key: string]: number } = {};66 while (!testDone) {71 while (!testDone) {67 for (let name in counters) {72 for (const name in counters) {68 if (!(name in prevCounters)) {73 if (!(name in prevCounters)) {69 prevCounters[name] = 0;74 prevCounters[name] = 0;70 }75 }77 await waitNewBlocks(api, 1);82 await waitNewBlocks(api, 1);78 }83 }79 });84 });80 let waiting: Promise<void>[] = [];85 const waiting: Promise<void>[] = [];81 console.log(`Starting ${os.cpus().length} workers`);86 console.log(`Starting ${os.cpus().length} workers`);82 usingApi(async (api) => {87 usingApi(async (api) => {83 const alice = privateKey('//Alice');88 const alice = privateKey('//Alice');84 for (let id in os.cpus()) {89 for (const id in os.cpus()) {85 const WORKER_NAME = `//LoadWorker${id}_${Date.now()}`;90 const WORKER_NAME = `//LoadWorker${id}_${Date.now()}`;86 const workerAccount = privateKey(WORKER_NAME);91 const workerAccount = privateKey(WORKER_NAME);87 const tx = api.tx.balances.transfer(workerAccount.address, 400n * 10n ** 23n);92 const tx = api.tx.balances.transfer(workerAccount.address, 400n * 10n ** 23n);88 await submitTransactionAsync(alice, tx);93 await submitTransactionAsync(alice, tx);899490 let worker = cluster.fork({95 const worker = cluster.fork({91 WORKER_NAME,96 WORKER_NAME,92 STAGES: id + 297 STAGES: id + 2,93 });98 });94 worker.on('message', msg => {99 worker.on('message', msg => {95 for (let key in msg) {100 for (const key in msg) {96 increaseCounter(key, msg[key]);101 increaseCounter(key, msg[key]);97 }102 }98 });103 });99 waiting.push(new Promise(res => worker.on('exit', res)));104 waiting.push(new Promise(res => worker.on('exit', res)));100 }105 }101 await Promise.all(waiting);106 await Promise.all(waiting);102 testDone = true;107 testDone = true;103 })108 });104} else {109} else {105 increaseCounter('startedWorkers', 1);110 increaseCounter('startedWorkers', 1);106 usingApi(async (api) => {111 usingApi(async (api) => {tests/src/transfer.test.tsdiffbeforeafterboth64 });64 });656566 it('User can transfer owned token', async () => {66 it('User can transfer owned token', async () => {67 await usingApi(async (api) => {67 await usingApi(async () => {68 const Alice = privateKey('//Alice');68 const Alice = privateKey('//Alice');69 const Bob = privateKey('//Bob');69 const Bob = privateKey('//Bob');70 // nft70 // nft879388describe('Negative Integration Test Transfer(recipient, collection_id, item_id, value)', () => {94describe('Negative Integration Test Transfer(recipient, collection_id, item_id, value)', () => {89 before(async () => {95 before(async () => {90 await usingApi(async (api: ApiPromise) => {96 await usingApi(async () => {91 Alice = privateKey('//Alice');97 Alice = privateKey('//Alice');92 Bob = privateKey('//Bob');98 Bob = privateKey('//Bob');93 Charlie = privateKey('//Charlie');99 Charlie = privateKey('//Charlie');tests/src/transferFrom.test.tsdiffbeforeafterboth14 createCollectionExpectSuccess,14 createCollectionExpectSuccess,15 createFungibleItemExpectSuccess,15 createFungibleItemExpectSuccess,16 createItemExpectSuccess,16 createItemExpectSuccess,17 destroyCollectionExpectSuccess,18 getAllowance,17 getAllowance,19 transferFromExpectFail,18 transferFromExpectFail,20 transferFromExpectSuccess,19 transferFromExpectSuccess,31 let Charlie: IKeyringPair;30 let Charlie: IKeyringPair;323133 before(async () => {32 before(async () => {34 await usingApi(async (api) => {33 await usingApi(async () => {35 Alice = privateKey('//Alice');34 Alice = privateKey('//Alice');36 Bob = privateKey('//Bob');35 Bob = privateKey('//Bob');37 Charlie = privateKey('//Charlie');36 Charlie = privateKey('//Charlie');38 });37 });39 });38 });403941 it('Execute the extrinsic and check nftItemList - owner of token', async () => {40 it('Execute the extrinsic and check nftItemList - owner of token', async () => {42 await usingApi(async (api: ApiPromise) => {41 await usingApi(async () => {43 // nft42 // nft44 const nftCollectionId = await createCollectionExpectSuccess();43 const nftCollectionId = await createCollectionExpectSuccess();45 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');44 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');92 let Charlie: IKeyringPair;99 let Charlie: IKeyringPair;9310094 before(async () => {101 before(async () => {95 await usingApi(async (api) => {102 await usingApi(async () => {96 Alice = privateKey('//Alice');103 Alice = privateKey('//Alice');97 Bob = privateKey('//Bob');104 Bob = privateKey('//Bob');98 Charlie = privateKey('//Charlie');105 Charlie = privateKey('//Charlie');139 }); */146 }); */140147141 it('transferFrom for not approved address', async () => {148 it('transferFrom for not approved address', async () => {142 await usingApi(async (api: ApiPromise) => {149 await usingApi(async () => {143 // nft150 // nft144 const nftCollectionId = await createCollectionExpectSuccess();151 const nftCollectionId = await createCollectionExpectSuccess();145 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');152 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');160 });173 });161174162 it('transferFrom incorrect token count', async () => {175 it('transferFrom incorrect token count', async () => {163 await usingApi(async (api: ApiPromise) => {176 await usingApi(async () => {164 // nft177 // nft165 const nftCollectionId = await createCollectionExpectSuccess();178 const nftCollectionId = await createCollectionExpectSuccess();166 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');179 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');184 });203 });185204186 it('execute transferFrom from account that is not owner of collection', async () => {205 it('execute transferFrom from account that is not owner of collection', async () => {187 await usingApi(async (api: ApiPromise) => {206 await usingApi(async () => {188 const Dave = privateKey('//Dave');207 const Dave = privateKey('//Dave');189 // nft208 // nft190 const nftCollectionId = await createCollectionExpectSuccess();209 const nftCollectionId = await createCollectionExpectSuccess();223 });242 });224 });243 });225 it( 'transferFrom burnt token before approve NFT', async () => {244 it( 'transferFrom burnt token before approve NFT', async () => {226 await usingApi(async (api: ApiPromise) => {245 await usingApi(async () => {227 // nft246 // nft228 const nftCollectionId = await createCollectionExpectSuccess();247 const nftCollectionId = await createCollectionExpectSuccess();229 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');248 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');233 });252 });234 });253 });235 it( 'transferFrom burnt token before approve Fungible', async () => {254 it( 'transferFrom burnt token before approve Fungible', async () => {236 await usingApi(async (api: ApiPromise) => {255 await usingApi(async () => {237 const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});256 const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});238 const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');257 const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');239 await burnItemExpectSuccess(Alice, fungibleCollectionId, 1, 10);258 await burnItemExpectSuccess(Alice, fungibleCollectionId, 1, 10);243 });262 });244 }); 263 }); 245 it( 'transferFrom burnt token before approve ReFungible', async () => {264 it( 'transferFrom burnt token before approve ReFungible', async () => {246 await usingApi(async (api: ApiPromise) => {265 await usingApi(async () => {247 const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});266 const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});248 const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');267 const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');249 await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 1);268 await burnItemExpectSuccess(Alice, reFungibleCollectionId, newReFungibleTokenId, 1);254 });273 });255 274 256 it( 'transferFrom burnt token after approve NFT', async () => {275 it( 'transferFrom burnt token after approve NFT', async () => {257 await usingApi(async (api: ApiPromise) => {276 await usingApi(async () => {258 // nft277 // nft259 const nftCollectionId = await createCollectionExpectSuccess();278 const nftCollectionId = await createCollectionExpectSuccess();260 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');279 const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');264 });283 });265 });284 });266 it( 'transferFrom burnt token after approve Fungible', async () => {285 it( 'transferFrom burnt token after approve Fungible', async () => {267 await usingApi(async (api: ApiPromise) => {286 await usingApi(async () => {268 const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});287 const fungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});269 const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');288 const newFungibleTokenId = await createItemExpectSuccess(Alice, fungibleCollectionId, 'Fungible');270 await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, Alice, Bob);289 await approveExpectSuccess(fungibleCollectionId, newFungibleTokenId, Alice, Bob);274 });293 });275 }); 294 }); 276 it( 'transferFrom burnt token after approve ReFungible', async () => {295 it( 'transferFrom burnt token after approve ReFungible', async () => {277 await usingApi(async (api: ApiPromise) => {296 await usingApi(async () => {278 const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});297 const reFungibleCollectionId = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});279 const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');298 const newReFungibleTokenId = await createItemExpectSuccess(Alice, reFungibleCollectionId, 'ReFungible');280 await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);299 await approveExpectSuccess(reFungibleCollectionId, newReFungibleTokenId, Alice, Bob);tests/src/util/contracthelpers.tsdiffbeforeafterboth3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.4//4//556import chai from "chai";6import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';7import chaiAsPromised from 'chai-as-promised';8import { submitTransactionAsync, submitTransactionExpectFailAsync } from "../substrate/substrate-api";8import { submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';9import fs from "fs";9import fs from 'fs';10import { Abi, BlueprintPromise as Blueprint, CodePromise, ContractPromise as Contract } from "@polkadot/api-contract";10import { Abi, CodePromise, ContractPromise as Contract } from '@polkadot/api-contract';11import { IKeyringPair } from "@polkadot/types/types";11import { IKeyringPair } from '@polkadot/types/types';12import { ApiPromise, Keyring } from "@polkadot/api";12import { ApiPromise, Keyring } from '@polkadot/api';131314chai.use(chaiAsPromised);14chai.use(chaiAsPromised);15const expect = chai.expect;15const expect = chai.expect;20const gasLimit = '200000000000';20const gasLimit = '200000000000';21const endowment = '100000000000000000';21const endowment = '100000000000000000';222223/* eslint no-async-promise-executor: "off" */23function deployContract(alice: IKeyringPair, code: CodePromise, constructor: string = 'default', ...args: any[]): Promise<Contract> {24function deployContract(alice: IKeyringPair, code: CodePromise, constructor = 'default', ...args: any[]): Promise<Contract> {24 return new Promise<Contract>(async (resolve, reject) => {25 return new Promise<Contract>(async (resolve) => {25 const unsub = await (code as any)26 const unsub = await (code as any)26 .tx[constructor]({value: endowment, gasLimit}, ...args)27 .tx[constructor]({value: endowment, gasLimit}, ...args)27 .signAndSend(alice, (result: any) => {28 .signAndSend(alice, (result: any) => {30 resolve((result as any).contract);31 resolve((result as any).contract);31 unsub();32 unsub();32 }33 }33 })34 });34 });35 });35}36}3637404141 // Transfer balance to it42 // Transfer balance to it42 const keyring = new Keyring({ type: 'sr25519' });43 const keyring = new Keyring({ type: 'sr25519' });43 const alice = keyring.addFromUri(`//Alice`);44 const alice = keyring.addFromUri('//Alice');44 let amount = new BigNumber(endowment);45 let amount = new BigNumber(endowment);45 amount = amount.plus(100e15);46 amount = amount.plus(100e15);46 const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());47 const tx = api.tx.balances.transfer(deployer.address, amount.toFixed());71 const result = await contract.query.get(deployer.address, value, gasLimit);72 const result = await contract.query.get(deployer.address, value, gasLimit);727373 if(!result.result.isOk) {74 if(!result.result.isOk) {74 throw `Failed to get flipper value`;75 throw 'Failed to get flipper value';75 }76 }76 return (result.result.asOk.data[0] == 0x00) ? false : true;77 return (result.result.asOk.data[0] == 0x00) ? false : true;77}78}89 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;90 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;90}91}9192function instantiateTransferContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {93 return new Promise<any>(async (resolve, reject) => {94 const unsub = await blueprint.tx95 .default(endowment, gasLimit)96 .signAndSend(alice, (result) => {97 if (result.status.isInBlock || result.status.isFinalized) {98 unsub();99 resolve(result);100 }101 }); 102 });103}10492105export async function deployTransferContract(api: ApiPromise): Promise<[Contract, IKeyringPair]> {93export async function deployTransferContract(api: ApiPromise): Promise<[Contract, IKeyringPair]> {106 const metadata = JSON.parse(fs.readFileSync('./src/transfer_contract/metadata.json').toString('utf-8'));94 const metadata = JSON.parse(fs.readFileSync('./src/transfer_contract/metadata.json').toString('utf-8'));tests/src/util/helpers.tsdiffbeforeafterboth4//4//556import { ApiPromise, Keyring } from '@polkadot/api';6import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, BlockNumber, Call, EventRecord } from '@polkadot/types/interfaces';7import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';8import { IKeyringPair } from '@polkadot/types/types';11import { evmToAddress } from '@polkadot/util-crypto';9import { evmToAddress } from '@polkadot/util-crypto';12import { BigNumber } from 'bignumber.js';10import { BigNumber } from 'bignumber.js';13import BN from 'bn.js';11import BN from 'bn.js';14import chai from 'chai';12import chai from 'chai';15import chaiAsPromised from 'chai-as-promised';13import chaiAsPromised from 'chai-as-promised';16import { alicesPublicKey, nullPublicKey } from '../accounts';14import { alicesPublicKey } from '../accounts';17import privateKey from '../substrate/privateKey';15import privateKey from '../substrate/privateKey';18import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';16import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';19import { ICollectionInterface } from '../types';17import { ICollectionInterface } from '../types';20import { hexToStr, strToUTF16, utf16ToStr } from './util';18import { hexToStr, strToUTF16, utf16ToStr } from './util';21import { Compact, Option, Raw, Vec } from '@polkadot/types/codec';22// import { AccountId, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, Call, ChangesTrieConfiguration, Consensus, ConsensusEngineId, Digest, DigestItem, DispatchClass, DispatchInfo, DispatchInfoTo190, EcdsaSignature, Ed25519Signature, Extrinsic, ExtrinsicEra, ExtrinsicPayload, ExtrinsicPayloadUnknown, ExtrinsicPayloadV1, ExtrinsicPayloadV2, ExtrinsicPayloadV3, ExtrinsicPayloadV4, ExtrinsicSignatureV1, ExtrinsicSignatureV2, ExtrinsicSignatureV3, ExtrinsicSignatureV4, ExtrinsicUnknown, ExtrinsicV1, ExtrinsicV2, ExtrinsicV3, ExtrinsicV4, Hash, Header, ImmortalEra, Index, Justification, KeyTypeId, KeyValue, LockIdentifier, LookupSource, LookupTarget, Moment, MortalEra, MultiSignature, Origin, Perbill, Percent, Permill, Perquintill, Phantom, PhantomData, PreRuntime, Seal, SealV0, Signature, SignedBlock, SignerPayload, Sr25519Signature, ValidatorId, Weight, WeightMultiplier } from '@polkadot/types/interfaces/runtime';231924chai.use(chaiAsPromised);20chai.use(chaiAsPromised);25const expect = chai.expect;21const expect = chai.expect;44 }40 }454146 // AccountId42 // AccountId47 return {substrate: input.toString()}43 return {substrate: input.toString()};48}44}49export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {45export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {50 input = normalizeAccountId(input);46 input = normalizeAccountId(input);93 VariableData: number[];89 VariableData: number[];94}90}9596interface IFungibleTokenDataType {97 Value: BN;98}9991100interface IGetMessage {92interface IGetMessage {101 checkMsgNftMethod: string;93 checkMsgNftMethod: string;110}102}111103112export function nftEventMessage(events: EventRecord[]): IGetMessage {104export function nftEventMessage(events: EventRecord[]): IGetMessage {113 let checkMsgNftMethod: string = '';105 let checkMsgNftMethod = '';114 let checkMsgTrsMethod: string = '';106 let checkMsgTrsMethod = '';115 let checkMsgSysMethod: string = '';107 let checkMsgSysMethod = '';116 events.forEach(({ event: { method, section } }) => {108 events.forEach(({ event: { method, section } }) => {117 if (section === 'nft') {109 if (section === 'nft') {118 checkMsgNftMethod = method;110 checkMsgNftMethod = method;134 const result: GenericResult = {126 const result: GenericResult = {135 success: false,127 success: false,136 };128 };137 events.forEach(({ phase, event: { data, method, section } }) => {129 events.forEach(({ event: { method } }) => {138 // console.log(` ${phase}: ${section}.${method}:: ${data}`);130 // console.log(` ${phase}: ${section}.${method}:: ${data}`);139 if (method === 'ExtrinsicSuccess') {131 if (method === 'ExtrinsicSuccess') {140 result.success = true;132 result.success = true;147139148export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {140export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {149 let success = false;141 let success = false;150 let collectionId: number = 0;142 let collectionId = 0;151 events.forEach(({ phase, event: { data, method, section } }) => {143 events.forEach(({ event: { data, method, section } }) => {152 // console.log(` ${phase}: ${section}.${method}:: ${data}`);144 // console.log(` ${phase}: ${section}.${method}:: ${data}`);153 if (method == 'ExtrinsicSuccess') {145 if (method == 'ExtrinsicSuccess') {154 success = true;146 success = true;165157166export function getCreateItemResult(events: EventRecord[]): CreateItemResult {158export function getCreateItemResult(events: EventRecord[]): CreateItemResult {167 let success = false;159 let success = false;168 let collectionId: number = 0;160 let collectionId = 0;169 let itemId: number = 0;161 let itemId = 0;170 let recipient;162 let recipient;171 events.forEach(({ phase, event: { data, method, section } }) => {163 events.forEach(({ event: { data, method, section } }) => {172 // console.log(` ${phase}: ${section}.${method}:: ${data}`);164 // console.log(` ${phase}: ${section}.${method}:: ${data}`);173 if (method == 'ExtrinsicSuccess') {165 if (method == 'ExtrinsicSuccess') {174 success = true;166 success = true;241 mode: { type: 'NFT' },233 mode: { type: 'NFT' },242 name: 'name',234 name: 'name',243 tokenPrefix: 'prefix',235 tokenPrefix: 'prefix',244}236};245237246export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {238export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {247 const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };239 const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };248240249 let collectionId: number = 0;241 let collectionId = 0;250 await usingApi(async (api) => {242 await usingApi(async (api) => {251 // Get number of collections before the transaction243 // Get number of collections before the transaction252 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);244 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);357}349}358350359function getDestroyResult(events: EventRecord[]): boolean {351function getDestroyResult(events: EventRecord[]): boolean {360 let success: boolean = false;352 let success = false;361 events.forEach(({ phase, event: { data, method, section } }) => {353 events.forEach(({ event: { method } }) => {362 // console.log(` ${phase}: ${section}.${method}:: ${data}`);363 if (method == 'ExtrinsicSuccess') {354 if (method == 'ExtrinsicSuccess') {364 success = true;355 success = true;365 }356 }366 });357 });367 return success;358 return success;368}359}369360370export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {361export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {371 await usingApi(async (api) => {362 await usingApi(async (api) => {372 // Run the DestroyCollection transaction363 // Run the DestroyCollection transaction373 const alicePrivateKey = privateKey(senderSeed);364 const alicePrivateKey = privateKey(senderSeed);376 });367 });377}368}378369379export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {370export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {380 await usingApi(async (api) => {371 await usingApi(async (api) => {381 // Run the DestroyCollection transaction372 // Run the DestroyCollection transaction382 const alicePrivateKey = privateKey(senderSeed);373 const alicePrivateKey = privateKey(senderSeed);471 });462 });472}463}473464474export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {465export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {475 await usingApi(async (api) => {466 await usingApi(async (api) => {476467477 // Run the transaction468 // Run the transaction481 });472 });482}473}483474484export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {475export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {485 await usingApi(async (api) => {476 await usingApi(async (api) => {486477487 // Run the transaction478 // Run the transaction502}493}503494504495505export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {496export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {506 await usingApi(async (api) => {497 await usingApi(async (api) => {507498508 // Run the transaction499 // Run the transaction552 });543 });553}544}554545555export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {546export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string) {556 await usingApi(async (api) => {547 await usingApi(async (api) => {557 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);548 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);558 const events = await submitTransactionAsync(sender, tx);549 const events = await submitTransactionAsync(sender, tx);563}554}564555565export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {556export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {566 let whitelisted: boolean = false;557 let whitelisted = false;567 await usingApi(async (api) => {558 await usingApi(async (api) => {568 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;559 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;569 });560 });689 accountFrom: IKeyringPair | CrossAccountId,683 accountFrom: IKeyringPair | CrossAccountId,690 accountTo: IKeyringPair | CrossAccountId,684 accountTo: IKeyringPair | CrossAccountId,691 value: number | bigint = 1,685 value: number | bigint = 1,692 type: string = 'NFT') {686 type = 'NFT',687) {693 await usingApi(async (api: ApiPromise) => {688 await usingApi(async (api: ApiPromise) => {694 const to = normalizeAccountId(accountTo);689 const to = normalizeAccountId(accountTo);736 });731 });737}732}738733734/* eslint no-async-promise-executor: "off" */739async function getBlockNumber(api: ApiPromise): Promise<number> {735async function getBlockNumber(api: ApiPromise): Promise<number> {740 return new Promise<number>(async (resolve, reject) => {736 return new Promise<number>(async (resolve) => {741 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {737 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {742 unsubscribe();738 unsubscribe();743 resolve(head.number.toNumber());739 resolve(head.number.toNumber());751 sender: IKeyringPair,748 sender: IKeyringPair,752 recipient: IKeyringPair,749 recipient: IKeyringPair,753 value: number | bigint = 1,750 value: number | bigint = 1,754 type: string = 'NFT') {751) {755 await usingApi(async (api: ApiPromise) => {752 await usingApi(async (api: ApiPromise) => {756 let balanceBefore = new BN(0);757758759 let blockNumber: number | undefined = await getBlockNumber(api);753 const blockNumber: number | undefined = await getBlockNumber(api);760 let expectedBlockNumber = blockNumber + 2;754 const expectedBlockNumber = blockNumber + 2;761755762 expect(blockNumber).to.be.greaterThan(0);756 expect(blockNumber).to.be.greaterThan(0);763 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value); 757 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value); 764 const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);758 const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);765759766 const events = await submitTransactionAsync(sender, scheduleTx);760 await submitTransactionAsync(sender, scheduleTx);767761768 const sponsorBalanceBefore = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());769 const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());762 const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());770763771 const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;764 const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;774 // sleep for 2 blocks767 // sleep for 2 blocks775 await new Promise(resolve => setTimeout(resolve, 6000 * 2));768 await new Promise(resolve => setTimeout(resolve, 6000 * 2));776769777 const sponsorBalanceAfter = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());778 const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());770 const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());779771780 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;772 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;790 sender: IKeyringPair,783 sender: IKeyringPair,791 recipient: IKeyringPair | CrossAccountId,784 recipient: IKeyringPair | CrossAccountId,792 value: number | bigint = 1,785 value: number | bigint = 1,793 type: string = 'NFT') {786 type = 'NFT',787) {794 await usingApi(async (api: ApiPromise) => {788 await usingApi(async (api: ApiPromise) => {795 const to = normalizeAccountId(recipient);789 const to = normalizeAccountId(recipient);831 sender: IKeyringPair,826 sender: IKeyringPair,832 recipient: IKeyringPair,827 recipient: IKeyringPair,833 value: number | bigint = 1,828 value: number | bigint = 1,834 type: string = 'NFT') {829) {835 await usingApi(async (api: ApiPromise) => {830 await usingApi(async (api: ApiPromise) => {836 const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);831 const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);837 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;832 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;884881885export async function createItemExpectSuccess(882export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {886 sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {887 let newItemId: number = 0;883 let newItemId = 0;888 await usingApi(async (api) => {884 await usingApi(async (api) => {889 const to = normalizeAccountId(owner);885 const to = normalizeAccountId(owner);890 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);886 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);1000}995}10019961002export async function isWhitelisted(collectionId: number, address: string) {997export async function isWhitelisted(collectionId: number, address: string) {1003 let whitelisted: boolean = false;998 let whitelisted = false;1004 await usingApi(async (api) => {999 await usingApi(async (api) => {1005 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;1000 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;1006 });1001 });tests/src/util/util.tsdiffbeforeafterboth4//4//556export function strToUTF16(str: string): any {6export function strToUTF16(str: string): any {7 let buf: number[] = [];7 const buf: number[] = [];8 for (let i=0, strLen=str.length; i < strLen; i++) {8 for (let i=0, strLen=str.length; i < strLen; i++) {9 buf.push(str.charCodeAt(i));9 buf.push(str.charCodeAt(i));10 }10 }11 return buf;11 return buf;12}12}131314export function utf16ToStr(buf: number[]): string {14export function utf16ToStr(buf: number[]): string {15 let str: string = "";15 let str = '';16 for (let i=0, strLen=buf.length; i < strLen; i++) {16 for (let i=0, strLen=buf.length; i < strLen; i++) {17 if (buf[i] != 0) str += String.fromCharCode(buf[i]);17 if (buf[i] != 0) str += String.fromCharCode(buf[i]);18 else break;18 else break;21}21}222223export function hexToStr(buf: string): string {23export function hexToStr(buf: string): string {24 let str: string = "";24 let str = '';25 let hexStart = buf.indexOf("0x");25 let hexStart = buf.indexOf('0x');26 if (hexStart < 0) hexStart = 0;26 if (hexStart < 0) hexStart = 0;27 else hexStart = 2; 27 else hexStart = 2; 28 for (let i=hexStart, strLen=buf.length; i < strLen; i+=2) {28 for (let i=hexStart, strLen=buf.length; i < strLen; i+=2) {29 let ch = buf[i] + buf[i+1];29 const ch = buf[i] + buf[i+1];30 let num = parseInt(ch, 16);30 const num = parseInt(ch, 16);31 if (num != 0) str += String.fromCharCode(num);31 if (num != 0) str += String.fromCharCode(num);32 else break;32 else break;33 }33 }