git.delta.rocks / unique-network / refs/commits / 3fb62366cc89

difftreelog

Merge pull request #153 from usetech-llc/feature/NFTPAR-536_code_style

usetech-llc2021-07-08parents: #d08f396 #ad8b982.patch.diff
in: master
Enforce codestyle

117 files changed

modified.devcontainer/devcontainer.jsondiffbeforeafterboth
12 }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}
added.github/workflows/codestyle.ymldiffbeforeafterboth

no changes

added.github/workflows/tests_codestyle.ymldiffbeforeafterboth

no changes

added.rustfmt.tomldiffbeforeafterboth

no changes

added.vscode/extensions.jsondiffbeforeafterboth

no changes

added.vscode/settings.jsondiffbeforeafterboth

no changes

modifiedCargo.lockdiffbeforeafterboth
5993 "sp-std",5993 "sp-std",
5994]5994]
5995
5996[[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]
60105995
6011[[package]]5996[[package]]
6012name = "pallet-scheduler"5997name = "pallet-scheduler"
6026 "up-sponsorship",6011 "up-sponsorship",
6027]6012]
6013
6014[[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]
60286028
6029[[package]]6029[[package]]
6030name = "pallet-session"6030name = "pallet-session"
modifiedREADME.mddiffbeforeafterboth
228## Running Integration Tests228## Running Integration Tests
229229
230See [tests/README.md](./tests/README.md).230See [tests/README.md](./tests/README.md).
231231
232## Code Formatting
233
234### Get formatter and linter settings into your branch (if you forked before they were introduced)
235```bash
236git cherry-pick -n 8ff77c21b0d30b2a4648fa35dbf61dfa9d3948a7
237```
238
239### Apply formatting and clippy fixes
240```bash
241cargo clippy
242cargo fmt
243```
244
245### Format tests
246```bash
247pushd tests && yarn fix ; popd
248```
249
250### Check code style in tests
251```bash
252cd tests && yarn eslint --ext .ts,.js src/
253```
modifiedcrates/evm-coder-macros/src/lib.rsdiffbeforeafterboth
1#![allow(dead_code)]
2
1use darling::FromMeta;3use darling::FromMeta;
2use inflector::cases;4use inflector::cases;
modifiedcrates/evm-coder-macros/src/solidity_interface.rsdiffbeforeafterboth
1#![allow(dead_code)]
2
1use 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)?;
266268
267 let camel_name = info269 let camel_name = info
268 .rename_selector270 .rename_selector
283 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_inner
547 )*549 )*
550 #[allow(unreachable_code)] // In case of no inner calls
548 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;
modifiedcrates/evm-coder-macros/src/to_log.rsdiffbeforeafterboth
41impl 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);
4545
46 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() {
modifiedcrates/evm-coder/src/abi.rsdiffbeforeafterboth
104 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}
258258
modifiedcrates/evm-coder/tests/a.rsdiffbeforeafterboth
1#![allow(dead_code)] // This test only checks that macros is not panicking
2
1use evm_coder::{solidity_interface, types::*, ToLog};3use evm_coder::{solidity_interface, types::*, ToLog};
2use evm_coder_macros::solidity;4use evm_coder_macros::solidity;
modifiednode/cli/Cargo.tomldiffbeforeafterboth
33
4[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'
88
9################################################################################9################################################################################
1717
18[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'
2222
23[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'
2727
28[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'
3232
33[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'
3737
38[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'
4242
43[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'
4747
48[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'
5353
54[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'
5858
59[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'
6363
64[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'
6868
69[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'
7474
75[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'
7979
80[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'
8484
85[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'
8989
90[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'
9494
95[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'
100100
101[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'
105105
106[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'
110110
111[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'
115115
116[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'
120120
121[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'
125125
126[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'
130130
131[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'
135135
136[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'
140140
141[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'
145145
146[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'
150150
151[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'
155155
156[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'
160160
161[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'
165165
166[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'
170170
171[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'
175175
176[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'
180180
181[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'
185185
186[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'
190190
191[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'
195195
196[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'
200200
201[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'
205205
206206
207[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'
211211
212[dependencies.serde]212[dependencies.serde]
222222
223[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'
226226
227[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'
230230
231[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'
234234
235[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'
238238
239[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'
242242
243[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'
246246
247[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'
250250
251[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'
254254
255255
256################################################################################256################################################################################
257# Polkadot dependencies257# Polkadot dependencies
258[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'
261261
262[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'
265265
266[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'
269269
270[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'
273273
274[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'
277277
278278
279################################################################################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" }
326326
327nft-rpc = { path = "../rpc" }327nft-rpc = { path = "../rpc" }
328328
modifiednode/cli/build.rsdiffbeforeafterboth

no syntactic changes

modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
64 // ID64 // ID
65 "dev",65 "dev",
66 ChainType::Local,66 ChainType::Local,
67 move || testnet_genesis(67 move || {
68 testnet_genesis(
68 // Sudo account69 // Sudo account
69 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 // Bootnodes
82 vec![],84 vec![],
83 // Telemetry85 // Telemetry
101 // ID103 // ID
102 "local_testnet",104 "local_testnet",
103 ChainType::Local,105 ChainType::Local,
104 move || testnet_genesis(106 move || {
107 testnet_genesis(
105 // Sudo account108 // Sudo account
106 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 // Bootnodes
129 vec![],133 vec![],
130 // Telemetry134 // Telemetry
159 .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_accounts
164 .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_accounts
173 .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}
225228
modifiednode/cli/src/cli.rsdiffbeforeafterboth
1use 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;
64
modifiednode/cli/src/command.rsdiffbeforeafterboth
18use 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 }
121121
122 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 }
126125
129 }128 }
130}129}
131130
131#[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()?;
134134
189 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 }
252252
253 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())?;
267268
268 runner.run_node_until_exit(|config| async move {269 runner.run_node_until_exit(|config| async move {
269 // TODO
270 let key = sp_core::Pair::generate().0;
271
272 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);
274272
275 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 );
310305
311 crate::service::start_node(config, key, polkadot_config, id)306 crate::service::start_node(config, polkadot_config, id)
312 .await307 .await
313 .map(|r| r.0)308 .map(|r| r.0)
314 .map_err(Into::into)309 .map_err(Into::into)
modifiednode/cli/src/service.rsdiffbeforeafterboth
1616
17// Cumulus Imports17// Cumulus Imports
18use 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;
27
28// Polkadot Imports
29use polkadot_primitives::v1::CollatorPair;
3025
31// Substrate Imports26// Substrate Imports
32use 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}
7775
85///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 to
87/// 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 = config
116 .telemetry_endpoints118 .telemetry_endpoints
117 .clone()119 .clone()
118 .filter(|x| !x.is_empty())120 .filter(|x| !x.is_empty())
134138
135 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 );
158162
186 pending_transactions,
187 filter_pool,
188 frontier_backend,
189 telemetry_worker_handle,
190 ),
182 };191 };
183192
190#[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;
231242
232 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: &parachain_config,267 config: &parachain_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: Unhardcode
288 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)?;
375
396395
397 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 );
438435
480 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,
modifiednode/rpc/Cargo.tomldiffbeforeafterboth
13futures = { 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"] }
4444
45pallet-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" }
modifiednode/rpc/src/lib.rsdiffbeforeafterboth
189 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 filters
205 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())));
218218
219 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),
modifiedpallets/contract-helpers/Cargo.tomldiffbeforeafterboth
15version = '0.1.0'15version = '0.1.0'
1616
17[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' }
2323
24[features]24[features]
25default = ["std"]25default = ["std"]
modifiedpallets/contract-helpers/src/lib.rsdiffbeforeafterboth
75 #[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 }
9396
94 #[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 }
110116
111 #[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 }
128137
129 #[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) != who
184 {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 }
193203
200 ) -> 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 None
259 }267 }
260 }268 }
modifiedpallets/inflation/Cargo.tomldiffbeforeafterboth
43default-features = false43default-features = false
44optional = true44optional = true
45git = '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'
4848
49[dependencies.frame-support]49[dependencies.frame-support]
50default-features = false50default-features = false
51git = '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'
5454
55[dependencies.frame-system]55[dependencies.frame-system]
56default-features = false56default-features = false
57git = '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'
6060
61[dependencies.pallet-balances]61[dependencies.pallet-balances]
62default-features = false62default-features = false
63git = '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'
6666
67[dependencies.pallet-timestamp]67[dependencies.pallet-timestamp]
68default-features = false68default-features = false
69git = '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'
7272
73[dependencies.pallet-randomness-collective-flip]73[dependencies.pallet-randomness-collective-flip]
74default-features = false74default-features = false
75git = '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'
7878
79[dependencies.sp-std]79[dependencies.sp-std]
80default-features = false80default-features = false
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'
8484
85[dependencies.serde]85[dependencies.serde]
90[dependencies.sp-runtime]90[dependencies.sp-runtime]
91default-features = false91default-features = false
92git = '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'
9595
96[dependencies.sp-core]96[dependencies.sp-core]
97default-features = false97default-features = false
98git = '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'
101101
102[dependencies.sp-io]102[dependencies.sp-io]
103default-features = false103default-features = false
104git = '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'
107107
108108
modifiedpallets/inflation/src/benchmarking.rsdiffbeforeafterboth

no syntactic changes

modifiedpallets/inflation/src/lib.rsdiffbeforeafterboth
3936
40use 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;
4542
modifiedpallets/inflation/src/tests.rsdiffbeforeafterboth
1#[cfg(test)]1#![cfg(test)]
2mod tests {2#![allow(clippy::from_over_into)]
3 use crate as pallet_inflation;3use crate as pallet_inflation;
44
5 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};
1515
16 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;18
19 }19const YEAR: u64 = 5_259_600;
20 20
21 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 = ();25
26 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,35
36 {36frame_support::construct_runtime!(
37 Balances: pallet_balances::{Module, Call, Storage},37 pub enum Test where
38 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;47
48 }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 = ();54
55 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 {80
81 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 applied
84 }84}
8585
86 // 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}
91
92// 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}
99
100#[test]
101fn inflation_works() {
102 new_test_ext().execute_with(|| {
103 // Total issuance = 1_000_000_000
104 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);
107
108 // BlockInflation should be set after 1st block and
109 // first inflation deposit should be equal to BlockInflation
110 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}
118
119#[test]
120fn inflation_second_deposit() {
121 new_test_ext().execute_with(|| {
122 // Total issuance = 1_000_000_000
123 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);
127
128 // Next inflation deposit happens when block is multiple of InflationBlockInterval
129 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);
137
138 // The block with inflation
139 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}
147
148#[test]
149fn inflation_in_1_year() {
150 new_test_ext().execute_with(|| {
151 // Total issuance = 1_000_000_000
152 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();
157
158 Inflation::on_initialize(YEAR);
159 let block_inflation_year_1 = Inflation::block_inflation();
160
161 // Assert that year 1 inflation is less than year 0
162 assert!(block_inflation_year_0 > block_inflation_year_1);
163 });
164}
165
166#[test]
167fn inflation_in_1_to_9_years() {
168 new_test_ext().execute_with(|| {
169 // Total issuance = 1_000_000_000
170 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);
174
175 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();
179
180 // Assert that next year inflation is less than previous year inflation
181 assert!(block_inflation_year_before > block_inflation_year_after);
182 }
183 });
184}
185
186#[test]
187fn inflation_after_year_10_is_flat() {
188 new_test_ext().execute_with(|| {
189 // Total issuance = 1_000_000_000
190 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);
194
195 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();
199
200 // Assert that next year inflation is equal to previous year inflation
201 assert_eq!(block_inflation_year_before, block_inflation_year_after);
202 }
203 });
204}
90205
91 #[test]206#[test]
92 fn inflation_works() {207fn inflation_rate_by_year() {
93 new_test_ext().execute_with(|| {
94 // Total issuance = 1_000_000_000
95 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);
98
99 // BlockInflation should be set after 1st block and
100 // first inflation deposit should be equal to BlockInflation
101 Inflation::on_initialize(1);
102 assert!(Inflation::block_inflation() > 0);
103 assert_eq!(Balances::free_balance(1234) - initial_issuance, Inflation::block_inflation());
104 });
105 }
106
107 #[test]
108 fn inflation_second_deposit() {
109 new_test_ext().execute_with(|| {
110 // Total issuance = 1_000_000_000
111 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);
115
116 // Next inflation deposit happens when block is multiple of InflationBlockInterval
117 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);
125
126 // The block with inflation
127 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 }
132
133 #[test]
134 fn inflation_in_1_year() {
135 new_test_ext().execute_with(|| {
136 // Total issuance = 1_000_000_000
137 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();
142
143 Inflation::on_initialize(YEAR);
144 let block_inflation_year_1 = Inflation::block_inflation();
145
146 // Assert that year 1 inflation is less than year 0
147 assert!(block_inflation_year_0 > block_inflation_year_1);
148 });
149 }
150
151 #[test]
152 fn inflation_in_1_to_9_years() {
153 new_test_ext().execute_with(|| {
154 // Total issuance = 1_000_000_000
155 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);
159
160 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();
164
165 // Assert that next year inflation is less than previous year inflation
166 assert!(block_inflation_year_before > block_inflation_year_after);
167 }
168
169 });
170 }
171
172 #[test]
173 fn inflation_after_year_10_is_flat() {
174 new_test_ext().execute_with(|| {
175 // Total issuance = 1_000_000_000
176 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);
180
181 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();
185
186 // Assert that next year inflation is equal to previous year inflation
187 assert_eq!(block_inflation_year_before, block_inflation_year_after);
188 }
189 });
190 }
191
192 #[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;
196210
197 // 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}
242243
modifiedpallets/nft-charge-transaction/Cargo.tomldiffbeforeafterboth
2020
21[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' }
3232
33pallet-nft-transaction-payment = { default-features = false, path="../nft-transaction-payment" }33pallet-nft-transaction-payment = { default-features = false, path="../nft-transaction-payment" }
3434
modifiedpallets/nft-charge-transaction/src/lib.rsdiffbeforeafterboth
11#[cfg(feature = "std")]11#[cfg(feature = "std")]
12pub use serde::*;12pub use serde::*;
13
14#[cfg(feature = "runtime-benchmarks")]
15mod benchmarking;
1613
17use 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, DispatchClass
23 }
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 }
10497
98 #[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 }
127121
128 // Determine who is paying transaction fee based on ecnomic model122 // Determine who is paying transaction fee based on ecnomic model
129 // Parse call to extract collection ID and access collection sponsor 123 // Parse call to extract collection ID and access collection sponsor
130 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);
131125
132 let who_pays_fee = sponsor.unwrap_or_else(|| who.clone());126 let who_pays_fee = sponsor.unwrap_or_else(|| who.clone());
modifiedpallets/nft-transaction-payment/Cargo.tomldiffbeforeafterboth
2020
21[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' }
3131
32up-sponsorship = { default-features = false, path = "../../primitives/sponsorship", version = "0.1.0" }32up-sponsorship = { default-features = false, path = "../../primitives/sponsorship", version = "0.1.0" }
3333
modifiedpallets/nft-transaction-payment/src/benchmarking.rsdiffbeforeafterboth

no syntactic changes

modifiedpallets/nft-transaction-payment/src/lib.rsdiffbeforeafterboth

no syntactic changes

modifiedpallets/nft/Cargo.tomldiffbeforeafterboth
56default-features = false56default-features = false
57optional = true57optional = true
58git = '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'
6161
62[dependencies.frame-support]62[dependencies.frame-support]
63default-features = false63default-features = false
64git = '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'
6767
68[dependencies.frame-system]68[dependencies.frame-system]
69default-features = false69default-features = false
70git = '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'
7373
74[dependencies.pallet-balances]74[dependencies.pallet-balances]
75default-features = false75default-features = false
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 = '3.0.0'78version = '3.0.0'
7979
80[dependencies.pallet-timestamp]80[dependencies.pallet-timestamp]
81default-features = false81default-features = false
82git = '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'
8585
86[dependencies.pallet-randomness-collective-flip]86[dependencies.pallet-randomness-collective-flip]
87default-features = false87default-features = false
88git = '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'
9191
92[dependencies.sp-std]92[dependencies.sp-std]
93default-features = false93default-features = false
94git = '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'
9797
98[dependencies.pallet-contracts]98[dependencies.pallet-contracts]
99default-features = false99default-features = false
100git = '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'
103103
104[dependencies.pallet-transaction-payment]104[dependencies.pallet-transaction-payment]
105default-features = false105default-features = false
106git = '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'
109109
110[dependencies.serde]110[dependencies.serde]
115[dependencies.sp-runtime]115[dependencies.sp-runtime]
116default-features = false116default-features = false
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'
120120
121[dependencies.sp-core]121[dependencies.sp-core]
122default-features = false122default-features = false
123git = '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'
126126
127[dependencies.sp-io]127[dependencies.sp-io]
128default-features = false128default-features = false
129git = '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'
132132
133133
149ethereum-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" }
153153
154evm-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"] }
156156
157pallet-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"
modifiedpallets/nft/src/benchmarking.rsdiffbeforeafterboth
55
6use 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,
99
10const 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)
4646
47 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)
5656
57 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)
6767
68 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)
7676
77 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)
8585
86 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)
9595
96 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)
105105
106 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)
116116
117 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())
125125
126 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)
135135
136 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)
146146
147 // nft item147 // nft item
148 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 156
157 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)157 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)
158158
159 #[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())?;
176176
177 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)177 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)
178178
179 // fungible item179 // fungible item
180 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();
188188
189 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)189 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)
190190
191 // refungible item191 // refungible item
192 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();
200200
201 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)201 }: create_item(RawOrigin::Signed(caller.clone()), 2, caller.clone(), data)
202202
203 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)?;
212212
213 }: burn_item(RawOrigin::Signed(caller.clone()), 2, 1)213 }: burn_item(RawOrigin::Signed(caller.clone()), 2, 1)
214214
215 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)?;
225225
226 }: transfer(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1, 1)226 }: transfer(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1, 1)
227 227
228 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)?;
238238
239 }: transfer(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1, 1)239 }: transfer(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1, 1)
240240
241 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)?;
251251
252 }: transfer(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1, 1)252 }: transfer(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1, 1)
253253
254 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)?;
264264
265 }: approve(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1)265 }: approve(RawOrigin::Signed(caller.clone()), recipient.clone(), 2, 1)
266266
267 // Nft267 // Nft
268 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)?;
279279
280 }: 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)
281281
282 // Fungible282 // Fungible
283 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)?;
294294
295 }: 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)
296296
297 // ReFungible297 // ReFungible
298 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)?;
309309
310 }: 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)
311311
312 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());
314314
315 }: enable_contract_sponsoring(RawOrigin::Signed(caller.clone()), caller.clone(), true)315 }: enable_contract_sponsoring(RawOrigin::Signed(caller.clone()), caller.clone(), true)
316316
317 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())?;
324324
325 }: 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())
326326
327 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 335
336 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())
344344
345 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)?;
354354
355 }: 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())
356356
357 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)
365365
366 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: 0
376 };376 };
377 }: set_chain_limits(RawOrigin::Signed(caller.clone()), limits)377 }: set_chain_limits(RawOrigin::Signed(caller.clone()), limits)
378378
379 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)
388388
389 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 396
397 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: 0
402 };402 };
403403
404 }: set_collection_limits(RawOrigin::Signed(caller.clone()), 2, cl)404 }: set_collection_limits(RawOrigin::Signed(caller.clone()), 2, cl)
405405
406 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())
409409
410 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())
414414
415 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}
420420
modifiedpallets/nft/src/default_weights.rsdiffbeforeafterboth
22
3impl 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_u64
6 .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_u64
11 .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_u64
16 .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_u64
21 .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_u64
26 .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_u64
31 .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_u64
36 .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_u64
41 .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_u64
46 .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_u64
51 .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_u64
56 .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_u64
61 .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_u64
66 .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 storage
67 .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_u64
72 .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_u64
77 .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_u64
82 .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_u64
87 .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_u64
92 .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_u64
97 .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_u64
102 .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_u64
107 .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_u64
112 .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_u64
117 .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_u64
122 .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_u64
127 .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_u64
132 .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_u64
137 .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_u64
142 .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_u64
147 .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_u64
152 .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}
156156
modifiedpallets/nft/src/eth/account.rsdiffbeforeafterboth
1010
11pub trait CrossAccountId<AccountId>: 11pub trait CrossAccountId<AccountId>:
12 Encode + EncodeLike + Decode + 12 Encode + EncodeLike + Decode + Clone + PartialEq + Ord + core::fmt::Debug
13 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}
2222
23#[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 encoding
27 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 where
93 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),
modifiedpallets/nft/src/eth/erc.rsdiffbeforeafterboth
58 #[indexed] operator: address,68 #[indexed]
69 operator: address,
59 approved: bool,70 approved: bool,
60 }71 },
61}72}
6273
63#[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}
107169
108#[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}
124202
125/// Runtime metadata like helpers for evm
126#[solidity_interface]
127trait UniqueHelpers {
128 type Error;
129
130 /// Returns interface for NFT collections
131 fn nft_interface(&self) -> Result<string, Self::Error>;
132 /// Returns interface for Fungible collections
133 fn fungible_interface(&self) -> Result<string, Self::Error>;
134}
modifiedpallets/nft/src/eth/erc_impl.rsdiffbeforeafterboth
56 Ok(index)56 Ok(index)
57 }57 }
5858
59 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 implemetable
61 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")?;
116116
117 <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")?;
132132
133 <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")?;
178178
179 <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")?;
228228
229 <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")?;
244244
245 <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")?;
253253
254 <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 }
modifiedpallets/nft/src/eth/log.rsdiffbeforeafterboth
1use sp_std::cell::RefCell;1use sp_std::cell::RefCell;
2use sp_std::vec::Vec;2use sp_std::vec::Vec;
3use sp_core::{H160, H256};3
4use ethereum::Log;4use ethereum::Log;
55
6#[derive(Default)]6#[derive(Default)]
modifiedpallets/nft/src/eth/mod.rsdiffbeforeafterboth
28];28];
2929
30fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {30fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {
31 if &eth[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}
103100
111 .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);
156153
157// TODO: This function is slow, and output can be memoized154// TODO: This function is slow, and output can be memoized
158pub 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);
160
161 // 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/8728
162 #[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}
189185
modifiedpallets/nft/src/eth/sponsoring.rsdiffbeforeafterboth
22
3use 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;
1120
52 })
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_timeout
50 }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_timeout
67 } else {90 } else {
68 ChainLimit::get().fungible_sponsor_transfer_timeout91 ChainLimit::get().fungible_sponsor_transfer_timeout
69 };92 };
7093
71 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}
92120
93impl<T> pallet_evm::OnChargeEVMTransaction<T> for ChargeEvmTransaction121impl<T> pallet_evm::OnChargeEVMTransaction<T> for ChargeEvmTransaction
104 ) -> 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 }
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
6#![recursion_limit = "1024"]6#![recursion_limit = "1024"]
7
8#![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_unit
12)]
913
10extern crate alloc;14extern crate alloc;
1115
3033
31use 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;
4447
211 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.collection
215 }217 }
216}218}
217impl<T: Config> Deref for CollectionHandle<T> {219impl<T: Config> Deref for CollectionHandle<T> {
236238
237 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>;
240241
241 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>;
245248
375 CrossAccountId = <T as Config>::CrossAccountId,378 CrossAccountId = <T as Config>::CrossAccountId,
376 {379 {
377 /// New collection was created380 /// New collection was created
378 /// 381 ///
379 /// # Arguments382 /// # Arguments
380 /// 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),
387390
388 /// New item was created.391 /// New item was created.
389 /// 392 ///
390 /// # Arguments393 /// # Arguments
391 /// 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 item
397 ItemCreated(CollectionId, TokenId, CrossAccountId),400 ItemCreated(CollectionId, TokenId, CrossAccountId),
398401
399 /// Collection item was burned.402 /// Collection item was burned.
400 /// 403 ///
401 /// # Arguments404 /// # Arguments
402 /// 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),
407410
444 }447 }
445448
446 /// 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 /// # Permissions
449 /// 452 ///
450 /// * Anyone.453 /// * Anyone.
451 /// 454 ///
452 /// # Arguments455 /// # Arguments
453 /// 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 ID
462 #[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);
537540
538 // call event541 // call event
539 Self::deposit_event(RawEvent::CollectionCreated(next_id, mode.into(), who));542 Self::deposit_event(RawEvent::CollectionCreated(next_id, mode.id(), who));
540543
541 Ok(())544 Ok(())
542 }545 }
543546
544 /// **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 /// # Permissions
547 /// 550 ///
548 /// * Collection Owner.551 /// * Collection Owner.
549 /// 552 ///
550 /// # Arguments553 /// # Arguments
551 /// 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 }
588591
589 /// Add an address to white list.592 /// Add an address to white list.
590 /// 593 ///
591 /// # Permissions594 /// # Permissions
592 /// 595 ///
593 /// * Collection Owner596 /// * Collection Owner
594 /// * Collection Admin597 /// * Collection Admin
595 /// 598 ///
596 /// # Arguments599 /// # Arguments
597 /// 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 }
617620
618 /// Remove an address from white list.621 /// Remove an address from white list.
619 /// 622 ///
620 /// # Permissions623 /// # Permissions
621 /// 624 ///
622 /// * Collection Owner625 /// * Collection Owner
623 /// * Collection Admin626 /// * Collection Admin
624 /// 627 ///
625 /// # Arguments628 /// # Arguments
626 /// 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 }
646649
647 /// 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 /// # Permissions
650 /// 653 ///
651 /// * Collection Owner.654 /// * Collection Owner.
652 /// 655 ///
653 /// # Arguments656 /// # Arguments
654 /// 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, and
674 /// * Address is added to white list, and677 /// * Address is added to white list, and
675 /// * This method was called with True parameter678 /// * This method was called with True parameter
676 /// 679 ///
677 /// # Permissions680 /// # Permissions
678 /// * Collection Owner681 /// * Collection Owner
679 ///682 ///
680 /// # Arguments683 /// # Arguments
681 /// 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 }
698701
699 /// Change the owner of the collection.702 /// Change the owner of the collection.
700 /// 703 ///
701 /// # Permissions704 /// # Permissions
702 /// 705 ///
703 /// * Collection Owner.706 /// * Collection Owner.
704 /// 707 ///
705 /// # Arguments708 /// # Arguments
706 /// 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 }
722725
723 /// 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 /// # Permissions
727 /// 730 ///
728 /// * Collection Owner.731 /// * Collection Owner.
729 /// * Collection Admin.732 /// * Collection Admin.
730 /// 733 ///
731 /// # Arguments734 /// # Arguments
732 /// 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 /// # Permissions
759 /// 762 ///
760 /// * Collection Owner.763 /// * Collection Owner.
761 /// * Collection Admin.764 /// * Collection Admin.
762 /// 765 ///
763 /// # Arguments766 /// # Arguments
764 /// 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);
775778
776 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 }
785785
786 /// # Permissions786 /// # Permissions
787 /// 787 ///
788 /// * Collection Owner788 /// * Collection Owner
789 /// 789 ///
790 /// # Arguments790 /// # Arguments
791 /// 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 }
807807
808 /// # Permissions808 /// # Permissions
809 /// 809 ///
810 /// * Sponsor.810 /// * Sponsor.
811 /// 811 ///
812 /// # Arguments812 /// # Arguments
813 /// 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 /// # Permissions
835 ///835 ///
836 /// * Collection owner.836 /// * Collection owner.
837 /// 837 ///
838 /// # Arguments838 /// # Arguments
839 /// 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 }
854854
855 /// 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 /// # Permissions
858 /// 858 ///
859 /// * Collection Owner.859 /// * Collection Owner.
860 /// * Collection Admin.860 /// * Collection Admin.
861 /// * Anyone if861 /// * Anyone if
862 /// * White List is enabled, and862 /// * White List is enabled, and
863 /// * Address is added to white list, and863 /// * Address is added to white list, and
864 /// * MintPermission is enabled (see SetMintPermission method)864 /// * MintPermission is enabled (see SetMintPermission method)
865 /// 865 ///
866 /// # Arguments866 /// # Arguments
867 /// 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))]
878878
879 #[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 }
890890
891 /// 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 /// # Permissions
894 /// 894 ///
895 /// * Collection Owner.895 /// * Collection Owner.
896 /// * Collection Admin.896 /// * Collection Admin.
897 /// * Anyone if897 /// * Anyone if
898 /// * White List is enabled, and898 /// * White List is enabled, and
899 /// * Address is added to white list, and899 /// * Address is added to white list, and
900 /// * MintPermission is enabled (see SetMintPermission method)900 /// * MintPermission is enabled (see SetMintPermission method)
901 /// 901 ///
902 /// # Arguments902 /// # Arguments
903 /// 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 {
914914
915 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)?;
918918
923 }923 }
924924
925 /// Destroys a concrete instance of NFT.925 /// Destroys a concrete instance of NFT.
926 /// 926 ///
927 /// # Permissions927 /// # Permissions
928 /// 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 /// # Arguments
934 /// 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 }
950950
951 /// Change ownership of the token.951 /// Change ownership of the token.
952 /// 952 ///
953 /// # Permissions953 /// # Permissions
954 /// 954 ///
955 /// * Collection Owner955 /// * Collection Owner
956 /// * Collection Admin956 /// * Collection Admin
957 /// * Current NFT owner957 /// * Current NFT owner
958 ///958 ///
959 /// # Arguments959 /// # Arguments
960 /// 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 item
966 /// * 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: Ignored
972 /// * Fungible Mode: Must specify transferred amount972 /// * Fungible Mode: Must specify transferred amount
984 }984 }
985985
986 /// 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 /// # Permissions
989 /// 989 ///
990 /// * Collection Owner990 /// * Collection Owner
991 /// * Collection Admin991 /// * Collection Admin
992 /// * Current NFT owner992 /// * Current NFT owner
993 /// 993 ///
994 /// # Arguments994 /// # Arguments
995 /// 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 1012
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.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 /// # Permissions
1016 /// * Collection Owner1016 /// * Collection Owner
1017 /// * Collection Admin1017 /// * Collection Admin
1018 /// * Current NFT owner1018 /// * Current NFT owner
1019 /// * Address approved by current NFT owner1019 /// * Address approved by current NFT owner
1020 /// 1020 ///
1021 /// # Arguments1021 /// # Arguments
1022 /// 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 // }
10551055
1056 /// Set off-chain data schema.1056 /// Set off-chain data schema.
1057 /// 1057 ///
1058 /// # Permissions1058 /// # Permissions
1059 /// 1059 ///
1060 /// * Collection Owner1060 /// * Collection Owner
1061 /// * Collection Admin1061 /// * Collection Admin
1062 /// 1062 ///
1063 /// # Arguments1063 /// # Arguments
1064 /// 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 standard
1086 /// ImageURL1086 /// ImageURL
1087 /// Unique1087 /// Unique
1088 /// 1088 ///
1089 /// # Permissions1089 /// # Permissions
1090 /// 1090 ///
1091 /// * Collection Owner1091 /// * Collection Owner
1092 /// * Collection Admin1092 /// * Collection Admin
1093 /// 1093 ///
1094 /// # Arguments1094 /// # Arguments
1095 /// 1095 ///
1096 /// * collection_id.1096 /// * collection_id.
1097 /// 1097 ///
1098 /// * schema: SchemaVersion: enum1098 /// * schema: SchemaVersion: enum
1099 #[weight = <T as Config>::WeightInfo::set_schema_version()]1099 #[weight = <T as Config>::WeightInfo::set_schema_version()]
1100 #[transactional]1100 #[transactional]
1113 }1113 }
11141114
1115 /// Set off-chain data schema.1115 /// Set off-chain data schema.
1116 /// 1116 ///
1117 /// # Permissions1117 /// # Permissions
1118 /// 1118 ///
1119 /// * Collection Owner1119 /// * Collection Owner
1120 /// * Collection Admin1120 /// * Collection Admin
1121 /// 1121 ///
1122 /// # Arguments1122 /// # Arguments
1123 /// 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 }
11461146
1147 /// Set const on-chain data schema.1147 /// Set const on-chain data schema.
1148 /// 1148 ///
1149 /// # Permissions1149 /// # Permissions
1150 /// 1150 ///
1151 /// * Collection Owner1151 /// * Collection Owner
1152 /// * Collection Admin1152 /// * Collection Admin
1153 /// 1153 ///
1154 /// # Arguments1154 /// # Arguments
1155 /// 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 }
11781178
1179 /// Set variable on-chain data schema.1179 /// Set variable on-chain data schema.
1180 /// 1180 ///
1181 /// # Permissions1181 /// # Permissions
1182 /// 1182 ///
1183 /// * Collection Owner1183 /// * Collection Owner
1184 /// * Collection Admin1184 /// * Collection Admin
1185 /// 1185 ///
1186 /// # Arguments1186 /// # Arguments
1187 /// 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();
12381238
1267 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)?;
12681273
1269 Ok(())1274 Ok(())
1270 }1275 }
12711276
1272 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 check
1275 Self::is_correct_transfer(target_collection, &recipient)?;1286 Self::is_correct_transfer(target_collection, recipient)?;
12761287
1277 // Transfer permissions check1288 // Transfer permissions check
1278 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>::NoPermission
1293 );
12811294
1282 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 }
12861299
1287 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 };
12941319
1295 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)?;
13091340
1310 // Transfer permissions check1341 // Transfer permissions check
1311 let bypasses_limits = collection.limits.owner_can_transfer &&1342 let bypasses_limits = collection.limits.owner_can_transfer
1312 Self::is_owner_or_admin_permissions(1343 && Self::is_owner_or_admin_permissions(collection, sender);
1313 &collection,
1314 &sender,
1315 );
13161344
1317 let allowance_limit = if bypasses_limits {1345 let allowance_limit = if bypasses_limits {
1318 None1346 None
1319 } 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 };
13281352
1329 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 }
13331357
1334 let allowance: u128 = amount1358 let allowance: u128 = amount
1353 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 }
13591390
1412 <Allowances<T>>::get(collection.id, (item_id, from.as_sub(), sender.as_sub()));
13751413
1376 // Limits check1414 // Limits check
1377 Self::is_correct_transfer(&collection, &recipient)?;1415 Self::is_correct_transfer(collection, recipient)?;
13781416
1379 // Transfer permissions check1417 // Transfer permissions check
1380 ensure!(1418 ensure!(
1381 approval >= amount || 1419 approval >= amount
1382 (1420 || (collection.limits.owner_can_transfer
1383 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>::NoPermission
1387 );1423 );
13881424
1389 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 }
13931429
1394 // 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 0
14011441
1402 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 };
14141458
1415 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 }
14221466
1429 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)?;
14331477
1434 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>::TokenVariableDataLimitExceeded
1481 );
14351482
1436 // Modify permissions check1483 // Modify permissions check
1437 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>::NoPermission
1488 );
14401489
1441 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 };
14481498
1449 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)?;
14591509
1460 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 }
14661516
1467 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_transfer
1479 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>::NoPermission
1483 );1531 );
14841532
1485 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 }
14881536
1489 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 };
14961543
1497 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)?;
15071554
1508 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>::AccountTokenLimitExceeded
1604 );
15391605
1540 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 {
1569
1577 } 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 };
15961683
1597 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 }];
16051694
1606 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 };
16111700
1612 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;
16241717
1625 // Mint 1718 // Mint
1626 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 };
17991902
1800 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.owner
1930 || <AdminList<T>>::get(collection.id).contains(subject)
1821 }1931 }
18221932
1837 let collection_id = target_collection.id;1950 let collection_id = target_collection.id;
18381951
1839 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 .owner
1846 .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 }
18591978
1866 Ok(())1991 Ok(())
1867 }1992 }
18681993
1869 /// 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 for
1870 /// the owner in fungible balances double map1995 /// the owner in fungible balances double map
1871 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 };
18832006
1884 ensure!(exists == true, Error::<T>::TokenNotFound);2007 ensure!(exists, Error::<T>::TokenNotFound);
1885 Ok(())2008 Ok(())
1886 }2009 }
18872010
1935 let item = full_item2063 let item = full_item
1936 .owner2064 .owner
1937 .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;
19422069
1956 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);
19582085
2086 let mut new_full_item = full_item.clone();
1959 // transfer2087 // transfer
1960 if amount == value && !new_owner_has_account {2088 if amount == value && !new_owner_has_account {
1961 // change owner2089 // change owner
1962 // new owner do not have account2090 // new owner do not have account
1963 let mut new_full_item = full_item.clone();
1964 new_full_item2091 new_full_item
1965 .owner2092 .owner
1966 .iter_mut()2093 .iter_mut()
1972 // update index collection2099 // update index collection
1973 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_item
1977 .owner2103 .owner
1978 .iter_mut()2104 .iter_mut()
2186 let item_contains = list.contains(&item_index.clone());2326 let item_contains = list.contains(&item_index.clone());
21872327
2188 if !item_contains {2328 if !item_contains {
2189 list.push(item_index.clone());2329 list.push(item_index);
2190 }2330 }
21912331
2192 <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 }
21982337
modifiedpallets/nft/src/mock.rsdiffbeforeafterboth
1#![allow(clippy::from_over_into)]
2
1use 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};
1416
15type 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);
3032
56 type OnKilledAccount = ();58 type OnKilledAccount = ();
57 type SystemWeightInfo = ();59 type SystemWeightInfo = ();
58 type SS58Prefix = SS58Prefix;60 type SS58Prefix = SS58Prefix;
61 type OnSetCode = ();
59}62}
6063
61parameter_types! {64parameter_types! {
78}81}
7982
80impl 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}
9699
97type 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>;
99102
100parameter_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}
113115
114impl 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}
136137
137parameter_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}
143
144pub struct TestEvmAddressMapping;
145impl AddressMapping<u64> for TestEvmAddressMapping {
146 fn into_account_id(_addr: sp_core::H160) -> u64 {
147 unimplemented!()
148 }
149}
150
151pub struct TestEvmBackwardsAddressMapping;
152impl EvmBackwardsAddressMapping<u64> for TestEvmBackwardsAddressMapping {
153 fn from_account_id(_account_id: u64) -> sp_core::H160 {
154 unimplemented!()
155 }
156}
157
158#[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.0
168 }
169 fn from_eth(_eth: sp_core::H160) -> Self {
170 unimplemented!()
171 }
172 fn as_eth(&self) -> &sp_core::H160 {
173 &self.1
174 }
175}
176
177pub 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}
141186
142impl 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}
149199
150// Build genesis storage according to the mock runtime.200// Build genesis storage according to the mock runtime.
modifiedpallets/nft/src/sponsorship.rsdiffbeforeafterboth
1use 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;
1013
11pub 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);
3335
34 // check free create limit36 // check free create limit
35 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 {
128125
129 sponsored126 sponsored
130 }127 }
131 _ => {128 _ => false,
132 false
133 },
134 };129 };
135 }130 }
136131
145 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> {
150
151 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 176where
186 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 }
modifiedpallets/nft/src/tests.rsdiffbeforeafterboth
1// Tests to be written here1// Tests to be written here
2use 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};
911
10fn default_collection_numbers_limit() -> u32 {12fn default_collection_numbers_limit() -> u32 {
11 1013 10
12}14}
1315
14fn 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}
2833
29fn 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}
3240
33fn default_fungible_data () -> CreateFungibleData {41fn default_fungible_data() -> CreateFungibleData {
34 CreateFungibleData { value: 5 }42 CreateFungibleData { value: 5 }
35}43}
3644
37fn 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}
4052
41fn 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();
4561
46 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 ));
5470
55 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_name
78 );
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_description
83 );
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_prefix
87 );
63 id88 id
64}89}
6590
66fn 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}
6994
70fn 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}
78104
105fn account(sub: u64) -> TestCrossAccountId {
106 TestCrossAccountId::from_sub(sub)
79}107}
80108
81// Use cases tests region109// Use cases tests region
82// #region110// #region
83111
84#[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 118
91 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::Unique
123 ));
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::Unique
129 );
93 });130 });
94}131}
95132
96#[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();
100137
101 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();
104141
105 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>::CollectionDecimalPointLimitExceeded
152 );
113 }); 153 });
114}154}
115155
116#[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 161
122 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}
129169
130// Use cases tests region170// Use cases tests region
131// #region171// #region
132#[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);
138176
139 let origin1 = Origin::signed(1);177 create_test_collection(&CollectionMode::NFT, 1);
140178
141 let items_data = vec![default_nft_data(), default_nft_data(), default_nft_data()];179 let origin1 = Origin::signed(1);
142180
143 assert_ok!(TemplateModule::create_multiple_items(181 let items_data = vec![default_nft_data(), default_nft_data(), default_nft_data()];
182
183 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_data
188 .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}
156200
157#[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);
162206
163 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_data
169 );
170 assert_eq!(211 assert_eq!(item.variable_data, data.variable_data);
171 item.variable_data,
172 data.variable_data
173 );
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: 1023
179 }217 }
180 );218 );
181 });219 });
182}220}
183221
184#[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);
190226
191 let origin1 = Origin::signed(1);227 create_test_collection(&CollectionMode::ReFungible, 1);
192228
193 let items_data = vec![default_re_fungible_data(), default_re_fungible_data(), default_re_fungible_data()];229 let origin1 = Origin::signed(1);
194230
195 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() {
202236
237 assert_ok!(TemplateModule::create_multiple_items(
238 origin1,
239 1,
240 account(1),
241 items_data
242 .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: 1023
211 }256 }
212 );257 );
213 }258 }
214 });259 });
215}260}
216261
217#[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);
223266
224 let data = default_fungible_data();267 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);
225 create_test_item(collection_id, &data.into());
226268
227 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());
271
272 assert_eq!(TemplateModule::fungible_item_id(collection_id, 1).value, 5);
228 });273 });
229}274}
230275
231//#[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 293
249// 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// }
256301
257#[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);
263306
264 let origin1 = Origin::signed(1);307 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);
265 let origin2 = Origin::signed(2);
266308
267 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);
269311
270 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());
272314
273 // change owner scenario
274 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);
278317
279 // split item scenario318 // change owner scenario
280 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);
283323
284 // split item and new owner has account scenario324 // split item scenario
325 assert_ok!(TemplateModule::transfer(
326 origin2.clone(),
327 account(3),
328 1,
329 1,
330 3
331 ));
332 assert_eq!(TemplateModule::balance_count(1, 2), 2);
333 assert_eq!(TemplateModule::balance_count(1, 3), 3);
334
335 // split item and new owner has account scenario
285 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}
292343
293#[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);
299348
300 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());
302350
303 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_data
310 );
311 assert_eq!(
312 item.variable_data,
313 data.variable_data
314 );
315 assert_eq!(
316 item.owner[0],
317 Ownership {
318 owner: 1,
319 fraction: 1023
320 }
321 );
322 }
323 assert_eq!(TemplateModule::balance_count(1, 1), 1023);
324 assert_eq!(TemplateModule::address_tokens(1, 1), [1]);
325353
326 // 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: 1023
333 }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]);
339370
340 // split item scenario371 // change owner scenario
341 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: 523
349 }
350 );
351 assert_eq!(
352 item.owner[1],
353 Ownership {
354 owner: 3,
355 fraction: 500377 fraction: 1023
356 }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]);
363384
364 // split item and new owner has account scenario385 // split item scenario
365 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 500
392 ));
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: 523
400 }
401 );
402 assert_eq!(
403 item.owner[1],
404 Ownership {
405 owner: account(3),
406 fraction: 500
407 }
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]);
414
415 // split item and new owner has account scenario
374 );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: 323
424 }
425 );
426 assert_eq!(
427 item.owner[1],
377 Ownership {428 Ownership {
378 owner: 3,429 owner: account(3),
379 fraction: 700430 fraction: 700
380 }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}
389440
390#[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);
396445
397 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]);
401447
402 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]);
452
453 let origin1 = Origin::signed(1);
403 // default scenario454 // default scenario
404 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}
412463
413#[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);
419468
420 let data = default_nft_data();469 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
421 create_test_item(collection_id, &data.into());
422470
423 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());
425473
426 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);
428476
429 // neg transfer
430 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);
437479
438 // do approve480 // neg transfer
439 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>::NoPermission
442 TemplateModule::approved(1, (1, 1, 2)),
443 5
444 );484 );
445485
446 assert_ok!(TemplateModule::transfer_from(486 // do approve
447 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);
490
491 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 1
453 ));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}
457502
458#[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);
464507
465 let origin1 = Origin::signed(1);508 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
466 let origin2 = Origin::signed(2);
467509
468 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);
470512
471 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]);
474515
475 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_data
479 ));
480 assert_ok!(TemplateModule::set_public_access_mode(
481 origin1.clone(),
482 1,
483 AccessMode::WhiteList
484 ));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]);
488522
489 // do approve
490 assert_ok!(TemplateModule::approve(origin1.clone(), 2, 1, 1, 5));523 assert_ok!(TemplateModule::set_mint_permission(
524 origin1.clone(),
525 1,
526 true
527 ));
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::WhiteList
532 ));
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 ));
494548
495 assert_ok!(TemplateModule::transfer_from(549 // do approve
550 assert_ok!(TemplateModule::approve(
496 origin2.clone(),551 origin1.clone(),
552 account(2),
553 1,
554 1,
555 5
556 ));
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);
560
561 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 1
502 ));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}
506572
507#[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);
516577
517 let data = default_re_fungible_data();578 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
518 create_test_item(collection_id, &data.into());
519579
520 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);
522582
523 assert_ok!(TemplateModule::set_mint_permission(583 let data = default_re_fungible_data();
524 origin1.clone(),
525 1,
526 true
527 ));
528 assert_ok!(TemplateModule::set_public_access_mode(584 create_test_item(collection_id, &data.into());
529 origin1.clone(),
530 1,
531 AccessMode::WhiteList
532 ));
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));
536585
537 // do approve
538 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]);
540588
541 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 true
545 1,
546 1,
547 100
548 ));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::WhiteList
598 ));
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 ));
553614
554 assert_eq!(615 // do approve
616 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);
618
619 assert_ok!(TemplateModule::transfer_from(
620 origin2,
621 account(1),
622 account(3),
623 1,
624 1,
625 100
626 ));
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]);
631
558 });632 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 923);
633 });
559}634}
560635
561#[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());
570640
571 let origin1 = Origin::signed(1);641 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);
572 let origin2 = Origin::signed(2);
573642
574 assert_eq!(TemplateModule::balance_count(1, 1), 5);643 let data = default_fungible_data();
644 create_test_item(collection_id, &data.into());
575645
576 assert_ok!(TemplateModule::set_mint_permission(646 let origin1 = Origin::signed(1);
577 origin1.clone(),
578 1,
579 true
580 ));
581 assert_ok!(TemplateModule::set_public_access_mode(
582 origin1.clone(),
583 1,
584 AccessMode::WhiteList
585 ));
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));
589648
590 // do approve
591 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 5
598 );
599650
600 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 true
655 ));
656 assert_ok!(TemplateModule::set_public_access_mode(
604 1,657 origin1.clone(),
605 1,658 1,
606 4659 AccessMode::WhiteList
607 ));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 ));
610676
611 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1);677 // do approve
678 assert_ok!(TemplateModule::approve(
679 origin1.clone(),
680 account(2),
681 1,
682 1,
683 5
684 ));
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);
612689
613 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 4
697 ));
619 4698 assert_eq!(TemplateModule::balance_count(1, 1), 1);
699 assert_eq!(TemplateModule::balance_count(1, 3), 4);
700
701 assert_eq!(TemplateModule::approved(1, (1, 1, 2)), 1);
702
703 assert_noop!(
620 ), Error::<Test>::NoPermission);704 TemplateModule::transfer_from(origin2, account(1), account(3), 1, 1, 4),
705 Error::<Test>::NoPermission
706 );
621 });707 });
622}708}
623709
624#[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 714
629 let collection_id = create_test_collection(&CollectionMode::NFT, 1);715 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
630 716
631 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 2
636 ));722 ));
637 assert_eq!(TemplateModule::collection_id(collection_id).unwrap().owner, 2);723 assert_eq!(
724 TemplateModule::collection_id(collection_id).unwrap().owner,
725 2
726 );
638 });727 });
639}728}
640729
641#[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 734
646 let collection_id = create_test_collection(&CollectionMode::NFT, 1);735 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
647 736
648 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}
652741
653#[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);
659746
660 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());
665748
666 // 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 ));
668755
669 // 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>::TokenNotFound
674 );
675758
676 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);
761
677 });762 // burn item
763 assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 5));
764 assert_noop!(
765 TemplateModule::burn_item(origin1, 1, 1, 5),
766 Error::<Test>::TokenNotFound
767 );
768
769 assert_eq!(TemplateModule::balance_count(1, 1), 0);
770 });
678}771}
679772
680#[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());
692777
693 // 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);
695779
696 // 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 ));
702786
703 assert_eq!(TemplateModule::balance_count(1, 1), 0);787 let data = default_fungible_data();
788 create_test_item(collection_id, &data.into());
789
790 // check balance (collection with id = 1, user id = 1)
791 assert_eq!(TemplateModule::balance_count(1, 1), 5);
792
704 });793 // burn item
794 assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 5));
795 assert_noop!(
796 TemplateModule::burn_item(origin1, 1, 1, 5),
797 Error::<Test>::TokenValueNotEnough
798 );
799
800 assert_eq!(TemplateModule::balance_count(1, 1), 0);
801 });
705}802}
706803
707#[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);
714808
715 assert_ok!(TemplateModule::set_mint_permission(809 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
716 origin1.clone(),
717 collection_id,
718 true
719 ));
720 assert_ok!(TemplateModule::set_public_access_mode(810 let origin1 = Origin::signed(1);
721 origin1.clone(),
722 collection_id,
723 AccessMode::WhiteList
724 ));
725 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
726811
727 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 true
816 ));
817 assert_ok!(TemplateModule::set_public_access_mode(
729 let data = default_re_fungible_data();818 origin1.clone(),
819 collection_id,
820 AccessMode::WhiteList
821 ));
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 ));
731827
732 // 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 ));
734833
735 // 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>::TokenNotFound
740 );
741836
742 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);
839
743 });840 // burn item
841 assert_ok!(TemplateModule::burn_item(origin1.clone(), 1, 1, 1023));
842 assert_noop!(
843 TemplateModule::burn_item(origin1, 1, 1, 1023),
844 Error::<Test>::TokenNotFound
845 );
846
847 assert_eq!(TemplateModule::balance_count(1, 1), 0);
848 });
744}849}
745850
746#[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);
756855
757 // 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);
760859
761 assert_eq!(TemplateModule::admin_list_collection(collection1_id).contains(&2), true);860 let origin1 = Origin::signed(1);
861
862 // collection admin
863 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 ));
873
874 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}
765878
766#[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);
774883
775 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);
777887
778 // 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);
781890
782 assert_eq!(TemplateModule::admin_list_collection(1).contains(&2), true);891 // collection admin
892 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 ));
784902
903 assert!(TemplateModule::admin_list_collection(1).contains(&account(2)),);
904 assert!(TemplateModule::admin_list_collection(1).contains(&account(3)),);
905
785 // remove admin906 // remove admin
786 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}
794915
795#[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 before
805 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);
808920
809 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());
817924
818 // check balance (collection with id = 1, user id = 1)925 // check balance before
926 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 0
931 );
932
933 let nft_data = default_nft_data();
934 create_test_item(nft_collection_id, &nft_data.into());
935
936 let fungible_data = default_fungible_data();
937 create_test_item(fungible_collection_id, &fungible_data.into());
938
939 let re_fungible_data = default_re_fungible_data();
940 create_test_item(re_fungible_collection_id, &re_fungible_data.into());
941
942 // 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 1023
948 );
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 5
958 );
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}
827968
828#[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());
837973
838 let origin1 = Origin::signed(1);974 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
839 975
976 let data = default_nft_data();
977 create_test_item(collection_id, &data.into());
978
979 let origin1 = Origin::signed(1);
980
840 // approve981 // approve
841 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}
845986
846#[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);
854991
855 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);
857995
858 // 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());
861998
862 assert_ok!(TemplateModule::set_mint_permission(999 // approve
1000 assert_ok!(TemplateModule::approve(
863 origin1.clone(),1001 origin1.clone(),
864 1,
865 true
866 ));
867 assert_ok!(TemplateModule::set_public_access_mode(1002 account(2),
868 origin1.clone(),
869 1,1003 1,
870 AccessMode::WhiteList1004 1,
1005 1
871 ));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));
8751008
876 assert_ok!(TemplateModule::transfer_from(1009 assert_ok!(TemplateModule::set_mint_permission(
877 origin2.clone(),1010 origin1.clone(),
878 1,1011 1,
1012 true
1013 ));
1014 assert_ok!(TemplateModule::set_public_access_mode(
879 2,1015 origin1.clone(),
880 1,1016 1,
1017 AccessMode::WhiteList
1018 ));
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)));
8841030
1031 assert_ok!(TemplateModule::transfer_from(
1032 origin2,
1033 account(1),
1034 account(2),
1035 1,
1036 1,
1037 1
1038 ));
1039
885 // after transfer1040 // after transfer
886 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}
8901045
891// #endregion1046// #endregion
8951050
896#[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);
9021055
903 let origin1 = Origin::signed(1);1056 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
1057
1058 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}
9081067
909#[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);
9171072
918 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);
1076
1077 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}
9231090
924#[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);
9301095
931 let origin2 = Origin::signed(2);1096 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
1097
1098 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>::NoPermission
935 );1102 );
936 });1103 });
937}1104}
9381105
939#[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();
9431110
944 let origin1 = Origin::signed(1);1111 let origin1 = Origin::signed(1);
9451112
946 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>::CollectionNotFound
949 );1116 );
950 });1117 });
951}1118}
9521119
953#[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);
9591124
960 let origin1 = Origin::signed(1);1125 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
1126
1127 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_id
1131 ));
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>::CollectionNotFound
965 );1135 );
966 });1136 });
967}1137}
9681138
969// If address is already added to white list, nothing happens1139// If address is already added to white list, nothing happens
970#[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 1144
975 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 1147
978 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}
9831161
984#[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);
9901166
991 let origin1 = Origin::signed(1);1167 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
1168
1169 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}
10011183
1002#[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);
10101188
1011 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);
10121192
1013 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 ));
1198
1199 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}
10221212
1023#[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);
10311217
1032 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);
1221
1222 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>::NoPermission
1036 );1230 );
1037 assert_eq!(TemplateModule::white_list(collection_id, 2), true);1231 assert!(TemplateModule::white_list(collection_id, 2));
1038 });1232 });
1039}1233}
10401234
1041#[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);
10461240
1047 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>::CollectionNotFound
1050 );1244 );
1051 });1245 });
1052}1246}
10531247
1054#[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);
10621252
1063 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);
1256
1257 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>::CollectionNotFound
1068 );1266 );
1069 assert_eq!(TemplateModule::white_list(collection_id, 2), false);1267 assert!(!TemplateModule::white_list(collection_id, 2));
1070 });1268 });
1071}1269}
10721270
1073// If address is already removed from white list, nothing happens1271// If address is already removed from white list, nothing happens
1074#[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);
10811276
1082 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);
1279
1280 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}
10961298
1097// 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);
11041304
1105 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());
11091306
1110 assert_ok!(TemplateModule::set_public_access_mode(1307 let origin1 = Origin::signed(1);
1111 origin1.clone(),
1112 collection_id,
1113 AccessMode::WhiteList
1114 ));
1115 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));
11161308
1117 assert_noop!(1309 let data = default_nft_data();
1310 create_test_item(collection_id, &data.into());
1311
1312 assert_ok!(TemplateModule::set_public_access_mode(
1313 origin1.clone(),
1314 collection_id,
1315 AccessMode::WhiteList
1316 ));
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 ));
1322
1323 assert_noop!(
1324 TemplateModule::transfer(origin1, account(3), 1, 1, 1),
1119 Error::<Test>::AddresNotInWhiteList1325 Error::<Test>::AddresNotInWhiteList
1120 );1326 );
1121 });1327 });
1122}1328}
11231329
1124#[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());
11341334
1135 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::WhiteList
1139 ));
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);
11421337
1143 // 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());
11461340
1147 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::WhiteList
1345 ));
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 ));
11521356
1153 assert_noop!(1357 // do approve
1358 assert_ok!(TemplateModule::approve(
1359 origin1.clone(),
1360 account(1),
1361 1,
1362 1,
1363 1
1364 ));
1154 TemplateModule::transfer_from(origin1.clone(), 1, 3, 1, 1, 1),1365 assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 1);
1366
1367 assert_ok!(TemplateModule::remove_from_white_list(
1368 origin1.clone(),
1369 1,
1370 account(1)
1371 ));
1372
1373 assert_noop!(
1374 TemplateModule::transfer_from(origin1, account(1), account(3), 1, 1, 1),
1155 Error::<Test>::AddresNotInWhiteList1375 Error::<Test>::AddresNotInWhiteList
1156 );1376 );
1157 });1377 });
1158}1378}
11591379
1160// 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);
11671385
1168 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());
11721387
1173 assert_ok!(TemplateModule::set_public_access_mode(1388 let origin1 = Origin::signed(1);
1174 origin1.clone(),
1175 collection_id,
1176 AccessMode::WhiteList
1177 ));
1178 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), 1, 1));
11791389
1180 assert_noop!(1390 let data = default_nft_data();
1391 create_test_item(collection_id, &data.into());
1392
1393 assert_ok!(TemplateModule::set_public_access_mode(
1394 origin1.clone(),
1395 collection_id,
1396 AccessMode::WhiteList
1397 ));
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 ));
1403
1404 assert_noop!(
1405 TemplateModule::transfer(origin1, account(3), 1, 1, 1),
1182 Error::<Test>::AddresNotInWhiteList1406 Error::<Test>::AddresNotInWhiteList
1183 );1407 );
1184 });1408 });
1185}1409}
11861410
1187#[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);
11931415
1194 let origin1 = Origin::signed(1);1416 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
11951417
1196 let data = default_nft_data();1418 let origin1 = Origin::signed(1);
1197 create_test_item(collection_id, &data.into());
11981419
1199 assert_ok!(TemplateModule::set_public_access_mode(1420 let data = default_nft_data();
1200 origin1.clone(),
1201 collection_id,
1202 AccessMode::WhiteList
1203 ));
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));
12061422
1207 // do approve
1208 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::WhiteList
1427 ));
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 ));
12101438
1211 assert_ok!(TemplateModule::remove_from_white_list(1439 // do approve
1440 assert_ok!(TemplateModule::approve(
1212 origin1.clone(),1441 origin1.clone(),
1213 collection_id,1442 account(1),
1214 21443 1,
1444 1,
1445 1
1446 ));
1215 ));1447 assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 1);
12161448
1217 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 ));
1454
1455 assert_noop!(
1456 TemplateModule::transfer_from(origin1, account(1), account(3), 1, 1, 1),
1219 Error::<Test>::AddresNotInWhiteList1457 Error::<Test>::AddresNotInWhiteList
1220 );1458 );
1221 });1459 });
1222}1460}
12231461
1224// 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);
12311467
1232 let origin1 = Origin::signed(1);1468 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
12331469
1234 let data = default_nft_data();1470 let origin1 = Origin::signed(1);
1235 create_test_item(collection_id, &data.into());
12361471
1237 assert_ok!(TemplateModule::set_public_access_mode(1472 let data = default_nft_data();
1473 create_test_item(collection_id, &data.into());
1474
1475 assert_ok!(TemplateModule::set_public_access_mode(
1238 origin1.clone(),1476 origin1.clone(),
1239 collection_id,1477 collection_id,
1240 AccessMode::WhiteList1478 AccessMode::WhiteList
1241 ));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>::AddresNotInWhiteList
1245 );1483 );
1246 });1484 });
1247}1485}
12481486
1249// 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);
12561492
1257 let origin1 = Origin::signed(1);1493 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
12581494
1259 let data = default_nft_data();1495 let origin1 = Origin::signed(1);
1260 create_test_item(collection_id, &data.into());
12611496
1262 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::WhiteList
1266 ));
12671499
1500 assert_ok!(TemplateModule::set_public_access_mode(
1501 origin1.clone(),
1502 collection_id,
1503 AccessMode::WhiteList
1504 ));
1505
1268 // do approve1506 // do approve
1269 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>::AddresNotInWhiteList
1272 );1510 );
1273 });1511 });
1274}1512}
12751513
1276// 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) and
1277// 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);
12841520
1285 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);
12891522
1290 assert_ok!(TemplateModule::set_public_access_mode(1523 let data = default_nft_data();
1291 origin1.clone(),
1292 collection_id,
1293 AccessMode::WhiteList
1294 ));
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));
12971525
1298 assert_ok!(TemplateModule::transfer(origin1.clone(), 2, 1, 1, 1));1526 let origin1 = Origin::signed(1);
1527
1528 assert_ok!(TemplateModule::set_public_access_mode(
1529 origin1.clone(),
1530 collection_id,
1531 AccessMode::WhiteList
1532 ));
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 ));
1543
1544 assert_ok!(TemplateModule::transfer(origin1, account(2), 1, 1, 1));
1299 });1545 });
1300}1546}
13011547
1302#[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);
13081552
1309 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);
13131554
1314 assert_ok!(TemplateModule::set_public_access_mode(1555 let data = default_nft_data();
1315 origin1.clone(),
1316 collection_id,
1317 AccessMode::WhiteList
1318 ));
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));
13211557
1322 // 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);
13251559
1560 assert_ok!(TemplateModule::set_public_access_mode(
1561 origin1.clone(),
1562 collection_id,
1563 AccessMode::WhiteList
1564 ));
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 ));
1575
1326 assert_ok!(TemplateModule::transfer_from(1576 // do approve
1577 assert_ok!(TemplateModule::approve(
1327 origin1.clone(),1578 origin1.clone(),
1579 account(1),
1580 1,
1581 1,
1582 5
1583 ));
1328 1,1584 assert_eq!(TemplateModule::approved(1, (1, 1, 1)), 5);
1585
1586 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 1
1333 ));1593 ));
1334 });1594 });
1335}1595}
13361596
1337// 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);
13451602
1346 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::WhiteList
1350 ));
1351 assert_ok!(TemplateModule::set_mint_permission(1604 let origin1 = Origin::signed(1);
1352 origin1.clone(),
1353 collection_id,
1354 false
1355 ));
13561605
1606 assert_ok!(TemplateModule::set_public_access_mode(
1607 origin1.clone(),
1608 collection_id,
1609 AccessMode::WhiteList
1610 ));
1611 assert_ok!(TemplateModule::set_mint_permission(
1612 origin1,
1613 collection_id,
1614 false
1615 ));
1616
1357 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}
13611621
1362// 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);
13691627
1370 let origin1 = Origin::signed(1);1628 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
1371 let origin2 = Origin::signed(2);
13721629
1373 assert_ok!(TemplateModule::set_public_access_mode(1630 let origin1 = Origin::signed(1);
1374 origin1.clone(),
1375 collection_id,
1376 AccessMode::WhiteList
1377 ));
1378 assert_ok!(TemplateModule::set_mint_permission(1631 let origin2 = Origin::signed(2);
1379 origin1.clone(),
1380 collection_id,
1381 false
1382 ));
13831632
1384 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::WhiteList
1637 ));
1638 assert_ok!(TemplateModule::set_mint_permission(
1639 origin1.clone(),
1640 collection_id,
1641 false
1642 ));
13851643
1386 assert_ok!(TemplateModule::create_item(1644 assert_ok!(TemplateModule::add_collection_admin(
1645 origin1,
1646 collection_id,
1647 account(2)
1648 ));
1649
1650 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}
13941658
1395// 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);
14021664
1403 let origin1 = Origin::signed(1);1665 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
1404 let origin2 = Origin::signed(2);
14051666
1406 assert_ok!(TemplateModule::set_public_access_mode(1667 let origin1 = Origin::signed(1);
1407 origin1.clone(),
1408 collection_id,
1409 AccessMode::WhiteList
1410 ));
1411 assert_ok!(TemplateModule::set_mint_permission(
1412 origin1.clone(),
1413 collection_id,
1414 false
1415 ));
1416 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1668 let origin2 = Origin::signed(2);
14171669
1418 assert_noop!(1670 assert_ok!(TemplateModule::set_public_access_mode(
1671 origin1.clone(),
1672 collection_id,
1673 AccessMode::WhiteList
1674 ));
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 false
1679 ));
1680 assert_ok!(TemplateModule::add_to_white_list(
1681 origin1,
1682 collection_id,
1683 account(2)
1684 ));
1685
1686 assert_noop!(
1687 TemplateModule::create_item(origin2, 1, account(2), default_nft_data().into()),
1420 Error::<Test>::PublicMintingNotAllowed1688 Error::<Test>::PublicMintingNotAllowed
1421 );1689 );
1422 });1690 });
1423}1691}
14241692
1425// 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);
14321698
1433 let origin1 = Origin::signed(1);1699 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
1434 let origin2 = Origin::signed(2);
14351700
1436 assert_ok!(TemplateModule::set_public_access_mode(1701 let origin1 = Origin::signed(1);
1437 origin1.clone(),
1438 collection_id,
1439 AccessMode::WhiteList
1440 ));
1441 assert_ok!(TemplateModule::set_mint_permission(1702 let origin2 = Origin::signed(2);
1442 origin1.clone(),
1443 collection_id,
1444 false
1445 ));
14461703
1447 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::WhiteList
1708 ));
1709 assert_ok!(TemplateModule::set_mint_permission(
1710 origin1,
1711 collection_id,
1712 false
1713 ));
1714
1715 assert_noop!(
1716 TemplateModule::create_item(origin2, 1, account(2), default_nft_data().into()),
1449 Error::<Test>::PublicMintingNotAllowed1717 Error::<Test>::PublicMintingNotAllowed
1450 );1718 );
1451 });1719 });
1452}1720}
14531721
1454// 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);
14611727
1462 let origin1 = Origin::signed(1);1728 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
14631729
1464 assert_ok!(TemplateModule::set_public_access_mode(1730 let origin1 = Origin::signed(1);
1465 origin1.clone(),
1466 collection_id,
1467 AccessMode::WhiteList
1468 ));
1469 assert_ok!(TemplateModule::set_mint_permission(
1470 origin1.clone(),
1471 collection_id,
1472 true
1473 ));
14741731
1732 assert_ok!(TemplateModule::set_public_access_mode(
1733 origin1.clone(),
1734 collection_id,
1735 AccessMode::WhiteList
1736 ));
1737 assert_ok!(TemplateModule::set_mint_permission(
1738 origin1,
1739 collection_id,
1740 true
1741 ));
1742
1475 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}
14791747
1480// 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);
14871753
1488 let origin1 = Origin::signed(1);1754 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
1489 let origin2 = Origin::signed(2);
14901755
1491 assert_ok!(TemplateModule::set_public_access_mode(1756 let origin1 = Origin::signed(1);
1492 origin1.clone(),
1493 collection_id,
1494 AccessMode::WhiteList
1495 ));
1496 assert_ok!(TemplateModule::set_mint_permission(1757 let origin2 = Origin::signed(2);
1497 origin1.clone(),
1498 collection_id,
1499 true
1500 ));
15011758
1502 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::WhiteList
1763 ));
1764 assert_ok!(TemplateModule::set_mint_permission(
1765 origin1.clone(),
1766 collection_id,
1767 true
1768 ));
15031769
1504 assert_ok!(TemplateModule::create_item(1770 assert_ok!(TemplateModule::add_collection_admin(
1771 origin1,
1772 collection_id,
1773 account(2)
1774 ));
1775
1776 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}
15121784
1513// 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);
15201790
1521 let origin1 = Origin::signed(1);1791 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
1522 let origin2 = Origin::signed(2);
15231792
1524 assert_ok!(TemplateModule::set_public_access_mode(1793 let origin1 = Origin::signed(1);
1525 origin1.clone(),
1526 collection_id,
1527 AccessMode::WhiteList
1528 ));
1529 assert_ok!(TemplateModule::set_mint_permission(1794 let origin2 = Origin::signed(2);
1530 origin1.clone(),
1531 collection_id,
1532 true
1533 ));
15341795
1535 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::WhiteList
1800 ));
1801 assert_ok!(TemplateModule::set_mint_permission(
1802 origin1,
1803 collection_id,
1804 true
1805 ));
1806
1807 assert_noop!(
1808 TemplateModule::create_item(origin2, 1, account(2), default_nft_data().into()),
1537 Error::<Test>::AddresNotInWhiteList1809 Error::<Test>::AddresNotInWhiteList
1538 );1810 );
1539 });1811 });
1540}1812}
15411813
1542// 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);
15491819
1550 let origin1 = Origin::signed(1);1820 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
1551 let origin2 = Origin::signed(2);
15521821
1553 assert_ok!(TemplateModule::set_public_access_mode(1822 let origin1 = Origin::signed(1);
1554 origin1.clone(),
1555 collection_id,
1556 AccessMode::WhiteList
1557 ));
1558 assert_ok!(TemplateModule::set_mint_permission(
1559 origin1.clone(),
1560 collection_id,
1561 true
1562 ));
1563 assert_ok!(TemplateModule::add_to_white_list(origin1.clone(), collection_id, 2));1823 let origin2 = Origin::signed(2);
15641824
1565 assert_ok!(TemplateModule::create_item(1825 assert_ok!(TemplateModule::set_public_access_mode(
1566 origin2.clone(),1826 origin1.clone(),
1827 collection_id,
1828 AccessMode::WhiteList
1829 ));
1830 assert_ok!(TemplateModule::set_mint_permission(
1831 origin1.clone(),
1832 collection_id,
1833 true
1834 ));
1835 assert_ok!(TemplateModule::add_to_white_list(
1836 origin1,
1837 collection_id,
1838 account(2)
1839 ));
1840
1841 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}
15731849
1574// Total number of collections. Positive test1850// Total number of collections. Positive test
1575#[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 1855
1580 create_test_collection(&CollectionMode::NFT, 1);1856 create_test_collection(&CollectionMode::NFT, 1);
1581 });1857 });
1582}1858}
15831859
1584// Total number of collections. Negotive test1860// Total number of collections. Negotive test
1585#[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();
15891865
1590 let origin1 = Origin::signed(1);1866 let origin1 = Origin::signed(1);
15911867
1592 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 }
15951871
1596 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();
15991875
1600 // 11-th collection in chain. Expects error1876 // 11-th collection in chain. Expects error
1601 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::NFT
1607 ), Error::<Test>::TotalCollectionsLimitExceeded);1884 ),
1885 Error::<Test>::TotalCollectionsLimitExceeded
1886 );
1608 });1887 });
1609}1888}
16101889
1611// Owned tokens by a single address. Positive test1890// Owned tokens by a single address. Positive test
1612#[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);
16181895
1619 let data = default_nft_data();1896 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
1897
1898 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}
16241903
1625// Owned tokens by a single address. Negotive test1904// Owned tokens by a single address. Negotive test
1626#[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 ));
16431923
1644 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());
16471925
1648 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());
1929
1930 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>::AddressOwnershipLimitExceeded
1933 );
1654 });1934 });
1655}1935}
16561936
1657// Number of collection admins. Positive test1937// Number of collection admins. Positive test
1658#[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 ));
16751956
1676 let origin1 = Origin::signed(1);1957 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
1677 1958
1959 let origin1 = Origin::signed(1);
1960
1678 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}
16821973
1683// Number of collection admins. Negotive test1974// Number of collection admins. Negotive test
1684#[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 ));
17011993
1702 let origin1 = Origin::signed(1);1994 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
17031995
1704 assert_ok!(TemplateModule::add_collection_admin(origin1.clone(), collection_id, 2));1996 let origin1 = Origin::signed(1);
1997
1998 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>::CollectionAdminsLimitExceeded
2006 );
1706 });2007 });
1707}2008}
17082009
1709// 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 ));
17272029
1728 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 });
17332031
1734 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 });
2037
2038 assert_noop!(
1736 collection_id,2039 TemplateModule::create_item(origin1, collection_id, account(1), too_big_const_data),
1737 1,
1738 too_big_const_data
1739 ), Error::<Test>::TokenConstDataLimitExceeded);2040 Error::<Test>::TokenConstDataLimitExceeded
2041 );
1740 });2042 });
1741}2043}
17422044
1743// 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 ));
17592064
1760 let collection_id = create_test_collection(&CollectionMode::NFT, 1);2065 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
17612066
1762 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 });
17672072
1768 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_data
1773 ), Error::<Test>::TokenVariableDataLimitExceeded);2075 Error::<Test>::TokenVariableDataLimitExceeded
2076 );
1774 });2077 });
1775}2078}
17762079
1777// 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 ));
17932099
1794 let collection_id = create_test_collection(&CollectionMode::NFT, 1);2100 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
17952101
1796 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 });
18012107
1802 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_data
1807 ), Error::<Test>::TokenConstDataLimitExceeded);2110 Error::<Test>::TokenConstDataLimitExceeded
2111 );
1808 });2112 });
1809}2113}
18102114
1811// 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 ));
18272134
1828 let collection_id = create_test_collection(&CollectionMode::NFT, 1);2135 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
18292136
1830 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 });
18352142
1836 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_data
1841 ), Error::<Test>::TokenVariableDataLimitExceeded);2145 Error::<Test>::TokenVariableDataLimitExceeded
2146 );
1842 });2147 });
1843}2148}
1844// #endregion2149// #endregion
18452150
1846#[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();
18502155
1851 let collection_id = create_test_collection(&CollectionMode::NFT, 1);2156 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
18522157
1853 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 ));
18552164
1856 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}
18602179
1861#[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);
18672184
1868 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()));
18702186
1871 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 ));
2193
2194 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}
18752208
1876#[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();
18802213
1881 let collection_id = create_test_collection(&CollectionMode::NFT, 1);2214 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
18822215
1883 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()));
18902217
1891 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());
2220
2221 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 ));
2228
2229 assert_eq!(
2230 TemplateModule::nft_item_id(collection_id, 1)
2231 .unwrap()
2232 .variable_data,
2233 variable_data
2234 );
1892 });2235 });
1893}2236}
18942237
1895#[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();
18992242
1900 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);2243 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
19012244
1902 let origin1 = Origin::signed(1);2245 let origin1 = Origin::signed(1);
19032246
1904 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());
19062249
1907 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 ));
19092257
1910 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_data
2263 );
1911 });2264 });
1912}2265}
19132266
1914
1915#[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();
19192271
1920 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);2272 let collection_id = create_test_collection(&CollectionMode::Fungible(3), 1);
19212273
1922 let origin1 = Origin::signed(1);2274 let origin1 = Origin::signed(1);
19232275
1924 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());
19262278
1927 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>::CantStoreMetadataInFungibleTokens
2283 );
1929 });2284 });
1930}2285}
19312286
1932#[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 ));
19472305
1948 let collection_id = create_test_collection(&CollectionMode::NFT, 1);2306 let collection_id = create_test_collection(&CollectionMode::NFT, 1);
19492307
1950 let origin1 = Origin::signed(1);2308 let origin1 = Origin::signed(1);
19512309
1952 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());
19542312
1955 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>::TokenVariableDataLimitExceeded
2317 );
1957 });2318 });
1958}2319}
19592320
1960#[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 ));
19762339
1977 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);2340 let collection_id = create_test_collection(&CollectionMode::ReFungible, 1);
19782341
1979 let origin1 = Origin::signed(1);2342 let origin1 = Origin::signed(1);
19802343
1981 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());
19832346
1984 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>::TokenVariableDataLimitExceeded
2351 );
1986 });2352 });
1987}2353}
19882354
modifiedpallets/scheduler/Cargo.tomldiffbeforeafterboth
12[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' }
2121
22up-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 }
2424
25[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' }
2828
29[features]29[features]
30default = ["std"]30default = ["std"]
modifiedpallets/scheduler/src/benchmarking.rsdiffbeforeafterboth

no syntactic changes

modifiedpallets/scheduler/src/lib.rsdiffbeforeafterboth
5050
51// 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)]
5354
54mod benchmarking;55mod benchmarking;
55pub mod weights;56pub mod weights;
5657
57use 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{
78
402 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,
455463
456 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 agenda
460 .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 });
471484
472 true485 true
473 } 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 agenda
484 .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 }
496514
497 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, so
503 // 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 };
506524
507 if when <= now {525 if when <= now {
508 return Err(Error::<T>::TargetBlockNumberInPast.into())526 return Err(Error::<T>::TargetBlockNumberInPast.into());
509 }527 }
510528
511 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 }
573595
605 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {627 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
606 // ensure id it is unique628 // ensure id it is unique
607 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 }
610632
611 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}
751790
752#[cfg(test)]791#[cfg(test)]
792#[allow(clippy::from_over_into)]
753mod tests {793mod tests {
754 use super::*;794 use super::*;
755795
887 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 }
891931
892 pub fn new_test_ext() -> sp_io::TestExternalities {932 pub fn new_test_ext() -> sp_io::TestExternalities {
1523 );
1524 }1759 }
15251760
1526 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 }
modifiedpallets/scheduler/src/weights.rsdiffbeforeafterboth
4039
41use 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;
4345
54pub 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_u64
58 .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_u64
65 .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_u64
72 .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_u64
79 .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}
8682
87// For backwards compatibility and tests83// For backwards compatibility and tests
88impl 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_u64
91 .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_u64
98 .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_u64
105 .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_u64
112 .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
modifiedprimitives/nft/Cargo.tomldiffbeforeafterboth
11[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' }
1919
20[features]20[features]
21default = ["std"]21default = ["std"]
modifiedprimitives/nft/src/lib.rsdiffbeforeafterboth
32
4pub use serde::{Serialize, Deserialize};3pub use serde::{Serialize, Deserialize};
54
6use 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}
5047
51impl 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 restrictions
150 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 sponsored
183 /// Some(v) - setVariableMetadata is sponsored 177 /// Some(v) - setVariableMetadata is sponsored
184 /// if there is v block between txs178 /// if there is v block between txs
185 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}
256249
257impl 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}
268259
modifiedruntime/Cargo.tomldiffbeforeafterboth
95default-features = false95default-features = false
96git = 'https://github.com/paritytech/substrate.git'96git = 'https://github.com/paritytech/substrate.git'
97optional = true97optional = true
98branch = 'polkadot-v0.9.3'98branch = 'polkadot-v0.9.7'
99version = '3.0.0'99version = '3.0.0'
100100
101[dependencies.frame-executive]101[dependencies.frame-executive]
102default-features = false102default-features = false
103git = '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'
106106
107[dependencies.frame-support]107[dependencies.frame-support]
108default-features = false108default-features = false
109git = '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'
112112
113[dependencies.frame-system]113[dependencies.frame-system]
114default-features = false114default-features = false
115git = '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'
118118
119[dependencies.frame-system-benchmarking]119[dependencies.frame-system-benchmarking]
120default-features = false120default-features = false
121git = 'https://github.com/paritytech/substrate.git'121git = 'https://github.com/paritytech/substrate.git'
122optional = true122optional = true
123branch = 'polkadot-v0.9.3'123branch = 'polkadot-v0.9.7'
124version = '3.0.0'124version = '3.0.0'
125125
126[dependencies.frame-system-rpc-runtime-api]126[dependencies.frame-system-rpc-runtime-api]
127default-features = false127default-features = false
128git = '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'
131131
132[dependencies.hex-literal]132[dependencies.hex-literal]
142[dependencies.pallet-aura]142[dependencies.pallet-aura]
143default-features = false143default-features = false
144git = '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'
147147
148[dependencies.pallet-balances]148[dependencies.pallet-balances]
149default-features = false149default-features = false
150git = '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'
153153
154# Contracts specific packages154# Contracts specific packages
155[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 = false
158branch = 'polkadot-v0.9.3'158branch = 'polkadot-v0.9.7'
159version = '3.0.0'159version = '3.0.0'
160160
161[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 = false
164branch = 'polkadot-v0.9.3'164branch = 'polkadot-v0.9.7'
165version = '3.0.0'165version = '3.0.0'
166166
167[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 = false
170branch = 'polkadot-v0.9.3'170branch = 'polkadot-v0.9.7'
171version = '3.0.0'171version = '3.0.0'
172172
173[dependencies.pallet-randomness-collective-flip]173[dependencies.pallet-randomness-collective-flip]
174default-features = false174default-features = false
175git = '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'
178178
179[dependencies.pallet-sudo]179[dependencies.pallet-sudo]
180default-features = false180default-features = false
181git = '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'
184184
185[dependencies.pallet-timestamp]185[dependencies.pallet-timestamp]
186default-features = false186default-features = false
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'
190190
191[dependencies.pallet-transaction-payment]191[dependencies.pallet-transaction-payment]
192default-features = false192default-features = false
193git = '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'
196196
197[dependencies.pallet-transaction-payment-rpc-runtime-api]197[dependencies.pallet-transaction-payment-rpc-runtime-api]
198default-features = false198default-features = false
199git = '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'
202202
203[dependencies.pallet-treasury]203[dependencies.pallet-treasury]
204default-features = false204default-features = false
205git = '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'
208208
209[dependencies.pallet-vesting]209[dependencies.pallet-vesting]
210default-features = false210default-features = false
211git = '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'
214214
215[dependencies.sp-arithmetic]215[dependencies.sp-arithmetic]
216default-features = false216default-features = false
217git = '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'
220220
221[dependencies.sp-api]221[dependencies.sp-api]
222default-features = false222default-features = false
223git = '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'
226226
227[dependencies.sp-block-builder]227[dependencies.sp-block-builder]
228default-features = false228default-features = false
229git = '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'
232232
233[dependencies.sp-core]233[dependencies.sp-core]
234default-features = false234default-features = false
235git = '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'
238238
239[dependencies.sp-consensus-aura]239[dependencies.sp-consensus-aura]
240default-features = false240default-features = false
241git = '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'
244244
245[dependencies.sp-inherents]245[dependencies.sp-inherents]
246default-features = false246default-features = false
247git = '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'
250250
251[dependencies.sp-io]251[dependencies.sp-io]
252default-features = false252default-features = false
253git = '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'
256256
257[dependencies.sp-offchain]257[dependencies.sp-offchain]
258default-features = false258default-features = false
259git = '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'
262262
263[dependencies.sp-runtime]263[dependencies.sp-runtime]
264default-features = false264default-features = false
265git = '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'
268268
269[dependencies.sp-session]269[dependencies.sp-session]
270default-features = false270default-features = false
271git = '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'
274274
275[dependencies.sp-std]275[dependencies.sp-std]
276default-features = false276default-features = false
277git = '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'
280280
281[dependencies.sp-transaction-pool]281[dependencies.sp-transaction-pool]
282default-features = false282default-features = false
283git = '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'
286286
287[dependencies.sp-version]287[dependencies.sp-version]
288default-features = false288default-features = false
289git = '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'
292292
293[dependencies.smallvec]293[dependencies.smallvec]
299[dependencies.parachain-info]299[dependencies.parachain-info]
300default-features = false300default-features = false
301git = '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'
304304
305[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 = false
309309
310[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 = false
314314
315[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 = false
319319
320[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 = false
324324
325[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 = false
329329
330[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 = false
334334
335[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 = false
339
340[dependencies.cumulus-primitives-timestamp]
341git = 'https://github.com/paritytech/cumulus.git'
342branch = 'polkadot-v0.9.7'
343default-features = false
339344
340################################################################################345################################################################################
341# Polkadot dependencies346# Polkadot dependencies
342347
343[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 = false
347352
348[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 = false
352357
353[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 = false
357362
358[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 = false
362367
363[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 = false
367372
368373
379pallet-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' }
381386
382pallet-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" }
385390
386################################################################################391################################################################################
modifiedruntime/build.rsdiffbeforeafterboth

no syntactic changes

modifiedruntime/src/chain_extension.rsdiffbeforeafterboth
108108
109 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 Item
114 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()))?;
117117
118 let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;118 let collection = pallet_nft::Module::<C>::get_collection(input.collection_id)?;
119119
126126
127 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 items
132 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 ))?;
139137
148146
149 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 // Approve
154 let mut env = env.buf_in_buf_out();152 let mut env = env.buf_in_buf_out();
167165
168 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 from
173 let mut env = env.buf_in_buf_out();171 let mut env = env.buf_in_buf_out();
187185
188 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 metadata
193 let mut env = env.buf_in_buf_out();191 let mut env = env.buf_in_buf_out();
205203
206 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 whitelist
211 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}
modifiedruntime/src/lib.rsdiffbeforeafterboth
8#![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 where
274 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}
290
291impl pallet_randomness_collective_flip::Config for Runtime {}
294292
295impl 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.
360358
361impl 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.
439439
440impl<T> WeightToFeePolynomial for LinearFee<T> where440impl<T> WeightToFeePolynomial for LinearFee<T>
441where
441 T: BaseArithmetic + From<u32> + Copy + Unsigned442 T: BaseArithmetic + From<u32> + Copy + Unsigned,
442{443{
443 type Balance = T;444 type Balance = T;
444445
689 type Event = Event;690 type Event = Event;
690 type WeightInfo = nft_weights::WeightInfo;691 type WeightInfo = nft_weights::WeightInfo;
691692
692 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 }
986993
1008 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 }
10141021
1151 }1158 }
1152}1159}
1160
1161struct CheckInherents;
1162
1163impl 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_proof
1169 .read_slot()
1170 .expect("Could not read the relay chain slot from the proof");
1171
1172 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");
1179
1180 inherent_data.check_extrinsics(&block)
1181 }
1182}
11531183
1154cumulus_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);
11581189
modifiedruntime/src/nft_weights.rsdiffbeforeafterboth
8pub 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_u64
12 .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_u64
17 .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_u64
22 .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_u64
27 .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_u64
32 .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_u64
37 .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_u64
42 .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_u64
47 .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_u64
52 .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_u64
57 .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_u64
62 .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_u64
67 .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_u64
72 .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 storage
73 .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_u64
78 .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_u64
83 .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_u64
88 .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_u64
93 .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_u64
98 .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_u64
103 .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_u64
108 .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_u64
113 .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_u64
118 .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_u64
123 .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_u64
128 .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_u64
133 .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_u64
138 .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_u64
143 .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_u64
148 .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_u64
153 .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_u64
158 .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}
162162
modifiedruntime_types.jsondiffbeforeafterboth
11 "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": {
addedtests/.eslintrc.jsondiffbeforeafterboth

no changes

modifiedtests/package.jsondiffbeforeafterboth
14 "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",
modifiedtests/src/addToContractWhiteList.test.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import 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';
1616
17chai.use(chaiAsPromised);17chai.use(chaiAsPromised);
18const expect = chai.expect;18const expect = chai.expect;
1919
20describe('Integration Test addToContractWhiteList', () => {20describe('Integration Test addToContractWhiteList', () => {
2121
22 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);
2626
27 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 });
3737
38 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);
4242
43 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();
5858
59describe('Negative Integration Test addToContractWhiteList', () => {59describe('Negative Integration Test addToContractWhiteList', () => {
6060
61 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');
6666
67 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 });
7676
77 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);
8181
82 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);
modifiedtests/src/addToWhiteList.test.tsdiffbeforeafterboth
27describe('Integration Test ext. addToWhiteList()', () => { 27describe('Integration Test ext. addToWhiteList()', () => {
28 28
29 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 });
modifiedtests/src/approve.test.tsdiffbeforeafterboth
82 let Charlie: IKeyringPair;82 let Charlie: IKeyringPair;
8383
84 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');
modifiedtests/src/block-production.test.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import 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';
99
10const BlockTimeMs = 12000;10const BlockTimeMs = 12000;
11const ToleranceMs = 1000;11const ToleranceMs = 1000;
1212
13/* 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 });
modifiedtests/src/burnItem.test.tsdiffbeforeafterboth
4//4//
55
6import { 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";
1716
18import chai from 'chai';17import chai from 'chai';
19import chaiAsPromised from 'chai-as-promised';18import chaiAsPromised from 'chai-as-promised';
2524
26describe('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 });
3433
139138
140describe('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 });
148147
modifiedtests/src/change-collection-owner.test.tsdiffbeforeafterboth
6import 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';
1111
12chai.use(chaiAsPromised);12chai.use(chaiAsPromised);
13const expect = chai.expect;13const expect = chai.expect;
32});32});
3333
34describe('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');
modifiedtests/src/check-event/createItemEvent.test.tsdiffbeforeafterboth
10import 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';
1414
15chai.use(chaiAsPromised);15chai.use(chaiAsPromised);
16const expect = chai.expect;16const expect = chai.expect;
modifiedtests/src/check-event/createMultipleItemsEvent.test.tsdiffbeforeafterboth
10import 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';
1414
15chai.use(chaiAsPromised);15chai.use(chaiAsPromised);
16const expect = chai.expect;16const expect = chai.expect;
modifiedtests/src/collision-tests/admVsOwnerChanges.test.tsdiffbeforeafterboth
1import { 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 10
15chai.use(chaiAsPromised); 11chai.use(chaiAsPromised);
modifiedtests/src/collision-tests/admVsOwnerData.test.tsdiffbeforeafterboth
1import { 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 10
15chai.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; 15
20
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 22
modifiedtests/src/collision-tests/admVsOwnerTake.test.tsdiffbeforeafterboth
1import { 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 10
15chai.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-expression
50 expect(itemBurn).to.be.null; 45 expect(itemBurn).to.be.null;
modifiedtests/src/collision-tests/adminDestroyCollection.test.tsdiffbeforeafterboth
1import { 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';
109
11chai.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;
2415
25before(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});
3523
51 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-expression
57 expect(whiteList).to.be.false;44 expect(whiteList).to.be.false;
modifiedtests/src/collision-tests/adminLimitsOff.test.tsdiffbeforeafterboth
1010
11chai.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);
5247
53 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([
modifiedtests/src/collision-tests/adminRightsOff.test.tsdiffbeforeafterboth
3import 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';
1010
11chai.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;
2415
25before(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});
3522
42 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);
modifiedtests/src/collision-tests/setSponsorNewOwner.test.tsdiffbeforeafterboth
1import { 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';
109
11chai.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([
modifiedtests/src/collision-tests/sponsorPayments.test.tsdiffbeforeafterboth
5import 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; 19
21
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 26
38 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 // 38
42 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);
modifiedtests/src/collision-tests/tokenLimitsOff.test.tsdiffbeforeafterboth
1313
14chai.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 //61
67 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.nft
69 .createMultipleItems(collectionId, Ferdie.address, args);64 .createMultipleItems(collectionId, Ferdie.address, args);
modifiedtests/src/collision-tests/turnsOffMinting.test.tsdiffbeforeafterboth
2import 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 16
19before(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 // 32
36 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-expression
46 expect(itemList).to.be.null; 42 expect(itemList).to.be.null;
modifiedtests/src/config.tsdiffbeforeafterboth
6import process from 'process';6import process from 'process';
77
8const 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};
1111
12export default config;12export default config;
modifiedtests/src/config_docker.tsdiffbeforeafterboth
77
8const 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};
1111
12export default config;12export default config;
modifiedtests/src/confirmSponsorship.test.tsdiffbeforeafterboth
55
6import 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';
2826
29chai.use(chaiAsPromised);27chai.use(chaiAsPromised);
36describe('integration test: ext. confirmSponsorship():', () => {34describe('integration test: ext. confirmSponsorship():', () => {
3735
38 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 });
4644
163 await addToWhiteListExpectSuccess(alice, collectionId, zeroBalance.address);161 await addToWhiteListExpectSuccess(alice, collectionId, zeroBalance.address);
164162
165 // Mint token using unused address as signer163 // Mint token using unused address as signer
166 const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT', zeroBalance.address);164 await createItemExpectSuccess(zeroBalance, collectionId, 'NFT', zeroBalance.address);
167165
168 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());
169167
195 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());
200198
201 // Try again after Zero gets some balance - now it should succeed199 // Try again after Zero gets some balance - now it should succeed
229227
230 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());
231
232 const badTransaction = async function () {
233 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);229 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
234 };
235
236 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());
237231
271 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());
276270
277 // Try again after Zero gets some balance - now it should succeed271 // Try again after Zero gets some balance - now it should succeed
317 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());
335329
336describe('(!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 });
345339
346 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 existed
348 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 });
352346
353 await confirmSponsorshipExpectFailure(collectionId, '//Bob');347 await confirmSponsorshipExpectFailure(collectionId, '//Bob');
modifiedtests/src/connection.test.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import 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;
3535
modifiedtests/src/contracts.test.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import 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';
1717
18import {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';
3030
3131
32chai.use(chaiAsPromised);32chai.use(chaiAsPromised);
37const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';37const marketContractAddress = '5CYN9j3YvRkqxewoxeSvRbhAym4465C57uMmX5j4yz99L5H6';
3838
39describe('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);
4444
45 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);
4848
65describe.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');
7070
71 // Prep work71 // Prep work
72 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);
7777
96 const bob = privateKey('//Bob');96 const bob = privateKey('//Bob');
9797
98 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');
125125
126 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');
170170
171 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());
174174
175 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');
189189
190 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);
194194
197 const result = getGenericResult(events);197 const result = getGenericResult(events);
198 expect(result.success).to.be.true;198 expect(result.success).to.be.true;
199199
200 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');
208208
209 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());
212212
213 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;
217217
218 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');
227227
228 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);
232232
modifiedtests/src/createItem.test.tsdiffbeforeafterboth
4// 4//
5 5
6import { 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 13
14let alice: IKeyringPair; 14let alice: IKeyringPair;
15 15
16describe('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 23
modifiedtests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth
55
6import 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';
1919
20import { 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;
2525
26const 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;
3333
34// 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 happens
36/*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());
5253
53describe('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 });
modifiedtests/src/destroyCollection.test.tsdiffbeforeafterboth
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 { 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';
1212
13chai.use(chaiAsPromised);13chai.use(chaiAsPromised);
1414
31 let alice: IKeyringPair;31 let alice: IKeyringPair;
3232
33 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 });
modifiedtests/src/enableContractSponsoring.test.tsdiffbeforeafterboth
8181
82 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);
8585
86 await enableContractSponsoringExpectFailure(alice, flipper.address, true);86 await enableContractSponsoringExpectFailure(alice, flipper.address, true);
87 });87 });
modifiedtests/src/eth/fungible.test.tsdiffbeforeafterboth
1//
2// This file is subject to the terms and conditions defined in
3// file 'LICENSE', which is part of this source code package.
4//
5
1import 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';
611
7describe('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 }
175180
176 {181 {
modifiedtests/src/eth/metadata.test.tsdiffbeforeafterboth
1//
2// This file is subject to the terms and conditions defined in
3// file 'LICENSE', which is part of this source code package.
4//
5
1import { 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';
611
7describe('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 });
5055
51 expect(+decimals).to.equal(6);56 expect(+decimals).to.equal(6);
52 })57 });
53})58});
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
1//
2// This file is subject to the terms and conditions defined in
3// file 'LICENSE', which is part of this source code package.
4//
5
1import 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';
611
7describe('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 }
175180
176 {181 {
modifiedtests/src/eth/util/helpers.tsdiffbeforeafterboth
1//
2// This file is subject to the terms and conditions defined in
3// file 'LICENSE', which is part of this source code package.
4//
5
1import { 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';
813
9let 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;
1318
14 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);
1621
17 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 });
6469
65export 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}
6974
70type NormalizedEvent = {75type NormalizedEvent = {
7580
76export 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 }
modifiedtests/src/inflation.test.tsdiffbeforeafterboth
55
6import 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';
1210
13chai.use(chaiAsPromised);11chai.use(chaiAsPromised);
14const expect = chai.expect;12const expect = chai.expect;
15
16let alice: IKeyringPair;
17let bob: IKeyringPair;
1813
19describe('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 });
26
27 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) => {
modifiedtests/src/overflow.test.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import { 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';
1212
13chai.use(chaiAsPromised);13chai.use(chaiAsPromised);
14const expect = chai.expect;14const expect = chai.expect;
modifiedtests/src/pallet-presence.test.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import { 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';
99
10function 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());
modifiedtests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth
55
6import 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';
3024
31chai.use(chaiAsPromised);25chai.use(chaiAsPromised);
32const expect = chai.expect;26const expect = chai.expect;
3327
34let alice: IKeyringPair;28let alice: IKeyringPair;
35let bob: IKeyringPair;29let bob: IKeyringPair;
36let charlie: IKeyringPair;
3730
38describe('integration test: ext. removeCollectionSponsor():', () => {31describe('integration test: ext. removeCollectionSponsor():', () => {
3932
40 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 });
4840
65 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());
7062
71 expect(BsponsorBalance.isEqualTo(AsponsorBalance)).to.be.true;63 expect(BsponsorBalance.isEqualTo(AsponsorBalance)).to.be.true;
9587
96describe('(!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 });
10596
106 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 existed
108 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 });
112103
113 await removeCollectionSponsorExpectFailure(collectionId);104 await removeCollectionSponsorExpectFailure(collectionId);
modifiedtests/src/removeFromContractWhiteList.test.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import 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';
1212
13describe('Integration Test removeFromContractWhiteList', () => {13describe('Integration Test removeFromContractWhiteList', () => {
14 let bob: IKeyringPair;14 let bob: IKeyringPair;
7373
74 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);
7777
78 await removeFromContractWhiteListExpectFailure(alice, flipper.address.toString(), bob.address);78 await removeFromContractWhiteListExpectFailure(alice, flipper.address.toString(), bob.address);
79 });79 });
modifiedtests/src/removeFromWhiteList.test.tsdiffbeforeafterboth
16 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;
3030
31 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;
6464
65 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 });
modifiedtests/src/rpc.load.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import { 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';
1614
17const value = 0;15const value = 0;
18const gasLimit = 500000n * 1000000n;16const gasLimit = 500000n * 1000000n;
19const endowment = `1000000000000000`;17const endowment = '1000000000000000';
2018
2119/*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 code
25 .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}
3533
34/*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.tx
39 .new(endowment, gasLimit)38 .new(endowment, gasLimit)
40 .signAndSend(alice, (result) => {39 .signAndSend(alice, (result) => {
5251
53 // Transfer balance to it52 // Transfer balance to it
54 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);
8281
83 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;
97
98 /* 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);
118119
119 // Fill smart contract up with data120 // Fill smart contract up with data
120 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);
123124
128 let rate = 0;129 let rate = 0;
129 const checkPoint = 10;130 const checkPoint = 10;
131
132 /* 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 }
modifiedtests/src/scheduler.test.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import { 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';
24
2517
26chai.use(chaiAsPromised);18chai.use(chaiAsPromised);
27const expect = chai.expect;
28
29const DATA = [1, 2, 3, 4];
3019
31describe('Integration Test scheduler base transaction', () => {20describe('Integration Test scheduler base transaction', () => {
32 let alice: IKeyringPair;
33
34 before(async () => {
35 await usingApi(async () => {
36 alice = privateKey('//Alice');
37 });
38 });
39
40 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 // nft
54
55});34});
56
57// describe('Negative Integration Test setOffchainSchema', () => {
58// let alice: IKeyringPair;
59// let bob: IKeyringPair;
60
61// let validCollectionId: number;
62
63// before(async () => {
64// await usingApi(async () => {
65// alice = privateKey('//Alice');
66// bob = privateKey('//Bob');
67
68// validCollectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });
69// });
70// });
71
72// it('fails on not existing collection id', async () => {
73// const nonExistingCollectionId = await usingApi(findNotExistingCollection);
74
75// await setOffchainSchemaExpectFailure(alice, nonExistingCollectionId, DATA);
76// });
77
78// it('fails on destroyed collection id', async () => {
79// const destroyedCollectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });
80// await destroyCollectionExpectSuccess(destroyedCollectionId);
81
82// await setOffchainSchemaExpectFailure(alice, destroyedCollectionId, DATA);
83// });
84
85// it('fails on too long data', async () => {
86// const tooLongData = new Array(4097).fill(0xff);
87
88// await setOffchainSchemaExpectFailure(alice, validCollectionId, tooLongData);
89// });
90
91// it('fails on execution by non-owner', async () => {
92// await setOffchainSchemaExpectFailure(bob, validCollectionId, DATA);
93// });
94// });
9535
modifiedtests/src/setCollectionLimits.test.tsdiffbeforeafterboth
73 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) => {
7575
76 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 });
207207
208 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 () => {
210210
211 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,
modifiedtests/src/setCollectionSponsor.test.tsdiffbeforeafterboth
55
6import 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';
1212
13chai.use(chaiAsPromised);13chai.use(chaiAsPromised);
14const expect = chai.expect;
1514
16let bob: IKeyringPair;15let bob: IKeyringPair;
1716
18describe('integration test: ext. setCollectionSponsor():', () => {17describe('integration test: ext. setCollectionSponsor():', () => {
1918
20 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 });
2625
46 const collectionId = await createCollectionExpectSuccess();45 const collectionId = await createCollectionExpectSuccess();
4746
48 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});
5453
55describe('(!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 });
6261
66 });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 existed
69 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 });
7372
74 await setCollectionSponsorExpectFailure(collectionId, bob.address);73 await setCollectionSponsorExpectFailure(collectionId, bob.address);
modifiedtests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth
23let largeShema: any;23let largeShema: any;
2424
25before(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');
modifiedtests/src/setContractSponsoringRateLimit.test.tsdiffbeforeafterboth
5959
60 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);
6363
64 await setContractSponsoringRateLimitExpectFailure(alice, flipper.address, 1);64 await setContractSponsoringRateLimitExpectFailure(alice, flipper.address, 1);
65 });65 });
modifiedtests/src/setPublicAccessMode.test.tsdiffbeforeafterboth
4// 4//
5 5
6// https://unique-network.readthedocs.io/en/latest/jsapi.html#setschemaversion 6// https://unique-network.readthedocs.io/en/latest/jsapi.html#setschemaversion
7import { 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'; 22
23
24chai.use(chaiAsPromised); 23chai.use(chaiAsPromised);
25const expect = chai.expect; 24const expect = chai.expect;
29 28
30describe('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 36
38 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 77
79 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);
modifiedtests/src/setSchemaVersion.test.tsdiffbeforeafterboth
103 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);
modifiedtests/src/setVariableMetaData.test.tsdiffbeforeafterboth
49});49});
5050
51describe('Negative Integration Test setVariableMetaData', () => {51describe('Negative Integration Test setVariableMetaData', () => {
52 let data = [1];52 const data = [1];
5353
54 let alice: IKeyringPair;54 let alice: IKeyringPair;
55 let bob: IKeyringPair;55 let bob: IKeyringPair;
6969
70 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 });
modifiedtests/src/setVariableOnChainSchema.test.tsdiffbeforeafterboth
23let largeSchema: any;23let largeSchema: any;
2424
25before(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');
modifiedtests/src/substrate/privateKey.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import { Keyring } from "@polkadot/api";6import { Keyring } from '@polkadot/api';
7import { IKeyringPair } from "@polkadot/types/types";7import { IKeyringPair } from '@polkadot/types/types';
88
9export 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' });
modifiedtests/src/substrate/promisify-substrate.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import { ApiPromise } from "@polkadot/api";6import { ApiPromise } from '@polkadot/api';
77
8type PromiseType<T> = T extends PromiseLike<infer TInner> ? TInner : T;8type PromiseType<T> = T extends PromiseLike<infer TInner> ? TInner : T;
99
modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import { 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';
1010
11import 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';
1515
16function 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}
2027
21export 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;
2532
26 // 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 };
3340
34 try {41 try {
7279
73export function80export function
74submitTransactionAsync(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 = () => {};
99107
108 /* 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(() => {
modifiedtests/src/substrate/wait-new-blocks.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import { ApiPromise } from "@polkadot/api";6import { ApiPromise } from '@polkadot/api';
77
8/* 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 {
modifiedtests/src/toggleContractWhiteList.test.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import 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';
1717
18chai.use(chaiAsPromised);18chai.use(chaiAsPromised);
19const expect = chai.expect;19const expect = chai.expect;
2323
24describe('Integration Test toggleContractWhiteList', () => {24describe('Integration Test toggleContractWhiteList', () => {
2525
26 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);
2929
38 });38 });
39 });39 });
4040
41 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');
4444
45 const [contract, deployer] = await deployFlipper(api);45 const [contract, deployer] = await deployFlipper(api);
4646
47 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.');
5252
53 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();
6161
62 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.');
6969
70 await deployerCanFlip();70 await deployerCanFlip();
7171
72 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.');
7979
80 await deployerCanFlip();80 await deployerCanFlip();
8181
82 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.');
8989
90 await deployerCanFlip();90 await deployerCanFlip();
9191
92 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.');
9999
100 });100 });
101 });101 });
102102
103 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);
106106
123123
124describe('Negative Integration Test toggleContractWhiteList', () => {124describe('Negative Integration Test toggleContractWhiteList', () => {
125125
126 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');
130130
131 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 });
140140
141 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);
145145
146 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);
modifiedtests/src/transfer.nload.tsdiffbeforeafterboth
1//
2// This file is subject to the terms and conditions defined in
3// file 'LICENSE', which is part of this source code package.
4//
5
1import { 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';
914
26}31}
2732
28async 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 array
31 const failedAccounts = [0];36 const failedAccounts = [0];
3237
36 increaseCounter('requests', finalUserAmount);41 increaseCounter('requests', finalUserAmount);
3742
38 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 }
5560
56 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);
8994
90 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) => {
modifiedtests/src/transfer.test.tsdiffbeforeafterboth
64 });64 });
6565
66 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 // nft
8793
88describe('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');
modifiedtests/src/transferFrom.test.tsdiffbeforeafterboth
14 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;
3231
33 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 });
4039
41 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 // nft
44 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;
93100
94 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 }); */
140147
141 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 // nft
144 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 });
161174
162 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 // nft
165 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 });
185204
186 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 // nft
190 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 // nft
228 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 // nft
259 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);
modifiedtests/src/util/contracthelpers.tsdiffbeforeafterboth
3// file 'LICENSE', which is part of this source code package.3// file 'LICENSE', which is part of this source code package.
4//4//
55
6import 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';
1313
14chai.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';
2222
23/* 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}
3637
4041
41 // Transfer balance to it42 // Transfer balance to it
42 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);
7273
73 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}
91
92function instantiateTransferContract(alice: IKeyringPair, blueprint: Blueprint) : Promise<any> {
93 return new Promise<any>(async (resolve, reject) => {
94 const unsub = await blueprint.tx
95 .default(endowment, gasLimit)
96 .signAndSend(alice, (result) => {
97 if (result.status.isInBlock || result.status.isFinalized) {
98 unsub();
99 resolve(result);
100 }
101 });
102 });
103}
10492
105export 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'));
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
4//4//
55
6import { 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';
2319
24chai.use(chaiAsPromised);20chai.use(chaiAsPromised);
25const expect = chai.expect;21const expect = chai.expect;
44 }40 }
4541
46 // AccountId42 // AccountId
47 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}
95
96interface IFungibleTokenDataType {
97 Value: BN;
98}
9991
100interface IGetMessage {92interface IGetMessage {
101 checkMsgNftMethod: string;93 checkMsgNftMethod: string;
110}102}
111103
112export 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;
147139
148export 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;
165157
166export 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};
245237
246export 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 };
248240
249 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 transaction
252 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);244 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);
357}349}
358350
359function 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}
369360
370export 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 transaction
373 const alicePrivateKey = privateKey(senderSeed);364 const alicePrivateKey = privateKey(senderSeed);
376 });367 });
377}368}
378369
379export 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 transaction
382 const alicePrivateKey = privateKey(senderSeed);373 const alicePrivateKey = privateKey(senderSeed);
471 });462 });
472}463}
473464
474export 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) => {
476467
477 // Run the transaction468 // Run the transaction
481 });472 });
482}473}
483474
484export 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) => {
486477
487 // Run the transaction478 // Run the transaction
502}493}
503494
504495
505export 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) => {
507498
508 // Run the transaction499 // Run the transaction
552 });543 });
553}544}
554545
555export 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}
564555
565export 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}
738733
734/* 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);
757
758
759 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;
761755
762 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);
765759
766 const events = await submitTransactionAsync(sender, scheduleTx);760 await submitTransactionAsync(sender, scheduleTx);
767761
768 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());
770763
771 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 blocks
775 await new Promise(resolve => setTimeout(resolve, 6000 * 2));768 await new Promise(resolve => setTimeout(resolve, 6000 * 2));
776769
777 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());
779771
780 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;
884881
885export 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}
1001996
1002export 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 });
modifiedtests/src/util/util.tsdiffbeforeafterboth
4//4//
55
6export 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}
1313
14export 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}
2222
23export 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 }