difftreelog
Merge pull request #422 from UniqueNetwork/feature/CORE-410
in: master
Feature/core 410 Properties for RFT
21 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6320,7 +6320,7 @@
[[package]]
name = "pallet-refungible"
-version = "0.1.0"
+version = "0.1.1"
dependencies = [
"frame-benchmarking",
"frame-support",
@@ -12733,7 +12733,7 @@
[[package]]
name = "up-data-structs"
-version = "0.1.0"
+version = "0.1.1"
dependencies = [
"derivative",
"frame-support",
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -966,7 +966,7 @@
),
);
<T as Config>::Currency::settle(
- &owner.as_sub(),
+ owner.as_sub(),
imbalance,
WithdrawReasons::TRANSFER,
ExistenceRequirement::KeepAlive,
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -183,7 +183,7 @@
value: property_value(),
}).collect::<Vec<_>>();
let item = create_max_item(&collection, &owner, owner.clone())?;
- }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props, false, &Unlimited)?}
+ }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), false, &Unlimited)?}
delete_token_properties {
let b in 0..MAX_PROPERTIES_PER_ITEM;
@@ -205,7 +205,7 @@
value: property_value(),
}).collect::<Vec<_>>();
let item = create_max_item(&collection, &owner, owner.clone())?;
- <Pallet<T>>::set_token_properties(&collection, &owner, item, props, false, &Unlimited)?;
+ <Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), false, &Unlimited)?;
let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
- }: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete, &Unlimited)?}
+ }: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete.into_iter(), &Unlimited)?}
}
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -3,7 +3,7 @@
//! Autogenerated weights for pallet_nonfungible
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-06-15, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! DATE: 2022-07-20, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
// Executed Command:
@@ -56,7 +56,7 @@
// Storage: Nonfungible TokenData (r:0 w:1)
// Storage: Nonfungible Owned (r:0 w:1)
fn create_item() -> Weight {
- (24_135_000 as Weight)
+ (20_328_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
@@ -65,9 +65,9 @@
// Storage: Nonfungible TokenData (r:0 w:4)
// Storage: Nonfungible Owned (r:0 w:4)
fn create_multiple_items(b: u32, ) -> Weight {
- (21_952_000 as Weight)
- // Standard Error: 5_000
- .saturating_add((4_727_000 as Weight).saturating_mul(b as Weight))
+ (10_134_000 as Weight)
+ // Standard Error: 3_000
+ .saturating_add((4_927_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(b as Weight)))
@@ -77,9 +77,9 @@
// Storage: Nonfungible TokenData (r:0 w:4)
// Storage: Nonfungible Owned (r:0 w:4)
fn create_multiple_items_ex(b: u32, ) -> Weight {
- (10_432_000 as Weight)
- // Standard Error: 6_000
- .saturating_add((7_383_000 as Weight).saturating_mul(b as Weight))
+ (5_710_000 as Weight)
+ // Standard Error: 4_000
+ .saturating_add((7_578_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
@@ -93,7 +93,7 @@
// Storage: Nonfungible Owned (r:0 w:1)
// Storage: Nonfungible TokenProperties (r:0 w:1)
fn burn_item() -> Weight {
- (29_798_000 as Weight)
+ (28_433_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(5 as Weight))
}
@@ -105,7 +105,7 @@
// Storage: Nonfungible Owned (r:0 w:1)
// Storage: Nonfungible TokenProperties (r:0 w:1)
fn burn_recursively_self_raw() -> Weight {
- (37_955_000 as Weight)
+ (34_435_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(5 as Weight))
}
@@ -119,8 +119,8 @@
// Storage: Common CollectionById (r:1 w:0)
fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 1_349_000
- .saturating_add((275_145_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 1_539_000
+ .saturating_add((304_456_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(7 as Weight))
.saturating_add(T::DbWeight::get().reads((4 as Weight).saturating_mul(b as Weight)))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
@@ -131,14 +131,14 @@
// Storage: Nonfungible Allowance (r:1 w:0)
// Storage: Nonfungible Owned (r:0 w:2)
fn transfer() -> Weight {
- (27_867_000 as Weight)
+ (24_376_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(5 as Weight))
}
// Storage: Nonfungible TokenData (r:1 w:0)
// Storage: Nonfungible Allowance (r:1 w:1)
fn approve() -> Weight {
- (18_824_000 as Weight)
+ (15_890_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
@@ -147,7 +147,7 @@
// Storage: Nonfungible AccountBalance (r:2 w:2)
// Storage: Nonfungible Owned (r:0 w:2)
fn transfer_from() -> Weight {
- (32_879_000 as Weight)
+ (28_634_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
@@ -159,7 +159,7 @@
// Storage: Nonfungible Owned (r:0 w:1)
// Storage: Nonfungible TokenProperties (r:0 w:1)
fn burn_from() -> Weight {
- (37_061_000 as Weight)
+ (32_201_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
@@ -167,28 +167,26 @@
fn set_token_property_permissions(b: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 57_000
- .saturating_add((15_149_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add((15_232_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Common CollectionPropertyPermissions (r:1 w:0)
- // Storage: Nonfungible TokenData (r:1 w:0)
// Storage: Nonfungible TokenProperties (r:1 w:1)
fn set_token_properties(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 2_278_000
- .saturating_add((409_613_000 as Weight).saturating_mul(b as Weight))
- .saturating_add(T::DbWeight::get().reads(3 as Weight))
+ // Standard Error: 1_648_000
+ .saturating_add((288_654_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Common CollectionPropertyPermissions (r:1 w:0)
- // Storage: Nonfungible TokenData (r:1 w:0)
// Storage: Nonfungible TokenProperties (r:1 w:1)
fn delete_token_properties(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 2_234_000
- .saturating_add((408_185_000 as Weight).saturating_mul(b as Weight))
- .saturating_add(T::DbWeight::get().reads(3 as Weight))
+ // Standard Error: 1_632_000
+ .saturating_add((289_190_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
}
@@ -200,7 +198,7 @@
// Storage: Nonfungible TokenData (r:0 w:1)
// Storage: Nonfungible Owned (r:0 w:1)
fn create_item() -> Weight {
- (24_135_000 as Weight)
+ (20_328_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
@@ -209,9 +207,9 @@
// Storage: Nonfungible TokenData (r:0 w:4)
// Storage: Nonfungible Owned (r:0 w:4)
fn create_multiple_items(b: u32, ) -> Weight {
- (21_952_000 as Weight)
- // Standard Error: 5_000
- .saturating_add((4_727_000 as Weight).saturating_mul(b as Weight))
+ (10_134_000 as Weight)
+ // Standard Error: 3_000
+ .saturating_add((4_927_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
.saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(b as Weight)))
@@ -221,9 +219,9 @@
// Storage: Nonfungible TokenData (r:0 w:4)
// Storage: Nonfungible Owned (r:0 w:4)
fn create_multiple_items_ex(b: u32, ) -> Weight {
- (10_432_000 as Weight)
- // Standard Error: 6_000
- .saturating_add((7_383_000 as Weight).saturating_mul(b as Weight))
+ (5_710_000 as Weight)
+ // Standard Error: 4_000
+ .saturating_add((7_578_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
@@ -237,7 +235,7 @@
// Storage: Nonfungible Owned (r:0 w:1)
// Storage: Nonfungible TokenProperties (r:0 w:1)
fn burn_item() -> Weight {
- (29_798_000 as Weight)
+ (28_433_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
@@ -249,7 +247,7 @@
// Storage: Nonfungible Owned (r:0 w:1)
// Storage: Nonfungible TokenProperties (r:0 w:1)
fn burn_recursively_self_raw() -> Weight {
- (37_955_000 as Weight)
+ (34_435_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
@@ -263,8 +261,8 @@
// Storage: Common CollectionById (r:1 w:0)
fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 1_349_000
- .saturating_add((275_145_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 1_539_000
+ .saturating_add((304_456_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(7 as Weight))
.saturating_add(RocksDbWeight::get().reads((4 as Weight).saturating_mul(b as Weight)))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
@@ -275,14 +273,14 @@
// Storage: Nonfungible Allowance (r:1 w:0)
// Storage: Nonfungible Owned (r:0 w:2)
fn transfer() -> Weight {
- (27_867_000 as Weight)
+ (24_376_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
// Storage: Nonfungible TokenData (r:1 w:0)
// Storage: Nonfungible Allowance (r:1 w:1)
fn approve() -> Weight {
- (18_824_000 as Weight)
+ (15_890_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
@@ -291,7 +289,7 @@
// Storage: Nonfungible AccountBalance (r:2 w:2)
// Storage: Nonfungible Owned (r:0 w:2)
fn transfer_from() -> Weight {
- (32_879_000 as Weight)
+ (28_634_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
}
@@ -303,7 +301,7 @@
// Storage: Nonfungible Owned (r:0 w:1)
// Storage: Nonfungible TokenProperties (r:0 w:1)
fn burn_from() -> Weight {
- (37_061_000 as Weight)
+ (32_201_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
}
@@ -311,28 +309,26 @@
fn set_token_property_permissions(b: u32, ) -> Weight {
(0 as Weight)
// Standard Error: 57_000
- .saturating_add((15_149_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add((15_232_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Common CollectionPropertyPermissions (r:1 w:0)
- // Storage: Nonfungible TokenData (r:1 w:0)
// Storage: Nonfungible TokenProperties (r:1 w:1)
fn set_token_properties(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 2_278_000
- .saturating_add((409_613_000 as Weight).saturating_mul(b as Weight))
- .saturating_add(RocksDbWeight::get().reads(3 as Weight))
+ // Standard Error: 1_648_000
+ .saturating_add((288_654_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Common CollectionPropertyPermissions (r:1 w:0)
- // Storage: Nonfungible TokenData (r:1 w:0)
// Storage: Nonfungible TokenProperties (r:1 w:1)
fn delete_token_properties(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 2_234_000
- .saturating_add((408_185_000 as Weight).saturating_mul(b as Weight))
- .saturating_add(RocksDbWeight::get().reads(3 as Weight))
+ // Standard Error: 1_632_000
+ .saturating_add((289_190_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
}
pallets/refungible/Cargo.tomldiffbeforeafterboth--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-refungible"
-version = "0.1.0"
+version = "0.1.1"
license = "GPLv3"
edition = "2021"
pallets/refungible/Changelog.mddiffbeforeafterboth--- /dev/null
+++ b/pallets/refungible/Changelog.md
@@ -0,0 +1,3 @@
+### 0.1.1
+---
+* Added support for properties for RFT collections and tokens.
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -18,9 +18,12 @@
use crate::{Pallet, Config, RefungibleHandle};
use sp_std::prelude::*;
-use pallet_common::benchmarking::{create_collection_raw, create_data};
+use pallet_common::benchmarking::{create_collection_raw, property_key, property_value, create_data};
use frame_benchmarking::{benchmarks, account};
-use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, CUSTOM_DATA_LIMIT, budget::Unlimited};
+use up_data_structs::{
+ CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, CUSTOM_DATA_LIMIT,
+ budget::Unlimited,
+};
use pallet_common::bench_init;
use core::convert::TryInto;
use core::iter::IntoIterator;
@@ -38,6 +41,7 @@
.collect::<BTreeMap<_, _>>()
.try_into()
.unwrap(),
+ properties: Default::default(),
}
}
fn create_max_item<T: Config>(
@@ -204,6 +208,68 @@
<Pallet<T>>::set_allowance(&collection, &sender, &burner, item, 200)?;
}: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item, 200, &Unlimited)?}
+ set_token_property_permissions {
+ let b in 0..MAX_PROPERTIES_PER_ITEM;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub;
+ };
+ let perms = (0..b).map(|k| PropertyKeyPermission {
+ key: property_key(k as usize),
+ permission: PropertyPermission {
+ mutable: false,
+ collection_admin: false,
+ token_owner: false,
+ },
+ }).collect::<Vec<_>>();
+ }: {<Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?}
+
+ set_token_properties {
+ let b in 0..MAX_PROPERTIES_PER_ITEM;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub;
+ };
+ let perms = (0..b).map(|k| PropertyKeyPermission {
+ key: property_key(k as usize),
+ permission: PropertyPermission {
+ mutable: false,
+ collection_admin: true,
+ token_owner: true,
+ },
+ }).collect::<Vec<_>>();
+ <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
+ let props = (0..b).map(|k| Property {
+ key: property_key(k as usize),
+ value: property_value(),
+ }).collect::<Vec<_>>();
+ let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
+ }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), false, &Unlimited)?}
+
+ delete_token_properties {
+ let b in 0..MAX_PROPERTIES_PER_ITEM;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub;
+ };
+ let perms = (0..b).map(|k| PropertyKeyPermission {
+ key: property_key(k as usize),
+ permission: PropertyPermission {
+ mutable: true,
+ collection_admin: true,
+ token_owner: true,
+ },
+ }).collect::<Vec<_>>();
+ <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
+ let props = (0..b).map(|k| Property {
+ key: property_key(k as usize),
+ value: property_value(),
+ }).collect::<Vec<_>>();
+ let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
+ <Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), false, &Unlimited)?;
+ let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
+ }: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete.into_iter(), &Unlimited)?}
+
repartition_item {
bench_init!{
owner: sub; collection: collection(owner);
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -20,9 +20,12 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};
use up_data_structs::{
CollectionId, TokenId, CreateItemExData, CreateRefungibleExData, budget::Budget, Property,
- PropertyKey, PropertyValue, PropertyKeyPermission, CreateItemData,
+ PropertyKey, PropertyValue, PropertyKeyPermission, CreateItemData, CollectionPropertiesVec,
};
-use pallet_common::{CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight};
+use pallet_common::{
+ CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
+ weights::WeightInfo as _,
+};
use pallet_structure::Error as StructureError;
use sp_runtime::{DispatchError};
use sp_std::{vec::Vec, vec};
@@ -41,6 +44,14 @@
};
}
+fn properties_weight<T: Config>(properties: &CollectionPropertiesVec) -> u64 {
+ if properties.len() > 0 {
+ <CommonWeights<T>>::set_token_properties(properties.len() as u32)
+ } else {
+ 0
+ }
+}
+
pub struct CommonWeights<T: Config>(PhantomData<T>);
impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
fn create_item() -> Weight {
@@ -48,16 +59,31 @@
}
fn create_multiple_items(data: &[CreateItemData]) -> Weight {
- <SelfWeightOf<T>>::create_multiple_items(data.len() as u32)
+ <SelfWeightOf<T>>::create_multiple_items(data.len() as u32).saturating_add(
+ data.iter()
+ .map(|data| match data {
+ CreateItemData::ReFungible(rft_data) => {
+ properties_weight::<T>(&rft_data.properties)
+ }
+ _ => 0,
+ })
+ .fold(0, |a, b| a.saturating_add(b)),
+ )
}
fn create_multiple_items_ex(call: &CreateItemExData<T::CrossAccountId>) -> Weight {
match call {
CreateItemExData::RefungibleMultipleOwners(i) => {
<SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32)
+ .saturating_add(properties_weight::<T>(&i.properties))
}
CreateItemExData::RefungibleMultipleItems(i) => {
<SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32)
+ .saturating_add(
+ i.iter()
+ .map(|d| properties_weight::<T>(&d.properties))
+ .fold(0, |a, b| a.saturating_add(b)),
+ )
}
_ => 0,
}
@@ -67,29 +93,24 @@
max_weight_of!(burn_item_partial(), burn_item_fully())
}
- fn set_collection_properties(_amount: u32) -> Weight {
- // Error
- 0
+ fn set_collection_properties(amount: u32) -> Weight {
+ <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)
}
- fn delete_collection_properties(_amount: u32) -> Weight {
- // Error
- 0
+ fn delete_collection_properties(amount: u32) -> Weight {
+ <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)
}
- fn set_token_properties(_amount: u32) -> Weight {
- // Error
- 0
+ fn set_token_properties(amount: u32) -> Weight {
+ <SelfWeightOf<T>>::set_token_properties(amount)
}
- fn delete_token_properties(_amount: u32) -> Weight {
- // Error
- 0
+ fn delete_token_properties(amount: u32) -> Weight {
+ <SelfWeightOf<T>>::delete_token_properties(amount)
}
- fn set_token_property_permissions(_amount: u32) -> Weight {
- // Error
- 0
+ fn set_token_property_permissions(amount: u32) -> Weight {
+ <SelfWeightOf<T>>::set_token_property_permissions(amount)
}
fn transfer() -> Weight {
@@ -140,6 +161,7 @@
out.insert(to.clone(), data.pieces);
out.try_into().expect("limit > 0")
},
+ properties: data.properties,
}),
_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),
}
@@ -297,46 +319,85 @@
fn set_collection_properties(
&self,
- _sender: T::CrossAccountId,
- _property: Vec<Property>,
+ sender: T::CrossAccountId,
+ properties: Vec<Property>,
) -> DispatchResultWithPostInfo {
- fail!(<Error<T>>::SettingPropertiesNotAllowed)
+ let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);
+
+ with_weight(
+ <Pallet<T>>::set_collection_properties(self, &sender, properties),
+ weight,
+ )
}
fn delete_collection_properties(
&self,
- _sender: &T::CrossAccountId,
- _property_keys: Vec<PropertyKey>,
+ sender: &T::CrossAccountId,
+ property_keys: Vec<PropertyKey>,
) -> DispatchResultWithPostInfo {
- fail!(<Error<T>>::SettingPropertiesNotAllowed)
+ let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);
+
+ with_weight(
+ <Pallet<T>>::delete_collection_properties(self, sender, property_keys),
+ weight,
+ )
}
fn set_token_properties(
&self,
- _sender: T::CrossAccountId,
- _token_id: TokenId,
- _property: Vec<Property>,
- _nesting_budget: &dyn Budget,
+ sender: T::CrossAccountId,
+ token_id: TokenId,
+ properties: Vec<Property>,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
- fail!(<Error<T>>::SettingPropertiesNotAllowed)
+ let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);
+
+ with_weight(
+ <Pallet<T>>::set_token_properties(
+ self,
+ &sender,
+ token_id,
+ properties.into_iter(),
+ false,
+ nesting_budget,
+ ),
+ weight,
+ )
}
fn set_token_property_permissions(
&self,
- _sender: &T::CrossAccountId,
- _property_permissions: Vec<PropertyKeyPermission>,
+ sender: &T::CrossAccountId,
+ property_permissions: Vec<PropertyKeyPermission>,
) -> DispatchResultWithPostInfo {
- fail!(<Error<T>>::SettingPropertiesNotAllowed)
+ let weight =
+ <CommonWeights<T>>::set_token_property_permissions(property_permissions.len() as u32);
+
+ with_weight(
+ <Pallet<T>>::set_token_property_permissions(self, sender, property_permissions),
+ weight,
+ )
}
fn delete_token_properties(
&self,
- _sender: T::CrossAccountId,
- _token_id: TokenId,
- _property_keys: Vec<PropertyKey>,
- _nesting_budget: &dyn Budget,
+ sender: T::CrossAccountId,
+ token_id: TokenId,
+ property_keys: Vec<PropertyKey>,
+ nesting_budget: &dyn Budget,
) -> DispatchResultWithPostInfo {
- fail!(<Error<T>>::SettingPropertiesNotAllowed)
+ let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);
+
+ with_weight(
+ <Pallet<T>>::delete_token_properties(
+ self,
+ &sender,
+ token_id,
+ property_keys.into_iter(),
+ nesting_budget,
+ ),
+ weight,
+ )
}
fn check_nesting(
@@ -373,8 +434,8 @@
TokenId(<TokensMinted<T>>::get(self.id))
}
- fn token_owner(&self, _token: TokenId) -> Option<T::CrossAccountId> {
- None
+ fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {
+ <Pallet<T>>::token_owner(self.id, token)
}
fn token_property(&self, _token_id: TokenId, _key: &PropertyKey) -> Option<PropertyValue> {
pallets/refungible/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`]25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//! of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//! Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//! transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//! an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//! with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//! collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//! some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//! Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use frame_support::{ensure, BoundedVec};91use up_data_structs::{92 AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,93 CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping, budget::Budget,94};95use pallet_evm::account::CrossAccountId;96use pallet_common::{Error as CommonError, Event as CommonEvent, Pallet as PalletCommon};97use pallet_structure::Pallet as PalletStructure;98use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};99use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};100use core::ops::Deref;101use codec::{Encode, Decode, MaxEncodedLen};102use scale_info::TypeInfo;103104pub use pallet::*;105#[cfg(feature = "runtime-benchmarks")]106pub mod benchmarking;107pub mod common;108pub mod erc;109pub mod weights;110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[struct_versioning::versioned(version = 2, upper)]113#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]114pub struct ItemData {115 pub const_data: BoundedVec<u8, CustomDataLimit>,116117 #[version(..2)]118 pub variable_data: BoundedVec<u8, CustomDataLimit>,119}120121#[frame_support::pallet]122pub mod pallet {123 use super::*;124 use frame_support::{125 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,126 traits::StorageVersion,127 };128 use frame_system::pallet_prelude::*;129 use up_data_structs::{CollectionId, TokenId};130 use super::weights::WeightInfo;131132 #[pallet::error]133 pub enum Error<T> {134 /// Not Refungible item data used to mint in Refungible collection.135 NotRefungibleDataUsedToMintFungibleCollectionToken,136 /// Maximum refungibility exceeded137 WrongRefungiblePieces,138 /// Refungible token can't be repartitioned by user who isn't owns all pieces139 RepartitionWhileNotOwningAllPieces,140 /// Refungible token can't nest other tokens141 RefungibleDisallowsNesting,142 /// Setting item properties is not allowed143 SettingPropertiesNotAllowed,144 }145146 #[pallet::config]147 pub trait Config:148 frame_system::Config + pallet_common::Config + pallet_structure::Config149 {150 type WeightInfo: WeightInfo;151 }152153 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);154155 #[pallet::pallet]156 #[pallet::storage_version(STORAGE_VERSION)]157 #[pallet::generate_store(pub(super) trait Store)]158 pub struct Pallet<T>(_);159160 /// Amount of tokens minted for collection161 #[pallet::storage]162 pub type TokensMinted<T: Config> =163 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;164165 /// Amount of burnt tokens for collection166 #[pallet::storage]167 pub type TokensBurnt<T: Config> =168 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;169170 /// Custom data serialized to bytes for token171 #[pallet::storage]172 pub type TokenData<T: Config> = StorageNMap<173 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),174 Value = ItemData,175 QueryKind = ValueQuery,176 >;177178 /// Total amount of pieces for token179 #[pallet::storage]180 pub type TotalSupply<T: Config> = StorageNMap<181 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),182 Value = u128,183 QueryKind = ValueQuery,184 >;185186 /// Used to enumerate tokens owned by account187 #[pallet::storage]188 pub type Owned<T: Config> = StorageNMap<189 Key = (190 Key<Twox64Concat, CollectionId>,191 Key<Blake2_128Concat, T::CrossAccountId>,192 Key<Twox64Concat, TokenId>,193 ),194 Value = bool,195 QueryKind = ValueQuery,196 >;197198 /// Amount of tokens owned by account199 #[pallet::storage]200 pub type AccountBalance<T: Config> = StorageNMap<201 Key = (202 Key<Twox64Concat, CollectionId>,203 // Owner204 Key<Blake2_128Concat, T::CrossAccountId>,205 ),206 Value = u32,207 QueryKind = ValueQuery,208 >;209210 /// Amount of token pieces owned by account211 #[pallet::storage]212 pub type Balance<T: Config> = StorageNMap<213 Key = (214 Key<Twox64Concat, CollectionId>,215 Key<Twox64Concat, TokenId>,216 // Owner217 Key<Blake2_128Concat, T::CrossAccountId>,218 ),219 Value = u128,220 QueryKind = ValueQuery,221 >;222223 /// Allowance set by an owner for a spender for a token224 #[pallet::storage]225 pub type Allowance<T: Config> = StorageNMap<226 Key = (227 Key<Twox64Concat, CollectionId>,228 Key<Twox64Concat, TokenId>,229 // Owner230 Key<Blake2_128, T::CrossAccountId>,231 // Spender232 Key<Blake2_128Concat, T::CrossAccountId>,233 ),234 Value = u128,235 QueryKind = ValueQuery,236 >;237238 #[pallet::hooks]239 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {240 fn on_runtime_upgrade() -> Weight {241 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {242 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {243 Some(<ItemDataVersion2>::from(v))244 })245 }246247 0248 }249 }250}251252pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);253impl<T: Config> RefungibleHandle<T> {254 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {255 Self(inner)256 }257 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {258 self.0259 }260}261impl<T: Config> Deref for RefungibleHandle<T> {262 type Target = pallet_common::CollectionHandle<T>;263264 fn deref(&self) -> &Self::Target {265 &self.0266 }267}268269impl<T: Config> Pallet<T> {270 /// Get number of RFT tokens in collection271 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {272 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)273 }274275 /// Check that RFT token exists276 ///277 /// - `token`: Token ID.278 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {279 <TotalSupply<T>>::contains_key((collection.id, token))280 }281}282283// unchecked calls skips any permission checks284impl<T: Config> Pallet<T> {285 /// Create RFT collection286 ///287 /// `init_collection` will take non-refundable deposit for collection creation.288 ///289 /// - `data`: Contains settings for collection limits and permissions.290 pub fn init_collection(291 owner: T::CrossAccountId,292 data: CreateCollectionData<T::AccountId>,293 ) -> Result<CollectionId, DispatchError> {294 <PalletCommon<T>>::init_collection(owner, data, false)295 }296297 /// Destroy RFT collection298 ///299 /// `destroy_collection` will throw error if collection contains any tokens.300 /// Only owner can destroy collection.301 pub fn destroy_collection(302 collection: RefungibleHandle<T>,303 sender: &T::CrossAccountId,304 ) -> DispatchResult {305 let id = collection.id;306307 if Self::collection_has_tokens(id) {308 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());309 }310311 // =========312313 PalletCommon::destroy_collection(collection.0, sender)?;314315 <TokensMinted<T>>::remove(id);316 <TokensBurnt<T>>::remove(id);317 <TokenData<T>>::remove_prefix((id,), None);318 <TotalSupply<T>>::remove_prefix((id,), None);319 <Balance<T>>::remove_prefix((id,), None);320 <Allowance<T>>::remove_prefix((id,), None);321 <Owned<T>>::remove_prefix((id,), None);322 <AccountBalance<T>>::remove_prefix((id,), None);323 Ok(())324 }325326 fn collection_has_tokens(collection_id: CollectionId) -> bool {327 <TokenData<T>>::iter_prefix((collection_id,))328 .next()329 .is_some()330 }331332 pub fn burn_token_unchecked(333 collection: &RefungibleHandle<T>,334 token_id: TokenId,335 ) -> DispatchResult {336 let burnt = <TokensBurnt<T>>::get(collection.id)337 .checked_add(1)338 .ok_or(ArithmeticError::Overflow)?;339340 <TokensBurnt<T>>::insert(collection.id, burnt);341 <TokenData<T>>::remove((collection.id, token_id));342 <TotalSupply<T>>::remove((collection.id, token_id));343 <Balance<T>>::remove_prefix((collection.id, token_id), None);344 <Allowance<T>>::remove_prefix((collection.id, token_id), None);345 // TODO: ERC721 transfer event346 Ok(())347 }348349 /// Burn RFT token pieces350 ///351 /// `burn` will decrease total amount of token pieces and amount owned by sender.352 /// `burn` can be called even if there are multiple owners of the RFT token.353 /// If sender wouldn't have any pieces left after `burn` than she will stop being354 /// one of the owners of the token. If there is no account that owns any pieces of355 /// the token than token will be burned too.356 ///357 /// - `amount`: Amount of token pieces to burn.358 /// - `token`: Token who's pieces should be burned359 /// - `collection`: Collection that contains the token360 pub fn burn(361 collection: &RefungibleHandle<T>,362 owner: &T::CrossAccountId,363 token: TokenId,364 amount: u128,365 ) -> DispatchResult {366 let total_supply = <TotalSupply<T>>::get((collection.id, token))367 .checked_sub(amount)368 .ok_or(<CommonError<T>>::TokenValueTooLow)?;369370 // This was probally last owner of this token?371 if total_supply == 0 {372 // Ensure user actually owns this amount373 ensure!(374 <Balance<T>>::get((collection.id, token, owner)) == amount,375 <CommonError<T>>::TokenValueTooLow376 );377 let account_balance = <AccountBalance<T>>::get((collection.id, owner))378 .checked_sub(1)379 // Should not occur380 .ok_or(ArithmeticError::Underflow)?;381382 // =========383384 <Owned<T>>::remove((collection.id, owner, token));385 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);386 <AccountBalance<T>>::insert((collection.id, owner), account_balance);387 Self::burn_token_unchecked(collection, token)?;388 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(389 collection.id,390 token,391 owner.clone(),392 amount,393 ));394 return Ok(());395 }396397 let balance = <Balance<T>>::get((collection.id, token, owner))398 .checked_sub(amount)399 .ok_or(<CommonError<T>>::TokenValueTooLow)?;400 let account_balance = if balance == 0 {401 <AccountBalance<T>>::get((collection.id, owner))402 .checked_sub(1)403 // Should not occur404 .ok_or(ArithmeticError::Underflow)?405 } else {406 0407 };408409 // =========410411 if balance == 0 {412 <Owned<T>>::remove((collection.id, owner, token));413 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);414 <Balance<T>>::remove((collection.id, token, owner));415 <AccountBalance<T>>::insert((collection.id, owner), account_balance);416 } else {417 <Balance<T>>::insert((collection.id, token, owner), balance);418 }419 <TotalSupply<T>>::insert((collection.id, token), total_supply);420 // TODO: ERC20 transfer event421 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(422 collection.id,423 token,424 owner.clone(),425 amount,426 ));427 Ok(())428 }429430 /// Transfer RFT token pieces from one account to another.431 ///432 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.433 ///434 /// - `from`: Owner of token pieces to transfer.435 /// - `to`: Recepient of transfered token pieces.436 /// - `amount`: Amount of token pieces to transfer.437 /// - `token`: Token whos pieces should be transfered438 /// - `collection`: Collection that contains the token439 pub fn transfer(440 collection: &RefungibleHandle<T>,441 from: &T::CrossAccountId,442 to: &T::CrossAccountId,443 token: TokenId,444 amount: u128,445 nesting_budget: &dyn Budget,446 ) -> DispatchResult {447 ensure!(448 collection.limits.transfers_enabled(),449 <CommonError<T>>::TransferNotAllowed450 );451452 if collection.permissions.access() == AccessMode::AllowList {453 collection.check_allowlist(from)?;454 collection.check_allowlist(to)?;455 }456 <PalletCommon<T>>::ensure_correct_receiver(to)?;457458 let balance_from = <Balance<T>>::get((collection.id, token, from))459 .checked_sub(amount)460 .ok_or(<CommonError<T>>::TokenValueTooLow)?;461 let mut create_target = false;462 let from_to_differ = from != to;463 let balance_to = if from != to {464 let old_balance = <Balance<T>>::get((collection.id, token, to));465 if old_balance == 0 {466 create_target = true;467 }468 Some(469 old_balance470 .checked_add(amount)471 .ok_or(ArithmeticError::Overflow)?,472 )473 } else {474 None475 };476477 let account_balance_from = if balance_from == 0 {478 Some(479 <AccountBalance<T>>::get((collection.id, from))480 .checked_sub(1)481 // Should not occur482 .ok_or(ArithmeticError::Underflow)?,483 )484 } else {485 None486 };487 // Account data is created in token, AccountBalance should be increased488 // But only if from != to as we shouldn't check overflow in this case489 let account_balance_to = if create_target && from_to_differ {490 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))491 .checked_add(1)492 .ok_or(ArithmeticError::Overflow)?;493 ensure!(494 account_balance_to < collection.limits.account_token_ownership_limit(),495 <CommonError<T>>::AccountTokenLimitExceeded,496 );497498 Some(account_balance_to)499 } else {500 None501 };502503 // =========504505 <PalletStructure<T>>::nest_if_sent_to_token(506 from.clone(),507 to,508 collection.id,509 token,510 nesting_budget,511 )?;512513 if let Some(balance_to) = balance_to {514 // from != to515 if balance_from == 0 {516 <Balance<T>>::remove((collection.id, token, from));517 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);518 } else {519 <Balance<T>>::insert((collection.id, token, from), balance_from);520 }521 <Balance<T>>::insert((collection.id, token, to), balance_to);522 if let Some(account_balance_from) = account_balance_from {523 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);524 <Owned<T>>::remove((collection.id, from, token));525 }526 if let Some(account_balance_to) = account_balance_to {527 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);528 <Owned<T>>::insert((collection.id, to, token), true);529 }530 }531532 // TODO: ERC20 transfer event533 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(534 collection.id,535 token,536 from.clone(),537 to.clone(),538 amount,539 ));540 Ok(())541 }542543 /// Batched operation to create multiple RFT tokens.544 ///545 /// Same as `create_item` but creates multiple tokens.546 ///547 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.548 pub fn create_multiple_items(549 collection: &RefungibleHandle<T>,550 sender: &T::CrossAccountId,551 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,552 nesting_budget: &dyn Budget,553 ) -> DispatchResult {554 if !collection.is_owner_or_admin(sender) {555 ensure!(556 collection.permissions.mint_mode(),557 <CommonError<T>>::PublicMintingNotAllowed558 );559 collection.check_allowlist(sender)?;560561 for item in data.iter() {562 for user in item.users.keys() {563 collection.check_allowlist(user)?;564 }565 }566 }567568 for item in data.iter() {569 for (owner, _) in item.users.iter() {570 <PalletCommon<T>>::ensure_correct_receiver(owner)?;571 }572 }573574 // Total pieces per tokens575 let totals = data576 .iter()577 .map(|data| {578 Ok(data579 .users580 .iter()581 .map(|u| u.1)582 .try_fold(0u128, |acc, v| acc.checked_add(*v))583 .ok_or(ArithmeticError::Overflow)?)584 })585 .collect::<Result<Vec<_>, DispatchError>>()?;586 for total in &totals {587 ensure!(588 *total <= MAX_REFUNGIBLE_PIECES,589 <Error<T>>::WrongRefungiblePieces590 );591 }592593 let first_token_id = <TokensMinted<T>>::get(collection.id);594 let tokens_minted = first_token_id595 .checked_add(data.len() as u32)596 .ok_or(ArithmeticError::Overflow)?;597 ensure!(598 tokens_minted < collection.limits.token_limit(),599 <CommonError<T>>::CollectionTokenLimitExceeded600 );601602 let mut balances = BTreeMap::new();603 for data in &data {604 for owner in data.users.keys() {605 let balance = balances606 .entry(owner)607 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));608 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;609610 ensure!(611 *balance <= collection.limits.account_token_ownership_limit(),612 <CommonError<T>>::AccountTokenLimitExceeded,613 );614 }615 }616617 for (i, token) in data.iter().enumerate() {618 let token_id = TokenId(first_token_id + i as u32 + 1);619 for (to, _) in token.users.iter() {620 <PalletStructure<T>>::check_nesting(621 sender.clone(),622 to,623 collection.id,624 token_id,625 nesting_budget,626 )?;627 }628 }629630 // =========631632 <TokensMinted<T>>::insert(collection.id, tokens_minted);633 for (account, balance) in balances {634 <AccountBalance<T>>::insert((collection.id, account), balance);635 }636 for (i, token) in data.into_iter().enumerate() {637 let token_id = first_token_id + i as u32 + 1;638 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);639640 <TokenData<T>>::insert(641 (collection.id, token_id),642 ItemData {643 const_data: token.const_data,644 },645 );646647 for (user, amount) in token.users.into_iter() {648 if amount == 0 {649 continue;650 }651 <Balance<T>>::insert((collection.id, token_id, &user), amount);652 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);653 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(654 &user,655 collection.id,656 TokenId(token_id),657 );658659 // TODO: ERC20 transfer event660 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(661 collection.id,662 TokenId(token_id),663 user,664 amount,665 ));666 }667 }668 Ok(())669 }670671 pub fn set_allowance_unchecked(672 collection: &RefungibleHandle<T>,673 sender: &T::CrossAccountId,674 spender: &T::CrossAccountId,675 token: TokenId,676 amount: u128,677 ) {678 if amount == 0 {679 <Allowance<T>>::remove((collection.id, token, sender, spender));680 } else {681 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);682 }683 // TODO: ERC20 approval event684 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(685 collection.id,686 token,687 sender.clone(),688 spender.clone(),689 amount,690 ))691 }692693 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.694 ///695 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.696 pub fn set_allowance(697 collection: &RefungibleHandle<T>,698 sender: &T::CrossAccountId,699 spender: &T::CrossAccountId,700 token: TokenId,701 amount: u128,702 ) -> DispatchResult {703 if collection.permissions.access() == AccessMode::AllowList {704 collection.check_allowlist(sender)?;705 collection.check_allowlist(spender)?;706 }707708 <PalletCommon<T>>::ensure_correct_receiver(spender)?;709710 if <Balance<T>>::get((collection.id, token, sender)) < amount {711 ensure!(712 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),713 <CommonError<T>>::CantApproveMoreThanOwned714 );715 }716717 // =========718719 Self::set_allowance_unchecked(collection, sender, spender, token, amount);720 Ok(())721 }722723 /// Returns allowance, which should be set after transaction724 fn check_allowed(725 collection: &RefungibleHandle<T>,726 spender: &T::CrossAccountId,727 from: &T::CrossAccountId,728 token: TokenId,729 amount: u128,730 nesting_budget: &dyn Budget,731 ) -> Result<Option<u128>, DispatchError> {732 if spender.conv_eq(from) {733 return Ok(None);734 }735 if collection.permissions.access() == AccessMode::AllowList {736 // `from`, `to` checked in [`transfer`]737 collection.check_allowlist(spender)?;738 }739 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {740 // TODO: should collection owner be allowed to perform this transfer?741 ensure!(742 <PalletStructure<T>>::check_indirectly_owned(743 spender.clone(),744 source.0,745 source.1,746 None,747 nesting_budget748 )?,749 <CommonError<T>>::ApprovedValueTooLow,750 );751 return Ok(None);752 }753 let allowance =754 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);755 if allowance.is_none() {756 ensure!(757 collection.ignores_allowance(spender),758 <CommonError<T>>::ApprovedValueTooLow759 );760 }761 Ok(allowance)762 }763764 /// Transfer RFT token pieces from one account to another.765 ///766 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.767 /// The owner should set allowance for the spender to transfer pieces.768 ///769 /// [`transfer`]: struct.Pallet.html#method.transfer770 pub fn transfer_from(771 collection: &RefungibleHandle<T>,772 spender: &T::CrossAccountId,773 from: &T::CrossAccountId,774 to: &T::CrossAccountId,775 token: TokenId,776 amount: u128,777 nesting_budget: &dyn Budget,778 ) -> DispatchResult {779 let allowance =780 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;781782 // =========783784 Self::transfer(collection, from, to, token, amount, nesting_budget)?;785 if let Some(allowance) = allowance {786 Self::set_allowance_unchecked(collection, from, spender, token, allowance);787 }788 Ok(())789 }790791 /// Burn RFT token pieces from the account.792 ///793 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should794 /// set allowance for the spender to burn pieces795 ///796 /// [`burn`]: struct.Pallet.html#method.burn797 pub fn burn_from(798 collection: &RefungibleHandle<T>,799 spender: &T::CrossAccountId,800 from: &T::CrossAccountId,801 token: TokenId,802 amount: u128,803 nesting_budget: &dyn Budget,804 ) -> DispatchResult {805 let allowance =806 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;807808 // =========809810 Self::burn(collection, from, token, amount)?;811 if let Some(allowance) = allowance {812 Self::set_allowance_unchecked(collection, from, spender, token, allowance);813 }814 Ok(())815 }816817 /// Create RFT token.818 ///819 /// The sender should be the owner/admin of the collection or collection should be configured820 /// to allow public minting.821 ///822 /// - `data`: Contains list of users who will become the owners of the token pieces and amount823 /// of token pieces they will receive.824 pub fn create_item(825 collection: &RefungibleHandle<T>,826 sender: &T::CrossAccountId,827 data: CreateRefungibleExData<T::CrossAccountId>,828 nesting_budget: &dyn Budget,829 ) -> DispatchResult {830 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)831 }832833 /// Repartition RFT token.834 ///835 /// `repartition` will set token balance of the sender and total amount of token pieces.836 /// Sender should own all of the token pieces. `repartition' could be done even if some837 /// token pieces were burned before.838 ///839 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.840 pub fn repartition(841 collection: &RefungibleHandle<T>,842 owner: &T::CrossAccountId,843 token: TokenId,844 amount: u128,845 ) -> DispatchResult {846 ensure!(847 amount <= MAX_REFUNGIBLE_PIECES,848 <Error<T>>::WrongRefungiblePieces849 );850 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);851 // Ensure user owns all pieces852 let total_supply = <TotalSupply<T>>::get((collection.id, token));853 let balance = <Balance<T>>::get((collection.id, token, owner));854 ensure!(855 total_supply == balance,856 <Error<T>>::RepartitionWhileNotOwningAllPieces857 );858859 <Balance<T>>::insert((collection.id, token, owner), amount);860 <TotalSupply<T>>::insert((collection.id, token), amount);861 Ok(())862 }863864 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {865 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()866 }867}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`]25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//! of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//! Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//! transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//! an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//! with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//! collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//! some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//! Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use frame_support::{ensure, fail, BoundedVec, transactional, storage::with_transaction};91use up_data_structs::{92 AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,93 CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping, budget::Budget,94 Property, PropertyScope, TrySetProperty, PropertyKey, PropertyValue, PropertyPermission,95 PropertyKeyPermission,96};97use pallet_evm::account::CrossAccountId;98use pallet_common::{99 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,100 CommonCollectionOperations as _,101};102use pallet_structure::Pallet as PalletStructure;103use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};104use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};105use core::ops::Deref;106use codec::{Encode, Decode, MaxEncodedLen};107use scale_info::TypeInfo;108109pub use pallet::*;110#[cfg(feature = "runtime-benchmarks")]111pub mod benchmarking;112pub mod common;113pub mod erc;114pub mod weights;115pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;116117#[struct_versioning::versioned(version = 2, upper)]118#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]119pub struct ItemData {120 pub const_data: BoundedVec<u8, CustomDataLimit>,121122 #[version(..2)]123 pub variable_data: BoundedVec<u8, CustomDataLimit>,124}125126#[frame_support::pallet]127pub mod pallet {128 use super::*;129 use frame_support::{130 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,131 traits::StorageVersion,132 };133 use frame_system::pallet_prelude::*;134 use up_data_structs::{CollectionId, TokenId};135 use super::weights::WeightInfo;136137 #[pallet::error]138 pub enum Error<T> {139 /// Not Refungible item data used to mint in Refungible collection.140 NotRefungibleDataUsedToMintFungibleCollectionToken,141 /// Maximum refungibility exceeded142 WrongRefungiblePieces,143 /// Refungible token can't be repartitioned by user who isn't owns all pieces144 RepartitionWhileNotOwningAllPieces,145 /// Refungible token can't nest other tokens146 RefungibleDisallowsNesting,147 /// Setting item properties is not allowed148 SettingPropertiesNotAllowed,149 }150151 #[pallet::config]152 pub trait Config:153 frame_system::Config + pallet_common::Config + pallet_structure::Config154 {155 type WeightInfo: WeightInfo;156 }157158 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);159160 #[pallet::pallet]161 #[pallet::storage_version(STORAGE_VERSION)]162 #[pallet::generate_store(pub(super) trait Store)]163 pub struct Pallet<T>(_);164165 /// Amount of tokens minted for collection166 #[pallet::storage]167 pub type TokensMinted<T: Config> =168 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;169170 /// Amount of burnt tokens for collection171 #[pallet::storage]172 pub type TokensBurnt<T: Config> =173 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;174175 /// Custom data serialized to bytes for token176 #[pallet::storage]177 pub type TokenData<T: Config> = StorageNMap<178 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),179 Value = ItemData,180 QueryKind = ValueQuery,181 >;182183 #[pallet::storage]184 #[pallet::getter(fn token_properties)]185 pub type TokenProperties<T: Config> = StorageNMap<186 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),187 Value = up_data_structs::Properties,188 QueryKind = ValueQuery,189 OnEmpty = up_data_structs::TokenProperties,190 >;191192 /// Total amount of pieces for token193 #[pallet::storage]194 pub type TotalSupply<T: Config> = StorageNMap<195 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),196 Value = u128,197 QueryKind = ValueQuery,198 >;199200 /// Used to enumerate tokens owned by account201 #[pallet::storage]202 pub type Owned<T: Config> = StorageNMap<203 Key = (204 Key<Twox64Concat, CollectionId>,205 Key<Blake2_128Concat, T::CrossAccountId>,206 Key<Twox64Concat, TokenId>,207 ),208 Value = bool,209 QueryKind = ValueQuery,210 >;211212 /// Amount of tokens owned by account213 #[pallet::storage]214 pub type AccountBalance<T: Config> = StorageNMap<215 Key = (216 Key<Twox64Concat, CollectionId>,217 // Owner218 Key<Blake2_128Concat, T::CrossAccountId>,219 ),220 Value = u32,221 QueryKind = ValueQuery,222 >;223224 /// Amount of token pieces owned by account225 #[pallet::storage]226 pub type Balance<T: Config> = StorageNMap<227 Key = (228 Key<Twox64Concat, CollectionId>,229 Key<Twox64Concat, TokenId>,230 // Owner231 Key<Blake2_128Concat, T::CrossAccountId>,232 ),233 Value = u128,234 QueryKind = ValueQuery,235 >;236237 /// Allowance set by an owner for a spender for a token238 #[pallet::storage]239 pub type Allowance<T: Config> = StorageNMap<240 Key = (241 Key<Twox64Concat, CollectionId>,242 Key<Twox64Concat, TokenId>,243 // Owner244 Key<Blake2_128, T::CrossAccountId>,245 // Spender246 Key<Blake2_128Concat, T::CrossAccountId>,247 ),248 Value = u128,249 QueryKind = ValueQuery,250 >;251252 #[pallet::hooks]253 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {254 fn on_runtime_upgrade() -> Weight {255 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {256 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {257 Some(<ItemDataVersion2>::from(v))258 })259 }260261 0262 }263 }264}265266pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);267impl<T: Config> RefungibleHandle<T> {268 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {269 Self(inner)270 }271 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {272 self.0273 }274}275impl<T: Config> Deref for RefungibleHandle<T> {276 type Target = pallet_common::CollectionHandle<T>;277278 fn deref(&self) -> &Self::Target {279 &self.0280 }281}282283impl<T: Config> Pallet<T> {284 /// Get number of RFT tokens in collection285 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {286 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)287 }288289 /// Check that RFT token exists290 ///291 /// - `token`: Token ID.292 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {293 <TotalSupply<T>>::contains_key((collection.id, token))294 }295296 pub fn set_scoped_token_property(297 collection_id: CollectionId,298 token_id: TokenId,299 scope: PropertyScope,300 property: Property,301 ) -> DispatchResult {302 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {303 properties.try_scoped_set(scope, property.key, property.value)304 })305 .map_err(<CommonError<T>>::from)?;306307 Ok(())308 }309310 pub fn set_scoped_token_properties(311 collection_id: CollectionId,312 token_id: TokenId,313 scope: PropertyScope,314 properties: impl Iterator<Item = Property>,315 ) -> DispatchResult {316 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {317 stored_properties.try_scoped_set_from_iter(scope, properties)318 })319 .map_err(<CommonError<T>>::from)?;320321 Ok(())322 }323}324325// unchecked calls skips any permission checks326impl<T: Config> Pallet<T> {327 /// Create RFT collection328 ///329 /// `init_collection` will take non-refundable deposit for collection creation.330 ///331 /// - `data`: Contains settings for collection limits and permissions.332 pub fn init_collection(333 owner: T::CrossAccountId,334 data: CreateCollectionData<T::AccountId>,335 ) -> Result<CollectionId, DispatchError> {336 <PalletCommon<T>>::init_collection(owner, data, false)337 }338339 /// Destroy RFT collection340 ///341 /// `destroy_collection` will throw error if collection contains any tokens.342 /// Only owner can destroy collection.343 pub fn destroy_collection(344 collection: RefungibleHandle<T>,345 sender: &T::CrossAccountId,346 ) -> DispatchResult {347 let id = collection.id;348349 if Self::collection_has_tokens(id) {350 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());351 }352353 // =========354355 PalletCommon::destroy_collection(collection.0, sender)?;356357 <TokensMinted<T>>::remove(id);358 <TokensBurnt<T>>::remove(id);359 <TokenData<T>>::remove_prefix((id,), None);360 <TotalSupply<T>>::remove_prefix((id,), None);361 <Balance<T>>::remove_prefix((id,), None);362 <Allowance<T>>::remove_prefix((id,), None);363 <Owned<T>>::remove_prefix((id,), None);364 <AccountBalance<T>>::remove_prefix((id,), None);365 Ok(())366 }367368 fn collection_has_tokens(collection_id: CollectionId) -> bool {369 <TokenData<T>>::iter_prefix((collection_id,))370 .next()371 .is_some()372 }373374 pub fn burn_token_unchecked(375 collection: &RefungibleHandle<T>,376 token_id: TokenId,377 ) -> DispatchResult {378 let burnt = <TokensBurnt<T>>::get(collection.id)379 .checked_add(1)380 .ok_or(ArithmeticError::Overflow)?;381382 <TokensBurnt<T>>::insert(collection.id, burnt);383 <TokenData<T>>::remove((collection.id, token_id));384 <TokenProperties<T>>::remove((collection.id, token_id));385 <TotalSupply<T>>::remove((collection.id, token_id));386 <Balance<T>>::remove_prefix((collection.id, token_id), None);387 <Allowance<T>>::remove_prefix((collection.id, token_id), None);388 // TODO: ERC721 transfer event389 Ok(())390 }391392 /// Burn RFT token pieces393 ///394 /// `burn` will decrease total amount of token pieces and amount owned by sender.395 /// `burn` can be called even if there are multiple owners of the RFT token.396 /// If sender wouldn't have any pieces left after `burn` than she will stop being397 /// one of the owners of the token. If there is no account that owns any pieces of398 /// the token than token will be burned too.399 ///400 /// - `amount`: Amount of token pieces to burn.401 /// - `token`: Token who's pieces should be burned402 /// - `collection`: Collection that contains the token403 pub fn burn(404 collection: &RefungibleHandle<T>,405 owner: &T::CrossAccountId,406 token: TokenId,407 amount: u128,408 ) -> DispatchResult {409 let total_supply = <TotalSupply<T>>::get((collection.id, token))410 .checked_sub(amount)411 .ok_or(<CommonError<T>>::TokenValueTooLow)?;412413 // This was probally last owner of this token?414 if total_supply == 0 {415 // Ensure user actually owns this amount416 ensure!(417 <Balance<T>>::get((collection.id, token, owner)) == amount,418 <CommonError<T>>::TokenValueTooLow419 );420 let account_balance = <AccountBalance<T>>::get((collection.id, owner))421 .checked_sub(1)422 // Should not occur423 .ok_or(ArithmeticError::Underflow)?;424425 // =========426427 <Owned<T>>::remove((collection.id, owner, token));428 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);429 <AccountBalance<T>>::insert((collection.id, owner), account_balance);430 Self::burn_token_unchecked(collection, token)?;431 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(432 collection.id,433 token,434 owner.clone(),435 amount,436 ));437 return Ok(());438 }439440 let balance = <Balance<T>>::get((collection.id, token, owner))441 .checked_sub(amount)442 .ok_or(<CommonError<T>>::TokenValueTooLow)?;443 let account_balance = if balance == 0 {444 <AccountBalance<T>>::get((collection.id, owner))445 .checked_sub(1)446 // Should not occur447 .ok_or(ArithmeticError::Underflow)?448 } else {449 0450 };451452 // =========453454 if balance == 0 {455 <Owned<T>>::remove((collection.id, owner, token));456 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);457 <Balance<T>>::remove((collection.id, token, owner));458 <AccountBalance<T>>::insert((collection.id, owner), account_balance);459 } else {460 <Balance<T>>::insert((collection.id, token, owner), balance);461 }462 <TotalSupply<T>>::insert((collection.id, token), total_supply);463 // TODO: ERC20 transfer event464 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(465 collection.id,466 token,467 owner.clone(),468 amount,469 ));470 Ok(())471 }472473 #[transactional]474 fn modify_token_properties(475 collection: &RefungibleHandle<T>,476 sender: &T::CrossAccountId,477 token_id: TokenId,478 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,479 is_token_create: bool,480 nesting_budget: &dyn Budget,481 ) -> DispatchResult {482 let is_collection_admin = || collection.is_owner_or_admin(sender);483 let is_token_owner = || -> Result<bool, DispatchError> {484 let balance = collection.balance(sender.clone(), token_id);485 let total_pieces: u128 =486 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);487 if balance != total_pieces {488 return Ok(false);489 }490491 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(492 sender.clone(),493 collection.id,494 token_id,495 None,496 nesting_budget,497 )?;498499 Ok(is_bundle_owner)500 };501502 for (key, value) in properties {503 let permission = <PalletCommon<T>>::property_permissions(collection.id)504 .get(&key)505 .cloned()506 .unwrap_or_else(PropertyPermission::none);507508 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))509 .get(&key)510 .is_some();511512 match permission {513 PropertyPermission { mutable: false, .. } if is_property_exists => {514 return Err(<CommonError<T>>::NoPermission.into());515 }516517 PropertyPermission {518 collection_admin,519 token_owner,520 ..521 } => {522 //TODO: investigate threats during public minting.523 let is_token_create =524 is_token_create && (collection_admin || token_owner) && value.is_some();525 if !(is_token_create526 || (collection_admin && is_collection_admin())527 || (token_owner && is_token_owner()?))528 {529 fail!(<CommonError<T>>::NoPermission);530 }531 }532 }533534 match value {535 Some(value) => {536 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {537 properties.try_set(key.clone(), value)538 })539 .map_err(<CommonError<T>>::from)?;540541 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(542 collection.id,543 token_id,544 key,545 ));546 }547 None => {548 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {549 properties.remove(&key)550 })551 .map_err(<CommonError<T>>::from)?;552553 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(554 collection.id,555 token_id,556 key,557 ));558 }559 }560 }561562 Ok(())563 }564565 pub fn set_token_properties(566 collection: &RefungibleHandle<T>,567 sender: &T::CrossAccountId,568 token_id: TokenId,569 properties: impl Iterator<Item = Property>,570 is_token_create: bool,571 nesting_budget: &dyn Budget,572 ) -> DispatchResult {573 Self::modify_token_properties(574 collection,575 sender,576 token_id,577 properties.map(|p| (p.key, Some(p.value))),578 is_token_create,579 nesting_budget,580 )581 }582583 pub fn set_token_property(584 collection: &RefungibleHandle<T>,585 sender: &T::CrossAccountId,586 token_id: TokenId,587 property: Property,588 nesting_budget: &dyn Budget,589 ) -> DispatchResult {590 let is_token_create = false;591592 Self::set_token_properties(593 collection,594 sender,595 token_id,596 [property].into_iter(),597 is_token_create,598 nesting_budget,599 )600 }601602 pub fn delete_token_properties(603 collection: &RefungibleHandle<T>,604 sender: &T::CrossAccountId,605 token_id: TokenId,606 property_keys: impl Iterator<Item = PropertyKey>,607 nesting_budget: &dyn Budget,608 ) -> DispatchResult {609 let is_token_create = false;610611 Self::modify_token_properties(612 collection,613 sender,614 token_id,615 property_keys.into_iter().map(|key| (key, None)),616 is_token_create,617 nesting_budget,618 )619 }620621 pub fn delete_token_property(622 collection: &RefungibleHandle<T>,623 sender: &T::CrossAccountId,624 token_id: TokenId,625 property_key: PropertyKey,626 nesting_budget: &dyn Budget,627 ) -> DispatchResult {628 Self::delete_token_properties(629 collection,630 sender,631 token_id,632 [property_key].into_iter(),633 nesting_budget,634 )635 }636637 /// Transfer RFT token pieces from one account to another.638 ///639 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.640 ///641 /// - `from`: Owner of token pieces to transfer.642 /// - `to`: Recepient of transfered token pieces.643 /// - `amount`: Amount of token pieces to transfer.644 /// - `token`: Token whos pieces should be transfered645 /// - `collection`: Collection that contains the token646 pub fn transfer(647 collection: &RefungibleHandle<T>,648 from: &T::CrossAccountId,649 to: &T::CrossAccountId,650 token: TokenId,651 amount: u128,652 nesting_budget: &dyn Budget,653 ) -> DispatchResult {654 ensure!(655 collection.limits.transfers_enabled(),656 <CommonError<T>>::TransferNotAllowed657 );658659 if collection.permissions.access() == AccessMode::AllowList {660 collection.check_allowlist(from)?;661 collection.check_allowlist(to)?;662 }663 <PalletCommon<T>>::ensure_correct_receiver(to)?;664665 let balance_from = <Balance<T>>::get((collection.id, token, from))666 .checked_sub(amount)667 .ok_or(<CommonError<T>>::TokenValueTooLow)?;668 let mut create_target = false;669 let from_to_differ = from != to;670 let balance_to = if from != to {671 let old_balance = <Balance<T>>::get((collection.id, token, to));672 if old_balance == 0 {673 create_target = true;674 }675 Some(676 old_balance677 .checked_add(amount)678 .ok_or(ArithmeticError::Overflow)?,679 )680 } else {681 None682 };683684 let account_balance_from = if balance_from == 0 {685 Some(686 <AccountBalance<T>>::get((collection.id, from))687 .checked_sub(1)688 // Should not occur689 .ok_or(ArithmeticError::Underflow)?,690 )691 } else {692 None693 };694 // Account data is created in token, AccountBalance should be increased695 // But only if from != to as we shouldn't check overflow in this case696 let account_balance_to = if create_target && from_to_differ {697 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))698 .checked_add(1)699 .ok_or(ArithmeticError::Overflow)?;700 ensure!(701 account_balance_to < collection.limits.account_token_ownership_limit(),702 <CommonError<T>>::AccountTokenLimitExceeded,703 );704705 Some(account_balance_to)706 } else {707 None708 };709710 // =========711712 <PalletStructure<T>>::nest_if_sent_to_token(713 from.clone(),714 to,715 collection.id,716 token,717 nesting_budget,718 )?;719720 if let Some(balance_to) = balance_to {721 // from != to722 if balance_from == 0 {723 <Balance<T>>::remove((collection.id, token, from));724 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);725 } else {726 <Balance<T>>::insert((collection.id, token, from), balance_from);727 }728 <Balance<T>>::insert((collection.id, token, to), balance_to);729 if let Some(account_balance_from) = account_balance_from {730 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);731 <Owned<T>>::remove((collection.id, from, token));732 }733 if let Some(account_balance_to) = account_balance_to {734 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);735 <Owned<T>>::insert((collection.id, to, token), true);736 }737 }738739 // TODO: ERC20 transfer event740 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(741 collection.id,742 token,743 from.clone(),744 to.clone(),745 amount,746 ));747 Ok(())748 }749750 /// Batched operation to create multiple RFT tokens.751 ///752 /// Same as `create_item` but creates multiple tokens.753 ///754 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.755 pub fn create_multiple_items(756 collection: &RefungibleHandle<T>,757 sender: &T::CrossAccountId,758 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,759 nesting_budget: &dyn Budget,760 ) -> DispatchResult {761 if !collection.is_owner_or_admin(sender) {762 ensure!(763 collection.permissions.mint_mode(),764 <CommonError<T>>::PublicMintingNotAllowed765 );766 collection.check_allowlist(sender)?;767768 for item in data.iter() {769 for user in item.users.keys() {770 collection.check_allowlist(user)?;771 }772 }773 }774775 for item in data.iter() {776 for (owner, _) in item.users.iter() {777 <PalletCommon<T>>::ensure_correct_receiver(owner)?;778 }779 }780781 // Total pieces per tokens782 let totals = data783 .iter()784 .map(|data| {785 Ok(data786 .users787 .iter()788 .map(|u| u.1)789 .try_fold(0u128, |acc, v| acc.checked_add(*v))790 .ok_or(ArithmeticError::Overflow)?)791 })792 .collect::<Result<Vec<_>, DispatchError>>()?;793 for total in &totals {794 ensure!(795 *total <= MAX_REFUNGIBLE_PIECES,796 <Error<T>>::WrongRefungiblePieces797 );798 }799800 let first_token_id = <TokensMinted<T>>::get(collection.id);801 let tokens_minted = first_token_id802 .checked_add(data.len() as u32)803 .ok_or(ArithmeticError::Overflow)?;804 ensure!(805 tokens_minted < collection.limits.token_limit(),806 <CommonError<T>>::CollectionTokenLimitExceeded807 );808809 let mut balances = BTreeMap::new();810 for data in &data {811 for owner in data.users.keys() {812 let balance = balances813 .entry(owner)814 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));815 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;816817 ensure!(818 *balance <= collection.limits.account_token_ownership_limit(),819 <CommonError<T>>::AccountTokenLimitExceeded,820 );821 }822 }823824 for (i, token) in data.iter().enumerate() {825 let token_id = TokenId(first_token_id + i as u32 + 1);826 for (to, _) in token.users.iter() {827 <PalletStructure<T>>::check_nesting(828 sender.clone(),829 to,830 collection.id,831 token_id,832 nesting_budget,833 )?;834 }835 }836837 // =========838839 with_transaction(|| {840 for (i, data) in data.iter().enumerate() {841 let token_id = first_token_id + i as u32 + 1;842 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);843844 <TokenData<T>>::insert(845 (collection.id, token_id),846 ItemData {847 const_data: data.const_data.clone(),848 },849 );850851 for (user, amount) in data.users.iter() {852 if *amount == 0 {853 continue;854 }855 <Balance<T>>::insert((collection.id, token_id, &user), amount);856 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);857 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(858 user,859 collection.id,860 TokenId(token_id),861 );862 }863864 if let Err(e) = Self::set_token_properties(865 collection,866 sender,867 TokenId(token_id),868 data.properties.clone().into_iter(),869 true,870 nesting_budget,871 ) {872 return TransactionOutcome::Rollback(Err(e));873 }874 }875 TransactionOutcome::Commit(Ok(()))876 })?;877878 <TokensMinted<T>>::insert(collection.id, tokens_minted);879880 for (account, balance) in balances {881 <AccountBalance<T>>::insert((collection.id, account), balance);882 }883884 for (i, token) in data.into_iter().enumerate() {885 let token_id = first_token_id + i as u32 + 1;886887 for (user, amount) in token.users.into_iter() {888 if amount == 0 {889 continue;890 }891892 // TODO: ERC20 transfer event893 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(894 collection.id,895 TokenId(token_id),896 user,897 amount,898 ));899 }900 }901 Ok(())902 }903904 pub fn set_allowance_unchecked(905 collection: &RefungibleHandle<T>,906 sender: &T::CrossAccountId,907 spender: &T::CrossAccountId,908 token: TokenId,909 amount: u128,910 ) {911 if amount == 0 {912 <Allowance<T>>::remove((collection.id, token, sender, spender));913 } else {914 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);915 }916 // TODO: ERC20 approval event917 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(918 collection.id,919 token,920 sender.clone(),921 spender.clone(),922 amount,923 ))924 }925926 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.927 ///928 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.929 pub fn set_allowance(930 collection: &RefungibleHandle<T>,931 sender: &T::CrossAccountId,932 spender: &T::CrossAccountId,933 token: TokenId,934 amount: u128,935 ) -> DispatchResult {936 if collection.permissions.access() == AccessMode::AllowList {937 collection.check_allowlist(sender)?;938 collection.check_allowlist(spender)?;939 }940941 <PalletCommon<T>>::ensure_correct_receiver(spender)?;942943 if <Balance<T>>::get((collection.id, token, sender)) < amount {944 ensure!(945 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),946 <CommonError<T>>::CantApproveMoreThanOwned947 );948 }949950 // =========951952 Self::set_allowance_unchecked(collection, sender, spender, token, amount);953 Ok(())954 }955956 /// Returns allowance, which should be set after transaction957 fn check_allowed(958 collection: &RefungibleHandle<T>,959 spender: &T::CrossAccountId,960 from: &T::CrossAccountId,961 token: TokenId,962 amount: u128,963 nesting_budget: &dyn Budget,964 ) -> Result<Option<u128>, DispatchError> {965 if spender.conv_eq(from) {966 return Ok(None);967 }968 if collection.permissions.access() == AccessMode::AllowList {969 // `from`, `to` checked in [`transfer`]970 collection.check_allowlist(spender)?;971 }972 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {973 // TODO: should collection owner be allowed to perform this transfer?974 ensure!(975 <PalletStructure<T>>::check_indirectly_owned(976 spender.clone(),977 source.0,978 source.1,979 None,980 nesting_budget981 )?,982 <CommonError<T>>::ApprovedValueTooLow,983 );984 return Ok(None);985 }986 let allowance =987 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);988 if allowance.is_none() {989 ensure!(990 collection.ignores_allowance(spender),991 <CommonError<T>>::ApprovedValueTooLow992 );993 }994 Ok(allowance)995 }996997 /// Transfer RFT token pieces from one account to another.998 ///999 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1000 /// The owner should set allowance for the spender to transfer pieces.1001 ///1002 /// [`transfer`]: struct.Pallet.html#method.transfer1003 pub fn transfer_from(1004 collection: &RefungibleHandle<T>,1005 spender: &T::CrossAccountId,1006 from: &T::CrossAccountId,1007 to: &T::CrossAccountId,1008 token: TokenId,1009 amount: u128,1010 nesting_budget: &dyn Budget,1011 ) -> DispatchResult {1012 let allowance =1013 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10141015 // =========10161017 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1018 if let Some(allowance) = allowance {1019 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1020 }1021 Ok(())1022 }10231024 /// Burn RFT token pieces from the account.1025 ///1026 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1027 /// set allowance for the spender to burn pieces1028 ///1029 /// [`burn`]: struct.Pallet.html#method.burn1030 pub fn burn_from(1031 collection: &RefungibleHandle<T>,1032 spender: &T::CrossAccountId,1033 from: &T::CrossAccountId,1034 token: TokenId,1035 amount: u128,1036 nesting_budget: &dyn Budget,1037 ) -> DispatchResult {1038 let allowance =1039 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10401041 // =========10421043 Self::burn(collection, from, token, amount)?;1044 if let Some(allowance) = allowance {1045 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1046 }1047 Ok(())1048 }10491050 /// Create RFT token.1051 ///1052 /// The sender should be the owner/admin of the collection or collection should be configured1053 /// to allow public minting.1054 ///1055 /// - `data`: Contains list of users who will become the owners of the token pieces and amount1056 /// of token pieces they will receive.1057 pub fn create_item(1058 collection: &RefungibleHandle<T>,1059 sender: &T::CrossAccountId,1060 data: CreateRefungibleExData<T::CrossAccountId>,1061 nesting_budget: &dyn Budget,1062 ) -> DispatchResult {1063 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1064 }10651066 /// Repartition RFT token.1067 ///1068 /// `repartition` will set token balance of the sender and total amount of token pieces.1069 /// Sender should own all of the token pieces. `repartition' could be done even if some1070 /// token pieces were burned before.1071 ///1072 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.1073 pub fn repartition(1074 collection: &RefungibleHandle<T>,1075 owner: &T::CrossAccountId,1076 token: TokenId,1077 amount: u128,1078 ) -> DispatchResult {1079 ensure!(1080 amount <= MAX_REFUNGIBLE_PIECES,1081 <Error<T>>::WrongRefungiblePieces1082 );1083 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1084 // Ensure user owns all pieces1085 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1086 let balance = <Balance<T>>::get((collection.id, token, owner));1087 ensure!(1088 total_pieces == balance,1089 <Error<T>>::RepartitionWhileNotOwningAllPieces1090 );10911092 <Balance<T>>::insert((collection.id, token, owner), amount);1093 <TotalSupply<T>>::insert((collection.id, token), amount);1094 Ok(())1095 }10961097 fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1098 let mut owner = None;1099 let mut count = 0;1100 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1101 count += 1;1102 if count > 1 {1103 return None;1104 }1105 owner = Some(key);1106 }1107 owner1108 }11091110 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1111 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1112 }11131114 pub fn set_collection_properties(1115 collection: &RefungibleHandle<T>,1116 sender: &T::CrossAccountId,1117 properties: Vec<Property>,1118 ) -> DispatchResult {1119 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)1120 }11211122 pub fn delete_collection_properties(1123 collection: &RefungibleHandle<T>,1124 sender: &T::CrossAccountId,1125 property_keys: Vec<PropertyKey>,1126 ) -> DispatchResult {1127 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1128 }11291130 pub fn set_token_property_permissions(1131 collection: &RefungibleHandle<T>,1132 sender: &T::CrossAccountId,1133 property_permissions: Vec<PropertyKeyPermission>,1134 ) -> DispatchResult {1135 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1136 }1137}pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -3,7 +3,7 @@
//! Autogenerated weights for pallet_refungible
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-06-27, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! DATE: 2022-07-20, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
// Executed Command:
@@ -49,6 +49,9 @@
fn transfer_from_removing() -> Weight;
fn transfer_from_creating_removing() -> Weight;
fn burn_from() -> Weight;
+ fn set_token_property_permissions(b: u32, ) -> Weight;
+ fn set_token_properties(b: u32, ) -> Weight;
+ fn delete_token_properties(b: u32, ) -> Weight;
fn repartition_item() -> Weight;
}
@@ -62,7 +65,7 @@
// Storage: Refungible TokenData (r:0 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn create_item() -> Weight {
- (17_553_000 as Weight)
+ (21_310_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
@@ -73,9 +76,9 @@
// Storage: Refungible TokenData (r:0 w:4)
// Storage: Refungible Owned (r:0 w:4)
fn create_multiple_items(b: u32, ) -> Weight {
- (10_654_000 as Weight)
- // Standard Error: 1_000
- .saturating_add((5_114_000 as Weight).saturating_mul(b as Weight))
+ (9_552_000 as Weight)
+ // Standard Error: 2_000
+ .saturating_add((7_056_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(b as Weight)))
@@ -87,9 +90,9 @@
// Storage: Refungible TokenData (r:0 w:4)
// Storage: Refungible Owned (r:0 w:4)
fn create_multiple_items_ex_multiple_items(b: u32, ) -> Weight {
- (3_587_000 as Weight)
+ (4_857_000 as Weight)
// Standard Error: 2_000
- .saturating_add((7_931_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add((9_838_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
@@ -102,9 +105,9 @@
// Storage: Refungible Balance (r:0 w:4)
// Storage: Refungible Owned (r:0 w:4)
fn create_multiple_items_ex_multiple_owners(b: u32, ) -> Weight {
- (1_980_000 as Weight)
+ (11_335_000 as Weight)
// Standard Error: 2_000
- .saturating_add((6_305_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add((6_784_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
@@ -115,7 +118,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn burn_item_partial() -> Weight {
- (21_010_000 as Weight)
+ (21_239_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
@@ -125,14 +128,15 @@
// Storage: Refungible TokensBurnt (r:1 w:1)
// Storage: Refungible TokenData (r:0 w:1)
// Storage: Refungible Owned (r:0 w:1)
+ // Storage: Refungible TokenProperties (r:0 w:1)
fn burn_item_fully() -> Weight {
- (28_413_000 as Weight)
+ (29_426_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
- .saturating_add(T::DbWeight::get().writes(6 as Weight))
+ .saturating_add(T::DbWeight::get().writes(7 as Weight))
}
// Storage: Refungible Balance (r:2 w:2)
fn transfer_normal() -> Weight {
- (17_513_000 as Weight)
+ (17_743_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
@@ -140,7 +144,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_creating() -> Weight {
- (20_469_000 as Weight)
+ (20_699_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
@@ -148,7 +152,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_removing() -> Weight {
- (22_472_000 as Weight)
+ (22_833_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
@@ -156,21 +160,21 @@
// Storage: Refungible AccountBalance (r:2 w:2)
// Storage: Refungible Owned (r:0 w:2)
fn transfer_creating_removing() -> Weight {
- (24_866_000 as Weight)
+ (24_936_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
// Storage: Refungible Balance (r:1 w:0)
// Storage: Refungible Allowance (r:0 w:1)
fn approve() -> Weight {
- (13_475_000 as Weight)
+ (13_446_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Refungible Allowance (r:1 w:1)
// Storage: Refungible Balance (r:2 w:2)
fn transfer_from_normal() -> Weight {
- (24_707_000 as Weight)
+ (24_777_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
@@ -179,7 +183,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_from_creating() -> Weight {
- (27_812_000 as Weight)
+ (28_483_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(5 as Weight))
}
@@ -188,7 +192,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_from_removing() -> Weight {
- (29_966_000 as Weight)
+ (29_896_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(5 as Weight))
}
@@ -197,7 +201,7 @@
// Storage: Refungible AccountBalance (r:2 w:2)
// Storage: Refungible Owned (r:0 w:2)
fn transfer_from_creating_removing() -> Weight {
- (31_660_000 as Weight)
+ (32_070_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(7 as Weight))
}
@@ -208,15 +212,42 @@
// Storage: Refungible TokensBurnt (r:1 w:1)
// Storage: Refungible TokenData (r:0 w:1)
// Storage: Refungible Owned (r:0 w:1)
+ // Storage: Refungible TokenProperties (r:0 w:1)
fn burn_from() -> Weight {
- (36_248_000 as Weight)
+ (36_789_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
- .saturating_add(T::DbWeight::get().writes(7 as Weight))
+ .saturating_add(T::DbWeight::get().writes(8 as Weight))
+ }
+ // Storage: Common CollectionPropertyPermissions (r:1 w:1)
+ fn set_token_property_permissions(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 62_000
+ .saturating_add((15_803_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Common CollectionPropertyPermissions (r:1 w:0)
+ // Storage: Refungible TokenProperties (r:1 w:1)
+ fn set_token_properties(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 1_668_000
+ .saturating_add((302_308_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Common CollectionPropertyPermissions (r:1 w:0)
+ // Storage: Refungible TokenProperties (r:1 w:1)
+ fn delete_token_properties(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 1_619_000
+ .saturating_add((294_574_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Refungible TotalSupply (r:1 w:1)
// Storage: Refungible Balance (r:1 w:1)
fn repartition_item() -> Weight {
- (8_226_000 as Weight)
+ (8_325_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
@@ -231,7 +262,7 @@
// Storage: Refungible TokenData (r:0 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn create_item() -> Weight {
- (17_553_000 as Weight)
+ (21_310_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
}
@@ -242,9 +273,9 @@
// Storage: Refungible TokenData (r:0 w:4)
// Storage: Refungible Owned (r:0 w:4)
fn create_multiple_items(b: u32, ) -> Weight {
- (10_654_000 as Weight)
- // Standard Error: 1_000
- .saturating_add((5_114_000 as Weight).saturating_mul(b as Weight))
+ (9_552_000 as Weight)
+ // Standard Error: 2_000
+ .saturating_add((7_056_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
.saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(b as Weight)))
@@ -256,9 +287,9 @@
// Storage: Refungible TokenData (r:0 w:4)
// Storage: Refungible Owned (r:0 w:4)
fn create_multiple_items_ex_multiple_items(b: u32, ) -> Weight {
- (3_587_000 as Weight)
+ (4_857_000 as Weight)
// Standard Error: 2_000
- .saturating_add((7_931_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add((9_838_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
@@ -271,9 +302,9 @@
// Storage: Refungible Balance (r:0 w:4)
// Storage: Refungible Owned (r:0 w:4)
fn create_multiple_items_ex_multiple_owners(b: u32, ) -> Weight {
- (1_980_000 as Weight)
+ (11_335_000 as Weight)
// Standard Error: 2_000
- .saturating_add((6_305_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add((6_784_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
.saturating_add(RocksDbWeight::get().writes(3 as Weight))
@@ -284,7 +315,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn burn_item_partial() -> Weight {
- (21_010_000 as Weight)
+ (21_239_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
@@ -294,14 +325,15 @@
// Storage: Refungible TokensBurnt (r:1 w:1)
// Storage: Refungible TokenData (r:0 w:1)
// Storage: Refungible Owned (r:0 w:1)
+ // Storage: Refungible TokenProperties (r:0 w:1)
fn burn_item_fully() -> Weight {
- (28_413_000 as Weight)
+ (29_426_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
- .saturating_add(RocksDbWeight::get().writes(6 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(7 as Weight))
}
// Storage: Refungible Balance (r:2 w:2)
fn transfer_normal() -> Weight {
- (17_513_000 as Weight)
+ (17_743_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
}
@@ -309,7 +341,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_creating() -> Weight {
- (20_469_000 as Weight)
+ (20_699_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
@@ -317,7 +349,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_removing() -> Weight {
- (22_472_000 as Weight)
+ (22_833_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
@@ -325,21 +357,21 @@
// Storage: Refungible AccountBalance (r:2 w:2)
// Storage: Refungible Owned (r:0 w:2)
fn transfer_creating_removing() -> Weight {
- (24_866_000 as Weight)
+ (24_936_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
}
// Storage: Refungible Balance (r:1 w:0)
// Storage: Refungible Allowance (r:0 w:1)
fn approve() -> Weight {
- (13_475_000 as Weight)
+ (13_446_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Refungible Allowance (r:1 w:1)
// Storage: Refungible Balance (r:2 w:2)
fn transfer_from_normal() -> Weight {
- (24_707_000 as Weight)
+ (24_777_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(3 as Weight))
}
@@ -348,7 +380,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_from_creating() -> Weight {
- (27_812_000 as Weight)
+ (28_483_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
@@ -357,7 +389,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_from_removing() -> Weight {
- (29_966_000 as Weight)
+ (29_896_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
@@ -366,7 +398,7 @@
// Storage: Refungible AccountBalance (r:2 w:2)
// Storage: Refungible Owned (r:0 w:2)
fn transfer_from_creating_removing() -> Weight {
- (31_660_000 as Weight)
+ (32_070_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(7 as Weight))
}
@@ -377,15 +409,42 @@
// Storage: Refungible TokensBurnt (r:1 w:1)
// Storage: Refungible TokenData (r:0 w:1)
// Storage: Refungible Owned (r:0 w:1)
+ // Storage: Refungible TokenProperties (r:0 w:1)
fn burn_from() -> Weight {
- (36_248_000 as Weight)
+ (36_789_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
- .saturating_add(RocksDbWeight::get().writes(7 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(8 as Weight))
+ }
+ // Storage: Common CollectionPropertyPermissions (r:1 w:1)
+ fn set_token_property_permissions(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 62_000
+ .saturating_add((15_803_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Common CollectionPropertyPermissions (r:1 w:0)
+ // Storage: Refungible TokenProperties (r:1 w:1)
+ fn set_token_properties(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 1_668_000
+ .saturating_add((302_308_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
+ // Storage: Common CollectionPropertyPermissions (r:1 w:0)
+ // Storage: Refungible TokenProperties (r:1 w:1)
+ fn delete_token_properties(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 1_619_000
+ .saturating_add((294_574_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
// Storage: Refungible TotalSupply (r:1 w:1)
// Storage: Refungible Balance (r:1 w:1)
fn repartition_item() -> Weight {
- (8_226_000 as Weight)
+ (8_325_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
}
primitives/data-structs/Cargo.tomldiffbeforeafterboth--- a/primitives/data-structs/Cargo.toml
+++ b/primitives/data-structs/Cargo.toml
@@ -6,7 +6,7 @@
license = 'GPLv3'
homepage = "https://unique.network"
repository = 'https://github.com/UniqueNetwork/unique-chain'
-version = '0.1.0'
+version = '0.1.1'
[dependencies]
scale-info = { version = "2.0.1", default-features = false, features = [
primitives/data-structs/Changelog.mddiffbeforeafterboth--- /dev/null
+++ b/primitives/data-structs/Changelog.md
@@ -0,0 +1,3 @@
+### 0.1.1
+---
+* Added fields with properties to `CreateReFungibleData` and `CreateRefungibleExData`.
\ No newline at end of file
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -534,7 +534,12 @@
#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
#[derivative(Debug(format_with = "bounded::vec_debug"))]
pub const_data: BoundedVec<u8, CustomDataLimit>,
+
pub pieces: u128,
+
+ #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
+ #[derivative(Debug(format_with = "bounded::vec_debug"))]
+ pub properties: CollectionPropertiesVec,
}
#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
@@ -568,6 +573,8 @@
pub const_data: BoundedVec<u8, CustomDataLimit>,
#[derivative(Debug(format_with = "bounded::map_debug"))]
pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,
+ #[derivative(Debug(format_with = "bounded::vec_debug"))]
+ pub properties: CollectionPropertiesVec,
}
#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
tests/src/createMultipleItems.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -376,14 +376,26 @@
// ReFungible
const collectionIdReFungible =
await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
- const argsReFungible = [
- {ReFungible: ['1'.repeat(2049), 10]},
- {ReFungible: ['2'.repeat(2049), 10]},
- {ReFungible: ['3'.repeat(2049), 10]},
- ];
- const createMultipleItemsTxFungible = api.tx.unique
- .createMultipleItems(collectionIdReFungible, normalizeAccountId(alice.address), argsReFungible);
- await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTxFungible)).to.be.rejected;
+ {
+ const argsReFungible = [
+ {ReFungible: ['1'.repeat(2049), 10, []]},
+ {ReFungible: ['2'.repeat(2049), 10, []]},
+ {ReFungible: ['3'.repeat(2049), 10, []]},
+ ];
+ const createMultipleItemsTxFungible = api.tx.unique
+ .createMultipleItems(collectionIdReFungible, normalizeAccountId(alice.address), argsReFungible);
+ await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTxFungible)).to.be.rejected;
+ }
+ {
+ const argsReFungible = [
+ {ReFungible: {properties: [{key: 'key', value: 'A'.repeat(32769)}]}},
+ {ReFungible: {properties: [{key: 'key', value: 'B'.repeat(32769)}]}},
+ {ReFungible: {properties: [{key: 'key', value: 'C'.repeat(32769)}]}},
+ ];
+ const createMultipleItemsTxFungible = api.tx.unique
+ .createMultipleItems(collectionIdReFungible, normalizeAccountId(alice.address), argsReFungible);
+ await expect(submitTransactionExpectFailAsync(alice, createMultipleItemsTxFungible)).to.be.rejected;
+ }
});
});
tests/src/interfaces/augment-api-query.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-query.ts
+++ b/tests/src/interfaces/augment-api-query.ts
@@ -408,6 +408,7 @@
**/
owned: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, arg3: u32 | AnyNumber | Uint8Array) => Observable<bool>, [u32, PalletEvmAccountBasicCrossAccountIdRepr, u32]> & QueryableStorageEntry<ApiType, [u32, PalletEvmAccountBasicCrossAccountIdRepr, u32]>;
tokenData: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<PalletRefungibleItemData>, [u32, u32]> & QueryableStorageEntry<ApiType, [u32, u32]>;
+ tokenProperties: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<UpDataStructsProperties>, [u32, u32]> & QueryableStorageEntry<ApiType, [u32, u32]>;
tokensBurnt: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<u32>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
tokensMinted: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<u32>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
totalSupply: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<u128>, [u32, u32]> & QueryableStorageEntry<ApiType, [u32, u32]>;
tests/src/interfaces/default/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -2461,12 +2461,14 @@
export interface UpDataStructsCreateReFungibleData extends Struct {
readonly constData: Bytes;
readonly pieces: u128;
+ readonly properties: Vec<UpDataStructsProperty>;
}
/** @name UpDataStructsCreateRefungibleExData */
export interface UpDataStructsCreateRefungibleExData extends Struct {
readonly constData: Bytes;
readonly users: BTreeMap<PalletEvmAccountBasicCrossAccountIdRepr, u128>;
+ readonly properties: Vec<UpDataStructsProperty>;
}
/** @name UpDataStructsNestingPermissions */
tests/src/interfaces/lookup.tsdiffbeforeafterboth--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -1502,7 +1502,8 @@
**/
UpDataStructsCreateReFungibleData: {
constData: 'Bytes',
- pieces: 'u128'
+ pieces: 'u128',
+ properties: 'Vec<UpDataStructsProperty>'
},
/**
* Lookup193: up_data_structs::CreateItemExData<pallet_evm::account::BasicCrossAccountIdRepr<sp_core::crypto::AccountId32>>
@@ -1527,7 +1528,8 @@
**/
UpDataStructsCreateRefungibleExData: {
constData: 'Bytes',
- users: 'BTreeMap<PalletEvmAccountBasicCrossAccountIdRepr, u128>'
+ users: 'BTreeMap<PalletEvmAccountBasicCrossAccountIdRepr, u128>',
+ properties: 'Vec<UpDataStructsProperty>'
},
/**
* Lookup204: pallet_unique_scheduler::pallet::Call<T>
tests/src/interfaces/types-lookup.tsdiffbeforeafterboth--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -1629,6 +1629,7 @@
export interface UpDataStructsCreateReFungibleData extends Struct {
readonly constData: Bytes;
readonly pieces: u128;
+ readonly properties: Vec<UpDataStructsProperty>;
}
/** @name UpDataStructsCreateItemExData (193) */
@@ -1654,6 +1655,7 @@
export interface UpDataStructsCreateRefungibleExData extends Struct {
readonly constData: Bytes;
readonly users: BTreeMap<PalletEvmAccountBasicCrossAccountIdRepr, u128>;
+ readonly properties: Vec<UpDataStructsProperty>;
}
/** @name PalletUniqueSchedulerCall (204) */
tests/src/nesting/properties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/properties.test.ts
+++ b/tests/src/nesting/properties.test.ts
@@ -2,6 +2,7 @@
import usingApi, {executeTransaction} from '../substrate/substrate-api';
import {
addCollectionAdminExpectSuccess,
+ CollectionMode,
createCollectionExpectSuccess,
setCollectionPermissionsExpectSuccess,
createItemExpectSuccess,
@@ -23,9 +24,9 @@
});
});
- it('Makes sure collectionById supplies required fields', async () => {
+ async function testMakeSureSuppliesRequired(mode: CollectionMode) {
await usingApi(async api => {
- const collectionId = await createCollectionExpectSuccess();
+ const collectionId = await createCollectionExpectSuccess({mode: mode});
const collectionOption = await api.rpc.unique.collectionById(collectionId);
expect(collectionOption.isSome).to.be.true;
@@ -57,7 +58,15 @@
expect(collection.tokenPropertyPermissions.toHuman()).to.be.deep.equal(propertyPermissions);
expect(collection.properties.toHuman()).to.be.deep.equal(collectionProperties);
});
+ }
+
+ it('Makes sure collectionById supplies required fields for NFT', async () => {
+ await testMakeSureSuppliesRequired({type: 'NFT'});
});
+
+ it('Makes sure collectionById supplies required fields for ReFungible', async () => {
+ await testMakeSureSuppliesRequired({type: 'ReFungible'});
+ });
});
// ---------- COLLECTION PROPERTIES
@@ -79,9 +88,10 @@
});
});
- it('Sets properties for a collection', async () => {
+
+ async function testSetsPropertiesForCollection(mode: string) {
await usingApi(async api => {
- const events = await executeTransaction(api, bob, api.tx.unique.createCollectionEx({mode: 'NFT'}));
+ const events = await executeTransaction(api, bob, api.tx.unique.createCollectionEx({mode: mode}));
const {collectionId} = getCreateCollectionResult(events);
// As owner
@@ -106,48 +116,54 @@
{key: 'black_hole', value: ''},
]);
});
+ }
+ it('Sets properties for a NFT collection', async () => {
+ await testSetsPropertiesForCollection('NFT');
});
+ it('Sets properties for a ReFungible collection', async () => {
+ await testSetsPropertiesForCollection('ReFungible');
+ });
- it('Check valid names for collection properties keys', async () => {
+ async function testCheckValidNames(mode: string) {
await usingApi(async api => {
- const events = await executeTransaction(api, bob, api.tx.unique.createCollectionEx({mode: 'NFT'}));
+ const events = await executeTransaction(api, bob, api.tx.unique.createCollectionEx({mode: mode}));
const {collectionId} = getCreateCollectionResult(events);
-
+
// alpha symbols
await expect(executeTransaction(
api,
bob,
api.tx.unique.setCollectionProperties(collectionId, [{key: 'alpha'}]),
)).to.not.be.rejected;
-
+
// numeric symbols
await expect(executeTransaction(
api,
bob,
api.tx.unique.setCollectionProperties(collectionId, [{key: '123'}]),
)).to.not.be.rejected;
-
+
// underscore symbol
await expect(executeTransaction(
api,
bob,
api.tx.unique.setCollectionProperties(collectionId, [{key: 'black_hole'}]),
)).to.not.be.rejected;
-
+
// dash symbol
await expect(executeTransaction(
api,
bob,
api.tx.unique.setCollectionProperties(collectionId, [{key: 'semi-automatic'}]),
)).to.not.be.rejected;
-
+
// underscore symbol
await expect(executeTransaction(
api,
bob,
api.tx.unique.setCollectionProperties(collectionId, [{key: 'build.rs'}]),
)).to.not.be.rejected;
-
+
const propertyKeys = ['alpha', '123', 'black_hole', 'semi-automatic', 'build.rs'];
const properties = (await api.rpc.unique.collectionProperties(collectionId, propertyKeys)).toHuman();
expect(properties).to.be.deep.equal([
@@ -158,54 +174,72 @@
{key: 'build.rs', value: ''},
]);
});
+ }
+ it('Check valid names for NFT collection properties keys', async () => {
+ await testCheckValidNames('NFT');
+ });
+ it('Check valid names for ReFungible collection properties keys', async () => {
+ await testCheckValidNames('ReFungible');
});
- it('Changes properties of a collection', async () => {
+ async function testChangesProperties(mode: CollectionMode) {
await usingApi(async api => {
- const collection = await createCollectionExpectSuccess();
-
+ const collection = await createCollectionExpectSuccess({mode: mode});
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'come bond'}, {key: 'black_hole'}]),
)).to.not.be.rejected;
-
+
// Mutate the properties
await expect(executeTransaction(
api,
alice,
api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'bonded'}, {key: 'black_hole', value: 'LIGO'}]),
)).to.not.be.rejected;
-
+
const properties = (await api.rpc.unique.collectionProperties(collection, ['electron', 'black_hole'])).toHuman();
expect(properties).to.be.deep.equal([
{key: 'electron', value: 'bonded'},
{key: 'black_hole', value: 'LIGO'},
]);
});
+ }
+ it('Changes properties of a NFT collection', async () => {
+ await testChangesProperties({type: 'NFT'});
+ });
+ it('Changes properties of a ReFungible collection', async () => {
+ await testChangesProperties({type: 'ReFungible'});
});
- it('Deletes properties of a collection', async () => {
+ async function testDeleteProperties(mode: CollectionMode) {
await usingApi(async api => {
- const collection = await createCollectionExpectSuccess();
-
+ const collection = await createCollectionExpectSuccess({mode: mode});
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]),
)).to.not.be.rejected;
-
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.deleteCollectionProperties(collection, ['electron']),
)).to.not.be.rejected;
-
+
const properties = (await api.rpc.unique.collectionProperties(collection, ['electron', 'black_hole'])).toHuman();
expect(properties).to.be.deep.equal([
{key: 'black_hole', value: 'LIGO'},
]);
- });
+ });
+ }
+ it('Deletes properties of a NFT collection', async () => {
+ await testDeleteProperties({type: 'NFT'});
+ });
+ it('Deletes properties of a ReFungible collection', async () => {
+ await testDeleteProperties({type: 'ReFungible'});
});
});
@@ -217,10 +251,10 @@
});
});
- it('Fails to set properties in a collection if not its onwer/administrator', async () => {
+ async function testFailsSetPropertiesIfNotOwnerOrAdmin(mode: CollectionMode) {
await usingApi(async api => {
- const collection = await createCollectionExpectSuccess();
-
+ const collection = await createCollectionExpectSuccess({mode: mode});
+
await expect(executeTransaction(
api,
bob,
@@ -230,14 +264,20 @@
const properties = (await api.query.common.collectionProperties(collection)).toJSON();
expect(properties.map).to.be.empty;
expect(properties.consumedSpace).to.equal(0);
- });
+ });
+ }
+ it('Fails to set properties in a NFT collection if not its onwer/administrator', async () => {
+ await testFailsSetPropertiesIfNotOwnerOrAdmin({type: 'NFT'});
});
+ it('Fails to set properties in a ReFungible collection if not its onwer/administrator', async () => {
+ await testFailsSetPropertiesIfNotOwnerOrAdmin({type: 'ReFungible'});
+ });
- it('Fails to set properties that exceed the limits', async () => {
+ async function testFailsSetPropertiesThatExeedLimits(mode: CollectionMode) {
await usingApi(async api => {
- const collection = await createCollectionExpectSuccess();
+ const collection = await createCollectionExpectSuccess({mode: mode});
const spaceLimit = (await api.query.common.collectionProperties(collection)).toJSON().spaceLimit as number;
-
+
// Mute the general tx parsing error, too many bytes to process
{
console.error = () => {};
@@ -247,10 +287,10 @@
api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))}]),
)).to.be.rejected;
}
-
+
let properties = (await api.rpc.unique.collectionProperties(collection, ['electron'])).toJSON();
expect(properties).to.be.empty;
-
+
await expect(executeTransaction(
api,
alice,
@@ -259,16 +299,22 @@
{key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))},
]),
)).to.be.rejectedWith(/common\.NoSpaceForProperty/);
-
+
properties = (await api.rpc.unique.collectionProperties(collection, ['electron', 'black hole'])).toJSON();
expect(properties).to.be.empty;
- });
+ });
+ }
+ it('Fails to set properties that exceed the limits (NFT)', async () => {
+ await testFailsSetPropertiesThatExeedLimits({type: 'NFT'});
+ });
+ it('Fails to set properties that exceed the limits (ReFungible)', async () => {
+ await testFailsSetPropertiesThatExeedLimits({type: 'ReFungible'});
});
- it('Fails to set more properties than it is allowed', async () => {
+ async function testFailsSetMorePropertiesThanAllowed(mode: CollectionMode) {
await usingApi(async api => {
- const collection = await createCollectionExpectSuccess();
-
+ const collection = await createCollectionExpectSuccess({mode: mode});
+
const propertiesToBeSet = [];
for (let i = 0; i < 65; i++) {
propertiesToBeSet.push({
@@ -276,29 +322,35 @@
value: Math.random() > 0.5 ? 'high' : 'low',
});
}
-
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setCollectionProperties(collection, propertiesToBeSet),
)).to.be.rejectedWith(/common\.PropertyLimitReached/);
-
+
const properties = (await api.query.common.collectionProperties(collection)).toJSON();
expect(properties.map).to.be.empty;
expect(properties.consumedSpace).to.equal(0);
- });
+ });
+ }
+ it('Fails to set more properties than it is allowed (NFT)', async () => {
+ await testFailsSetMorePropertiesThanAllowed({type: 'NFT'});
});
-
- it('Fails to set properties with invalid names', async () => {
+ it('Fails to set more properties than it is allowed (ReFungible)', async () => {
+ await testFailsSetMorePropertiesThanAllowed({type: 'ReFungible'});
+ });
+
+ async function testFailsSetPropertiesWithInvalidNames(mode: CollectionMode) {
await usingApi(async api => {
- const collection = await createCollectionExpectSuccess();
-
+ const collection = await createCollectionExpectSuccess({mode: mode});
+
const invalidProperties = [
[{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],
[{key: 'Mr/Sandman', value: 'Bring me a gene'}],
[{key: 'déjà vu', value: 'hmm...'}],
];
-
+
for (let i = 0; i < invalidProperties.length; i++) {
await expect(executeTransaction(
api,
@@ -306,13 +358,13 @@
api.tx.unique.setCollectionProperties(collection, invalidProperties[i]),
), `on rejecting the new badly-named property #${i}`).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
}
-
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setCollectionProperties(collection, [{key: '', value: 'nothing must not exist'}]),
), 'on rejecting an unnamed property').to.be.rejectedWith(/common\.EmptyPropertyKey/);
-
+
await expect(executeTransaction(
api,
alice,
@@ -320,14 +372,14 @@
{key: 'CRISPR-Cas9', value: 'rewriting nature!'},
]),
), 'on setting the correctly-but-still-badly-named property').to.not.be.rejected;
-
+
const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');
-
+
const properties = (await api.rpc.unique.collectionProperties(collection, keys)).toHuman();
expect(properties).to.be.deep.equal([
{key: 'CRISPR-Cas9', value: 'rewriting nature!'},
]);
-
+
for (let i = 0; i < invalidProperties.length; i++) {
await expect(executeTransaction(
api,
@@ -336,7 +388,13 @@
), `on trying to delete the non-existent badly-named property #${i}`).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
}
});
+ }
+ it('Fails to set properties with invalid names (NFT)', async () => {
+ await testFailsSetPropertiesWithInvalidNames({type: 'NFT'});
});
+ it('Fails to set properties with invalid names (ReFungible)', async () => {
+ await testFailsSetPropertiesWithInvalidNames({type: 'ReFungible'});
+ });
});
// ---------- ACCESS RIGHTS
@@ -357,54 +415,66 @@
});
});
- it('Sets access rights to properties of a collection', async () => {
+ async function testSetsAccessRightsToProperties(mode: CollectionMode) {
await usingApi(async api => {
- const collection = await createCollectionExpectSuccess();
-
+ const collection = await createCollectionExpectSuccess({mode: mode});
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: true}}]),
)).to.not.be.rejected;
-
+
await addCollectionAdminExpectSuccess(alice, collection, bob.address);
-
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'mindgame', permission: {collectionAdmin: true, tokenOwner: false}}]),
)).to.not.be.rejected;
-
+
const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery', 'mindgame'])).toHuman();
expect(propertyRights).to.be.deep.equal([
{key: 'skullduggery', permission: {'mutable': true, 'collectionAdmin': false, 'tokenOwner': false}},
{key: 'mindgame', permission: {'mutable': false, 'collectionAdmin': true, 'tokenOwner': false}},
]);
- });
+ });
+ }
+ it('Sets access rights to properties of a collection (NFT)', async () => {
+ await testSetsAccessRightsToProperties({type: 'NFT'});
});
+ it('Sets access rights to properties of a collection (ReFungible)', async () => {
+ await testSetsAccessRightsToProperties({type: 'ReFungible'});
+ });
- it('Changes access rights to properties of a collection', async () => {
+ async function testChangesAccessRightsToProperty(mode: CollectionMode) {
await usingApi(async api => {
- const collection = await createCollectionExpectSuccess();
-
+ const collection = await createCollectionExpectSuccess({mode: mode});
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: true, collectionAdmin: true}}]),
)).to.not.be.rejected;
-
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]),
)).to.not.be.rejected;
-
+
const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery'])).toHuman();
expect(propertyRights).to.be.deep.equal([
{key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},
]);
});
+ }
+ it('Changes access rights to properties of a NFT collection', async () => {
+ await testChangesAccessRightsToProperty({type: 'NFT'});
});
+ it('Changes access rights to properties of a ReFungible collection', async () => {
+ await testChangesAccessRightsToProperty({type: 'ReFungible'});
+ });
});
describe('Negative Integration Test: Access Rights to Token Properties', () => {
@@ -415,25 +485,31 @@
});
});
- it('Prevents from setting access rights to properties of a collection if not an onwer/admin', async () => {
+ async function testPreventsFromSettingAccessRightsNotAdminOrOwner(mode: CollectionMode) {
await usingApi(async api => {
- const collection = await createCollectionExpectSuccess();
-
+ const collection = await createCollectionExpectSuccess({mode: mode});
+
await expect(executeTransaction(
api,
bob,
api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: true, tokenOwner: true}}]),
)).to.be.rejectedWith(/common\.NoPermission/);
-
+
const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery'])).toJSON();
expect(propertyRights).to.be.empty;
});
+ }
+ it('Prevents from setting access rights to properties of a NFT collection if not an onwer/admin', async () => {
+ await testPreventsFromSettingAccessRightsNotAdminOrOwner({type: 'NFT'});
});
+ it('Prevents from setting access rights to properties of a ReFungible collection if not an onwer/admin', async () => {
+ await testPreventsFromSettingAccessRightsNotAdminOrOwner({type: 'ReFungible'});
+ });
- it('Prevents from adding too many possible properties', async () => {
+ async function testPreventFromAddingTooManyPossibleProperties(mode: CollectionMode) {
await usingApi(async api => {
- const collection = await createCollectionExpectSuccess();
-
+ const collection = await createCollectionExpectSuccess({mode: mode});
+
const constitution = [];
for (let i = 0; i < 65; i++) {
constitution.push({
@@ -441,51 +517,63 @@
permission: Math.random() > 0.5 ? {mutable: true, collectionAdmin: true, tokenOwner: true} : {},
});
}
-
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setTokenPropertyPermissions(collection, constitution),
)).to.be.rejectedWith(/common\.PropertyLimitReached/);
-
+
const propertyRights = (await api.query.common.collectionPropertyPermissions(collection)).toJSON();
expect(propertyRights).to.be.empty;
- });
+ });
+ }
+ it('Prevents from adding too many possible properties (NFT)', async () => {
+ await testPreventFromAddingTooManyPossibleProperties({type: 'NFT'});
});
+ it('Prevents from adding too many possible properties (ReFungible)', async () => {
+ await testPreventFromAddingTooManyPossibleProperties({type: 'ReFungible'});
+ });
- it('Prevents access rights to be modified if constant', async () => {
+ async function testPreventAccessRightsModifiedIfConstant(mode: CollectionMode) {
await usingApi(async api => {
- const collection = await createCollectionExpectSuccess();
-
+ const collection = await createCollectionExpectSuccess({mode: mode});
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]),
)).to.not.be.rejected;
-
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {}}]),
)).to.be.rejectedWith(/common\.NoPermission/);
-
+
const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery'])).toHuman();
expect(propertyRights).to.deep.equal([
{key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},
]);
- });
+ });
+ }
+ it('Prevents access rights to be modified if constant (NFT)', async () => {
+ await testPreventAccessRightsModifiedIfConstant({type: 'NFT'});
+ });
+ it('Prevents access rights to be modified if constant (ReFungible)', async () => {
+ await testPreventAccessRightsModifiedIfConstant({type: 'ReFungible'});
});
- it('Prevents adding properties with invalid names', async () => {
+ async function testPreventsAddingPropertiesWithInvalidNames(mode: CollectionMode) {
await usingApi(async api => {
- const collection = await createCollectionExpectSuccess();
-
+ const collection = await createCollectionExpectSuccess({mode: mode});
+
const invalidProperties = [
[{key: 'skullduggery', permission: {tokenOwner: true}}, {key: 'im possible', permission: {collectionAdmin: true}}],
[{key: 'G#4', permission: {tokenOwner: true}}],
[{key: 'HÆMILTON', permission: {mutable: false, collectionAdmin: true, tokenOwner: true}}],
];
-
+
for (let i = 0; i < invalidProperties.length; i++) {
await expect(executeTransaction(
api,
@@ -493,13 +581,13 @@
api.tx.unique.setTokenPropertyPermissions(collection, invalidProperties[i]),
), `on setting the new badly-named property #${i}`).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
}
-
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setTokenPropertyPermissions(collection, [{key: '', permission: {}}]),
), 'on rejecting an unnamed property').to.be.rejectedWith(/common\.EmptyPropertyKey/);
-
+
const correctKey = '--0x03116e387820CA05'; // PolkadotJS would parse this as an already encoded hex-string
await expect(executeTransaction(
api,
@@ -508,30 +596,33 @@
{key: correctKey, permission: {collectionAdmin: true}},
]),
), 'on setting the correctly-but-still-badly-named property').to.not.be.rejected;
-
+
const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat(correctKey).concat('');
-
+
const propertyRights = (await api.rpc.unique.propertyPermissions(collection, keys)).toHuman();
expect(propertyRights).to.be.deep.equal([
{key: correctKey, permission: {mutable: false, collectionAdmin: true, tokenOwner: false}},
]);
});
+ }
+ it('Prevents adding properties with invalid names (NFT)', async () => {
+ await testPreventsAddingPropertiesWithInvalidNames({type: 'NFT'});
+ });
+ it('Prevents adding properties with invalid names (ReFungible)', async () => {
+ await testPreventsAddingPropertiesWithInvalidNames({type: 'ReFungible'});
});
});
// ---------- TOKEN PROPERTIES
describe('Integration Test: Token Properties', () => {
- let collection: number;
- let token: number;
- let nestedToken: number;
let permissions: {permission: any, signers: IKeyringPair[]}[];
before(async () => {
await usingApi(async (api, privateKeyWrapper) => {
- alice = privateKeyWrapper('//Alice');
- bob = privateKeyWrapper('//Bob');
- charlie = privateKeyWrapper('//Charlie');
+ alice = privateKeyWrapper('//Alice'); // collection owner
+ bob = privateKeyWrapper('//Bob'); // collection admin
+ charlie = privateKeyWrapper('//Charlie'); // token owner
permissions = [
{permission: {mutable: true, collectionAdmin: true}, signers: [alice, bob]},
@@ -543,36 +634,34 @@
];
});
});
-
- beforeEach(async () => {
- await usingApi(async () => {
- collection = await createCollectionExpectSuccess();
- await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
-
- token = await createItemExpectSuccess(alice, collection, 'NFT');
- nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, token)});
-
- await addCollectionAdminExpectSuccess(alice, collection, bob.address);
- await transferExpectSuccess(collection, token, alice, charlie);
- });
- });
- it('Reads yet empty properties of a token', async () => {
+ async function testReadsYetEmptyProperties(mode: CollectionMode) {
await usingApi(async api => {
- const collection = await createCollectionExpectSuccess();
- const token = await createItemExpectSuccess(alice, collection, 'NFT');
+ const collection = await createCollectionExpectSuccess({mode: mode});
+ const token = await createItemExpectSuccess(alice, collection, mode.type);
const properties = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();
expect(properties.map).to.be.empty;
expect(properties.consumedSpace).to.be.equal(0);
-
+
const tokenData = (await api.rpc.unique.tokenData(collection, token, ['anything'])).toJSON().properties;
expect(tokenData).to.be.empty;
});
+ }
+ it('Reads yet empty properties of a token (NFT)', async () => {
+ await testReadsYetEmptyProperties({type: 'NFT'});
});
+ it('Reads yet empty properties of a token (ReFungible)', async () => {
+ await testReadsYetEmptyProperties({type: 'ReFungible'});
+ });
- it('Assigns properties to a token according to permissions', async () => {
+ async function testAssignPropertiesAccordingToPermissions(mode: CollectionMode, pieces: number) {
await usingApi(async api => {
+ const collection = await createCollectionExpectSuccess({mode: mode});
+ const token = await createItemExpectSuccess(alice, collection, mode.type);
+ await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+ await transferExpectSuccess(collection, token, alice, charlie, pieces, mode.type);
+
const propertyKeys: string[] = [];
let i = 0;
for (const permission of permissions) {
@@ -603,10 +692,21 @@
expect(tokensData[i].value).to.be.equal('Serotonin increase');
}
});
+ }
+ it('Assigns properties to a token according to permissions (NFT)', async () => {
+ await testAssignPropertiesAccordingToPermissions({type: 'NFT'}, 1);
+ });
+ it('Assigns properties to a token according to permissions (ReFungible)', async () => {
+ await testAssignPropertiesAccordingToPermissions({type: 'ReFungible'}, 100);
});
- it('Changes properties of a token according to permissions', async () => {
+ async function testChangesPropertiesAccordingPermission(mode: CollectionMode, pieces: number) {
await usingApi(async api => {
+ const collection = await createCollectionExpectSuccess({mode: mode});
+ const token = await createItemExpectSuccess(alice, collection, mode.type);
+ await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+ await transferExpectSuccess(collection, token, alice, charlie, pieces, mode.type);
+
const propertyKeys: string[] = [];
let i = 0;
for (const permission of permissions) {
@@ -615,29 +715,29 @@
for (const signer of permission.signers) {
const key = i + '_' + signer.address;
propertyKeys.push(key);
-
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]),
), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;
-
+
await expect(executeTransaction(
api,
signer,
api.tx.unique.setTokenProperties(collection, token, [{key: key, value: 'Serotonin increase'}]),
), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;
-
+
await expect(executeTransaction(
api,
signer,
api.tx.unique.setTokenProperties(collection, token, [{key: key, value: 'Serotonin stable'}]),
), `on changing property ${i} by ${signer.address}`).to.not.be.rejected;
}
-
+
i++;
}
-
+
const properties = (await api.rpc.unique.tokenProperties(collection, token, propertyKeys)).toHuman() as any[];
const tokensData = (await api.rpc.unique.tokenData(collection, token, propertyKeys)).toHuman().properties as any[];
for (let i = 0; i < properties.length; i++) {
@@ -645,32 +745,43 @@
expect(tokensData[i].value).to.be.equal('Serotonin stable');
}
});
+ }
+ it('Changes properties of a token according to permissions (NFT)', async () => {
+ await testChangesPropertiesAccordingPermission({type: 'NFT'}, 1);
});
+ it('Changes properties of a token according to permissions (ReFungible)', async () => {
+ await testChangesPropertiesAccordingPermission({type: 'ReFungible'}, 100);
+ });
- it('Deletes properties of a token according to permissions', async () => {
+ async function testDeletePropertiesAccordingPermission(mode: CollectionMode, pieces: number) {
await usingApi(async api => {
+ const collection = await createCollectionExpectSuccess({mode: mode});
+ const token = await createItemExpectSuccess(alice, collection, mode.type);
+ await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+ await transferExpectSuccess(collection, token, alice, charlie, pieces, mode.type);
+
const propertyKeys: string[] = [];
let i = 0;
-
+
for (const permission of permissions) {
if (!permission.permission.mutable) continue;
for (const signer of permission.signers) {
const key = i + '_' + signer.address;
propertyKeys.push(key);
-
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]),
), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;
-
+
await expect(executeTransaction(
api,
signer,
api.tx.unique.setTokenProperties(collection, token, [{key: key, value: 'Serotonin increase'}]),
), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;
-
+
await expect(executeTransaction(
api,
signer,
@@ -680,17 +791,30 @@
i++;
}
-
+
const properties = (await api.rpc.unique.tokenProperties(collection, token, propertyKeys)).toJSON() as any[];
expect(properties).to.be.empty;
const tokensData = (await api.rpc.unique.tokenData(collection, token, propertyKeys)).toJSON().properties as any[];
expect(tokensData).to.be.empty;
expect((await api.query.nonfungible.tokenProperties(collection, token)).toJSON().consumedSpace).to.be.equal(0);
});
+ }
+ it('Deletes properties of a token according to permissions (NFT)', async () => {
+ await testDeletePropertiesAccordingPermission({type: 'NFT'}, 1);
});
+ it('Deletes properties of a token according to permissions (ReFungible)', async () => {
+ await testDeletePropertiesAccordingPermission({type: 'ReFungible'}, 100);
+ });
it('Assigns properties to a nested token according to permissions', async () => {
await usingApi(async api => {
+ const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
+ const token = await createItemExpectSuccess(alice, collection, 'NFT');
+ const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, token)});
+ await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+ await transferExpectSuccess(collection, token, alice, charlie);
+
const propertyKeys: string[] = [];
let i = 0;
for (const permission of permissions) {
@@ -725,6 +849,13 @@
it('Changes properties of a nested token according to permissions', async () => {
await usingApi(async api => {
+ const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
+ const token = await createItemExpectSuccess(alice, collection, 'NFT');
+ const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, token)});
+ await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+ await transferExpectSuccess(collection, token, alice, charlie);
+
const propertyKeys: string[] = [];
let i = 0;
for (const permission of permissions) {
@@ -767,6 +898,13 @@
it('Deletes properties of a nested token according to permissions', async () => {
await usingApi(async api => {
+ const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
+ const token = await createItemExpectSuccess(alice, collection, 'NFT');
+ const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, token)});
+ await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+ await transferExpectSuccess(collection, token, alice, charlie);
+
const propertyKeys: string[] = [];
let i = 0;
@@ -832,11 +970,11 @@
});
});
- beforeEach(async () => {
- collection = await createCollectionExpectSuccess();
- token = await createItemExpectSuccess(alice, collection, 'NFT');
+ async function prepare(mode: CollectionMode, pieces: number) {
+ collection = await createCollectionExpectSuccess({mode: mode});
+ token = await createItemExpectSuccess(alice, collection, mode.type);
await addCollectionAdminExpectSuccess(alice, collection, bob.address);
- await transferExpectSuccess(collection, token, alice, charlie);
+ await transferExpectSuccess(collection, token, alice, charlie, pieces, mode.type);
await usingApi(async api => {
let i = 0;
@@ -848,71 +986,89 @@
alice,
api.tx.unique.setTokenPropertyPermissions(collection, [{key: `${i}`, permission: passage.permission}]),
), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;
-
+
await expect(executeTransaction(
api,
signer,
api.tx.unique.setTokenProperties(collection, token, [{key: `${i}`, value: 'Serotonin increase'}]),
), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;
-
+
i++;
}
-
+
originalSpace = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON().consumedSpace as number;
- });
- });
+ });
+ }
- it('Forbids changing/deleting properties of a token if the user is outside of permissions', async () => {
+ async function testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(mode: CollectionMode, pieces: number) {
+ await prepare(mode, pieces);
+
await usingApi(async api => {
let i = -1;
for (const forbiddance of constitution) {
i++;
if (!forbiddance.permission.mutable) continue;
-
+
await expect(executeTransaction(
api,
forbiddance.sinner,
api.tx.unique.setTokenProperties(collection, token, [{key: `${i}`, value: 'Serotonin down'}]),
), `on failing to change property ${i} by ${forbiddance.sinner.address}`).to.be.rejectedWith(/common\.NoPermission/);
-
+
await expect(executeTransaction(
api,
forbiddance.sinner,
api.tx.unique.deleteTokenProperties(collection, token, [`${i}`]),
), `on failing to delete property ${i} by ${forbiddance.sinner.address}`).to.be.rejectedWith(/common\.NoPermission/);
}
-
+
const properties = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();
expect(properties.consumedSpace).to.be.equal(originalSpace);
});
+ }
+ it('Forbids changing/deleting properties of a token if the user is outside of permissions (NFT)', async () => {
+ await testForbidsChangingDeletingPropertiesUserOutsideOfPermissions({type: 'NFT'}, 1);
});
+ it('Forbids changing/deleting properties of a token if the user is outside of permissions (ReFungible)', async () => {
+ await testForbidsChangingDeletingPropertiesUserOutsideOfPermissions({type: 'ReFungible'}, 100);
+ });
- it('Forbids changing/deleting properties of a token if the property is permanent (immutable)', async () => {
+ async function testForbidsChangingDeletingPropertiesIfPropertyImmutable(mode: CollectionMode, pieces: number) {
+ await prepare(mode, pieces);
+
await usingApi(async api => {
let i = -1;
for (const permission of constitution) {
i++;
if (permission.permission.mutable) continue;
-
+
await expect(executeTransaction(
api,
permission.signers[0],
api.tx.unique.setTokenProperties(collection, token, [{key: `${i}`, value: 'Serotonin down'}]),
), `on failing to change property ${i} by ${permission.signers[0].address}`).to.be.rejectedWith(/common\.NoPermission/);
-
+
await expect(executeTransaction(
api,
permission.signers[0],
api.tx.unique.deleteTokenProperties(collection, token, [i.toString()]),
), `on failing to delete property ${i} by ${permission.signers[0].address}`).to.be.rejectedWith(/common\.NoPermission/);
}
-
+
const properties = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();
expect(properties.consumedSpace).to.be.equal(originalSpace);
- });
+ });
+ }
+ it('Forbids changing/deleting properties of a token if the property is permanent (immutable) (NFT)', async () => {
+ await testForbidsChangingDeletingPropertiesIfPropertyImmutable({type: 'NFT'}, 1);
});
+ it('Forbids changing/deleting properties of a token if the property is permanent (immutable) (ReFungible)', async () => {
+ await testForbidsChangingDeletingPropertiesIfPropertyImmutable({type: 'ReFungible'}, 100);
+ });
+
+ async function testForbidsAddingPropertiesIfPropertyNotDeclared(mode: CollectionMode, pieces: number) {
+ await prepare(mode, pieces);
- it('Forbids adding properties to a token if the property is not declared / forbidden with the \'None\' permission', async () => {
await usingApi(async api => {
await expect(executeTransaction(
api,
@@ -925,20 +1081,28 @@
alice,
api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'now-existent', permission: {}}]),
), 'on setting a new non-permitted property').to.not.be.rejected;
-
+
await expect(executeTransaction(
api,
alice,
api.tx.unique.setTokenProperties(collection, token, [{key: 'now-existent', value: 'I exist!'}]),
), 'on failing to add a property forbidden by the \'None\' permission').to.be.rejectedWith(/common\.NoPermission/);
-
+
expect((await api.rpc.unique.tokenProperties(collection, token, ['non-existent', 'now-existent'])).toJSON()).to.be.empty;
const properties = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();
expect(properties.consumedSpace).to.be.equal(originalSpace);
});
+ }
+ it('Forbids adding properties to a token if the property is not declared / forbidden with the \'None\' permission (NFT)', async () => {
+ await testForbidsAddingPropertiesIfPropertyNotDeclared({type: 'NFT'}, 1);
+ });
+ it('Forbids adding properties to a token if the property is not declared / forbidden with the \'None\' permission (ReFungible)', async () => {
+ await testForbidsAddingPropertiesIfPropertyNotDeclared({type: 'ReFungible'}, 100);
});
- it('Forbids adding too many properties to a token', async () => {
+ async function testForbidsAddingTooManyProperties(mode: CollectionMode, pieces: number) {
+ await prepare(mode, pieces);
+
await usingApi(async api => {
await expect(executeTransaction(
api,
@@ -948,7 +1112,7 @@
{key: 'young_years', permission: {collectionAdmin: true, tokenOwner: true}},
]),
), 'on setting a new non-permitted property').to.not.be.rejected;
-
+
// Mute the general tx parsing error
{
console.error = () => {};
@@ -958,7 +1122,7 @@
api.tx.unique.setCollectionProperties(collection, [{key: 'a_holy_book', value: 'word '.repeat(6554)}]),
)).to.be.rejected;
}
-
+
await expect(executeTransaction(
api,
alice,
@@ -967,10 +1131,107 @@
{key: 'young_years', value: 'neverending'.repeat(1490)},
]),
)).to.be.rejectedWith(/common\.NoSpaceForProperty/);
-
+
expect((await api.rpc.unique.tokenProperties(collection, token, ['a_holy_book', 'young_years'])).toJSON()).to.be.empty;
const propertiesMap = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();
expect(propertiesMap.consumedSpace).to.be.equal(originalSpace);
});
+ }
+ it('Forbids adding too many properties to a token (NFT)', async () => {
+ await testForbidsAddingTooManyProperties({type: 'NFT'}, 1);
+ });
+ it('Forbids adding too many properties to a token (ReFungible)', async () => {
+ await testForbidsAddingTooManyProperties({type: 'ReFungible'}, 100);
+ });
+});
+
+describe('ReFungible token properties permissions tests', () => {
+ let collection: number;
+ let token: number;
+
+ before(async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ alice = privateKeyWrapper('//Alice');
+ bob = privateKeyWrapper('//Bob');
+ charlie = privateKeyWrapper('//Charlie');
+ });
+ });
+
+ beforeEach(async () => {
+ await usingApi(async api => {
+ collection = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+ token = await createItemExpectSuccess(alice, collection, 'ReFungible');
+ await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'key', permission: {mutable:true, tokenOwner: true}}]),
+ )).to.not.be.rejected;
+ });
+ });
+
+ it('Forbids add token property with tokenOwher==true but signer have\'t all pieces', async () => {
+ await usingApi(async api => {
+ await transferExpectSuccess(collection, token, alice, charlie, 33, 'ReFungible');
+
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setTokenProperties(collection, token, [
+ {key: 'key', value: 'word'},
+ ]),
+ )).to.be.rejectedWith(/common\.NoPermission/);
+ });
+ });
+
+ it('Forbids mutate token property with tokenOwher==true but signer have\'t all pieces', async () => {
+ await usingApi(async api => {
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'key', permission: {mutable:true, tokenOwner: true}}]),
+ )).to.not.be.rejected;
+
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setTokenProperties(collection, token, [
+ {key: 'key', value: 'word'},
+ ]),
+ )).to.be.not.rejected;
+
+ await transferExpectSuccess(collection, token, alice, charlie, 33, 'ReFungible');
+
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setTokenProperties(collection, token, [
+ {key: 'key', value: 'bad word'},
+ ]),
+ )).to.be.rejectedWith(/common\.NoPermission/);
+ });
+ });
+
+ it('Forbids delete token property with tokenOwher==true but signer have\'t all pieces', async () => {
+ await usingApi(async api => {
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.setTokenProperties(collection, token, [
+ {key: 'key', value: 'word'},
+ ]),
+ )).to.be.not.rejected;
+
+ await transferExpectSuccess(collection, token, alice, charlie, 33, 'ReFungible');
+
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.deleteTokenProperties(collection, token, [
+ 'key',
+ ]),
+ )).to.be.rejectedWith(/common\.NoPermission/);
+ });
});
});
tests/src/refungible.test.tsdiffbeforeafterboth--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import {default as usingApi} from './substrate/substrate-api';
+import {default as usingApi, executeTransaction} from './substrate/substrate-api';
import {IKeyringPair} from '@polkadot/types/types';
import {
createCollectionExpectSuccess,
@@ -30,6 +30,8 @@
transfer,
burnItem,
repartitionRFT,
+ createCollectionWithPropsExpectSuccess,
+ getDetailedCollectionInfo,
} from './util/helpers';
import chai from 'chai';
@@ -187,3 +189,26 @@
});
});
});
+
+describe('Test Refungible properties:', () => {
+ before(async () => {
+ await usingApi(async (api, privateKeyWrapper) => {
+ alice = privateKeyWrapper('//Alice');
+ bob = privateKeyWrapper('//Bob');
+ });
+ });
+
+ it('Сreate new collection with properties', async () => {
+ await usingApi(async api => {
+ const properties = [{key: 'key1', value: 'val1'}];
+ const propertyPermissions = [{key: 'key1', permission: {tokenOwner: true, mutable: false, collectionAdmin: true}}];
+ const collectionId = await createCollectionWithPropsExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'ReFungible'},
+ properties: properties,
+ propPerm: propertyPermissions,
+ });
+ const collection = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collection.properties.toHuman()).to.be.deep.equal(properties);
+ expect(collection.tokenPropertyPermissions.toHuman()).to.be.deep.equal(propertyPermissions);
+ });
+ });
+});
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -284,7 +284,7 @@
type: 'ReFungible';
}
-type CollectionMode = Nft | Fungible | ReFungible;
+export type CollectionMode = Nft | Fungible | ReFungible;
export type Property = {
key: any,
@@ -1414,7 +1414,7 @@
tx = api.tx.unique.createItem(collectionId, to, createData as any);
}
- const events = await submitTransactionAsync(sender, tx);
+ const events = await executeTransaction(api, sender, tx);
const result = getCreateItemResult(events);
const itemCountAfter = await getLastTokenId(api, collectionId);