difftreelog
feat createMultipleItemsEx call
in: master
16 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -17,7 +17,7 @@
TokenId, Weight, WithdrawReasons, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode,
NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,
- CustomDataLimit, CreateCollectionData, SponsorshipState,
+ CustomDataLimit, CreateCollectionData, SponsorshipState, CreateItemExData,
};
pub use pallet::*;
use sp_core::H160;
@@ -624,9 +624,10 @@
}
/// Worst cases
-pub trait CommonWeightInfo {
+pub trait CommonWeightInfo<CrossAccountId> {
fn create_item() -> Weight;
fn create_multiple_items(amount: u32) -> Weight;
+ fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;
fn burn_item() -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
@@ -648,6 +649,11 @@
to: T::CrossAccountId,
data: Vec<CreateItemData>,
) -> DispatchResultWithPostInfo;
+ fn create_multiple_items_ex(
+ &self,
+ sender: T::CrossAccountId,
+ data: CreateItemExData<T::CrossAccountId>,
+ ) -> DispatchResultWithPostInfo;
fn burn_item(
&self,
sender: T::CrossAccountId,
pallets/fungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -4,7 +4,7 @@
use sp_std::prelude::*;
use pallet_common::benchmarking::create_collection_raw;
use frame_benchmarking::{benchmarks, account};
-use up_data_structs::{CollectionMode};
+use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH};
use pallet_common::bench_init;
const SEED: u32 = 1;
@@ -26,6 +26,18 @@
};
}: {<Pallet<T>>::create_item(&collection, &sender, (to, 200))?}
+ create_multiple_items_ex {
+ let b in 0..MAX_ITEMS_PER_BATCH;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner);
+ };
+ let data = (0..b).map(|i| {
+ bench_init!(to: cross_sub(i););
+ (to, 200)
+ }).collect::<BTreeMap<_, _>>().try_into().unwrap();
+ }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)}
+
burn_item {
bench_init!{
owner: sub; collection: collection(owner);
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -1,7 +1,7 @@
use core::marker::PhantomData;
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, BoundedVec};
-use up_data_structs::TokenId;
+use up_data_structs::{TokenId, CreateItemExData};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::ArithmeticError;
use sp_std::{vec::Vec, vec};
@@ -21,6 +21,15 @@
Self::create_item()
}
+ fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {
+ match data {
+ CreateItemExData::Fungible(f) => {
+ <SelfWeightOf<T>>::create_multiple_items_ex(f.len() as u32)
+ }
+ _ => 0,
+ }
+ }
+
fn burn_item() -> Weight {
<SelfWeightOf<T>>::burn_item()
}
@@ -87,6 +96,23 @@
)
}
+ fn create_multiple_items_ex(
+ &self,
+ sender: <T>::CrossAccountId,
+ data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,
+ ) -> DispatchResultWithPostInfo {
+ let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);
+ let data = match data {
+ up_data_structs::CreateItemExData::Fungible(f) => f,
+ _ => fail!(<Error<T>>::NotFungibleDataUsedToMintFungibleCollectionToken),
+ };
+
+ with_weight(
+ <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner()),
+ weight,
+ )
+ }
+
fn burn_item(
&self,
sender: T::CrossAccountId,
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -392,6 +392,6 @@
sender: &T::CrossAccountId,
data: CreateItemData<T>,
) -> DispatchResult {
- Self::create_multiple_items(collection, sender, vec![data])
+ Self::create_multiple_items(collection, sender, [(data.0, data.1)].into_iter().collect())
}
}
pallets/fungible/src/weights.rsdiffbeforeafterboth--- a/pallets/fungible/src/weights.rs
+++ b/pallets/fungible/src/weights.rs
@@ -33,6 +33,7 @@
/// Weight functions needed for pallet_fungible.
pub trait WeightInfo {
fn create_item() -> Weight;
+ fn create_multiple_items_ex(b: u32, ) -> Weight;
fn burn_item() -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
@@ -51,6 +52,17 @@
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
// Storage: Fungible TotalSupply (r:1 w:1)
+ // Storage: Fungible Balance (r:4 w:4)
+ fn create_multiple_items_ex(b: u32, ) -> Weight {
+ (1_055_000 as Weight)
+ // Standard Error: 22_000
+ .saturating_add((5_273_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))
+ .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(b as Weight)))
+ }
+ // Storage: Fungible TotalSupply (r:1 w:1)
// Storage: Fungible Balance (r:1 w:1)
fn burn_item() -> Weight {
(14_096_000 as Weight)
@@ -97,6 +109,17 @@
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
}
// Storage: Fungible TotalSupply (r:1 w:1)
+ // Storage: Fungible Balance (r:4 w:4)
+ fn create_multiple_items_ex(b: u32, ) -> Weight {
+ (1_055_000 as Weight)
+ // Standard Error: 22_000
+ .saturating_add((5_273_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))
+ .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(b as Weight)))
+ }
+ // Storage: Fungible TotalSupply (r:1 w:1)
// Storage: Fungible Balance (r:1 w:1)
fn burn_item() -> Weight {
(14_096_000 as Weight)
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -56,6 +56,16 @@
let data = (0..b).map(|_| create_max_item_data::<T>(to.clone())).collect();
}: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
+ create_multiple_items_ex {
+ let b in 0..MAX_ITEMS_PER_BATCH;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner);
+ };
+ let data = (0..b).map(|i| {
+ bench_init!(to: cross_sub(i););
+ create_max_item_data::<T>(to)
+ }).collect();
}: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
burn_item {
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -1,7 +1,7 @@
use core::marker::PhantomData;
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, BoundedVec};
-use up_data_structs::{TokenId, CustomDataLimit};
+use up_data_structs::{TokenId, CustomDataLimit, CreateItemExData};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::DispatchError;
use sp_std::vec::Vec;
@@ -17,6 +17,13 @@
<SelfWeightOf<T>>::create_item()
}
+ fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {
+ match data {
+ CreateItemExData::NFT(t) => <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32),
+ _ => 0,
+ }
+ }
+
fn create_multiple_items(amount: u32) -> Weight {
<SelfWeightOf<T>>::create_multiple_items(amount)
}
@@ -91,6 +98,23 @@
)
}
+ fn create_multiple_items_ex(
+ &self,
+ sender: <T>::CrossAccountId,
+ data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,
+ ) -> DispatchResultWithPostInfo {
+ let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);
+ let data = match data {
+ up_data_structs::CreateItemExData::NFT(nft) => nft,
+ _ => fail!(Error::<T>::NotNonfungibleDataUsedToMintFungibleCollectionToken),
+ };
+
+ with_weight(
+ <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner()),
+ weight,
+ )
+ }
+
fn burn_item(
&self,
sender: T::CrossAccountId,
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -2,7 +2,9 @@
use erc::ERC721Events;
use frame_support::{BoundedVec, ensure};
-use up_data_structs::{AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData};
+use up_data_structs::{
+ AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
+};
use pallet_common::{
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,
};
@@ -22,11 +24,7 @@
pub mod erc;
pub mod weights;
-pub struct CreateItemData<T: Config> {
- pub const_data: BoundedVec<u8, CustomDataLimit>,
- pub variable_data: BoundedVec<u8, CustomDataLimit>,
- pub owner: T::CrossAccountId,
-}
+pub type CreateItemData<T> = CreateNftExData<<T as pallet_common::Config>::CrossAccountId>;
pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;
#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -34,6 +34,7 @@
pub trait WeightInfo {
fn create_item() -> Weight;
fn create_multiple_items(b: u32, ) -> Weight;
+ fn create_multiple_items_ex(b: u32, ) -> Weight;
fn burn_item() -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
@@ -66,6 +67,19 @@
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(b as Weight)))
}
+ // Storage: Nonfungible TokensMinted (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:4 w:4)
+ // Storage: Nonfungible TokenData (r:0 w:4)
+ // Storage: Nonfungible Owned (r:0 w:4)
+ fn create_multiple_items_ex(b: u32, ) -> Weight {
+ (2_090_000 as Weight)
+ // Standard Error: 10_000
+ .saturating_add((9_230_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))
+ .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(b as Weight)))
+ }
// Storage: Nonfungible TokenData (r:1 w:1)
// Storage: Nonfungible TokensBurnt (r:1 w:1)
// Storage: Nonfungible Allowance (r:1 w:0)
@@ -140,6 +154,19 @@
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
.saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(b as Weight)))
}
+ // Storage: Nonfungible TokensMinted (r:1 w:1)
+ // Storage: Nonfungible AccountBalance (r:4 w:4)
+ // Storage: Nonfungible TokenData (r:0 w:4)
+ // Storage: Nonfungible Owned (r:0 w:4)
+ fn create_multiple_items_ex(b: u32, ) -> Weight {
+ (2_090_000 as Weight)
+ // Standard Error: 10_000
+ .saturating_add((9_230_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))
+ .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(b as Weight)))
+ }
// Storage: Nonfungible TokenData (r:1 w:1)
// Storage: Nonfungible TokensBurnt (r:1 w:1)
// Storage: Nonfungible Allowance (r:1 w:0)
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -31,7 +31,8 @@
sender: &T::CrossAccountId,
users: impl IntoIterator<Item = (T::CrossAccountId, u128)>,
) -> Result<TokenId, DispatchError> {
- <Pallet<T>>::create_item(&collection, sender, create_max_item_data(users))?;
+ let data: CreateRefungibleExData<T::CrossAccountId> = create_max_item_data(users);
+ <Pallet<T>>::create_item(&collection, sender, data)?;
Ok(TokenId(<TokensMinted<T>>::get(&collection.id)))
}
@@ -60,6 +61,30 @@
let data = (0..b).map(|_| create_max_item_data([(to.clone(), 200)])).collect();
}: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
+ create_multiple_items_ex_multiple_items {
+ let b in 0..MAX_ITEMS_PER_BATCH;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner);
+ };
+ let data = (0..b).map(|t| {
+ bench_init!(to: cross_sub(t););
+ create_max_item_data([(to, 200)])
+ }).collect();
+ }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
+
+ create_multiple_items_ex_multiple_owners {
+ let b in 0..MAX_ITEMS_PER_BATCH;
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner);
+ };
+ let data = vec![create_max_item_data((0..b).map(|u| {
+ bench_init!(to: cross_sub(u););
+ (to, 200)
+ }))].try_into().unwrap();
+ }: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
+
// Other user left, token data is kept
burn_item_partial {
bench_init!{
@@ -170,6 +195,6 @@
sender: cross_from_sub(owner);
};
let item = create_max_item(&collection, &sender, [(sender.clone(), 200)])?;
- let data = create_data(b as usize);
+ let data = create_var_data(b).try_into().unwrap();
}: {<Pallet<T>>::set_variable_metadata(&collection, &sender, item, data)?}
}
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -2,10 +2,10 @@
use sp_std::collections::btree_map::BTreeMap;
use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight, BoundedVec};
-use up_data_structs::{TokenId, CustomDataLimit};
+use up_data_structs::{TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData};
use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
use sp_runtime::DispatchError;
-use sp_std::vec::Vec;
+use sp_std::{vec::Vec, vec};
use crate::{
AccountBalance, Allowance, Balance, Config, Error, Owned, Pallet, RefungibleHandle,
@@ -31,6 +31,18 @@
<SelfWeightOf<T>>::create_multiple_items(amount)
}
+ 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)
+ }
+ CreateItemExData::RefungibleMultipleItems(i) => {
+ <SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32)
+ }
+ _ => 0,
+ }
+ }
+
fn burn_item() -> Weight {
max_weight_of!(burn_item_partial(), burn_item_fully())
}
@@ -69,15 +81,15 @@
fn map_create_data<T: Config>(
data: up_data_structs::CreateItemData,
to: &T::CrossAccountId,
-) -> Result<CreateItemData<T>, DispatchError> {
+) -> Result<CreateRefungibleExData<T::CrossAccountId>, DispatchError> {
match data {
- up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateItemData {
+ up_data_structs::CreateItemData::ReFungible(data) => Ok(CreateRefungibleExData {
const_data: data.const_data,
variable_data: data.variable_data,
users: {
let mut out = BTreeMap::new();
out.insert(to.clone(), data.pieces);
- out
+ out.try_into().expect("limit > 0")
},
}),
_ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),
@@ -92,7 +104,7 @@
data: up_data_structs::CreateItemData,
) -> DispatchResultWithPostInfo {
with_weight(
- <Pallet<T>>::create_item(self, &sender, map_create_data(data, &to)?),
+ <Pallet<T>>::create_item(self, &sender, map_create_data::<T>(data, &to)?),
<CommonWeights<T>>::create_item(),
)
}
@@ -115,6 +127,28 @@
)
}
+ fn create_multiple_items_ex(
+ &self,
+ sender: <T>::CrossAccountId,
+ data: CreateItemExData<T::CrossAccountId>,
+ ) -> DispatchResultWithPostInfo {
+ let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);
+ let data = match data {
+ CreateItemExData::RefungibleMultipleOwners(r) => vec![r],
+ CreateItemExData::RefungibleMultipleItems(r)
+ if r.iter().all(|i| i.users.len() == 1) =>
+ {
+ r.into_inner()
+ }
+ _ => fail!(<Error<T>>::NotRefungibleDataUsedToMintFungibleCollectionToken),
+ };
+
+ with_weight(
+ <Pallet<T>>::create_multiple_items(self, &sender, data),
+ weight,
+ )
+ }
+
fn burn_item(
&self,
sender: T::CrossAccountId,
pallets/refungible/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use up_data_structs::{5 AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId, CreateCollectionData,6};7use pallet_common::{8 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,9};10use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};11use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};12use core::ops::Deref;13use codec::{Encode, Decode, MaxEncodedLen};14use scale_info::TypeInfo;1516pub use pallet::*;17#[cfg(feature = "runtime-benchmarks")]18pub mod benchmarking;19pub mod common;20pub mod erc;21pub mod weights;22pub struct CreateItemData<T: Config> {23 pub const_data: BoundedVec<u8, CustomDataLimit>,24 pub variable_data: BoundedVec<u8, CustomDataLimit>,25 pub users: BTreeMap<T::CrossAccountId, u128>,26}27pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2829#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]30pub struct ItemData {31 pub const_data: BoundedVec<u8, CustomDataLimit>,32 pub variable_data: BoundedVec<u8, CustomDataLimit>,33}3435#[frame_support::pallet]36pub mod pallet {37 use super::*;38 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};39 use up_data_structs::{CollectionId, TokenId};40 use super::weights::WeightInfo;4142 #[pallet::error]43 pub enum Error<T> {44 /// Not Refungible item data used to mint in Refungible collection.45 NotRefungibleDataUsedToMintFungibleCollectionToken,46 /// Maximum refungibility exceeded47 WrongRefungiblePieces,48 }4950 #[pallet::config]51 pub trait Config: frame_system::Config + pallet_common::Config {52 type WeightInfo: WeightInfo;53 }5455 #[pallet::pallet]56 #[pallet::generate_store(pub(super) trait Store)]57 pub struct Pallet<T>(_);5859 #[pallet::storage]60 pub type TokensMinted<T: Config> =61 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;62 #[pallet::storage]63 pub type TokensBurnt<T: Config> =64 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6566 #[pallet::storage]67 pub type TokenData<T: Config> = StorageNMap<68 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),69 Value = ItemData,70 QueryKind = ValueQuery,71 >;7273 #[pallet::storage]74 pub type TotalSupply<T: Config> = StorageNMap<75 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),76 Value = u128,77 QueryKind = ValueQuery,78 >;7980 /// Used to enumerate tokens owned by account81 #[pallet::storage]82 pub type Owned<T: Config> = StorageNMap<83 Key = (84 Key<Twox64Concat, CollectionId>,85 Key<Blake2_128Concat, T::CrossAccountId>,86 Key<Twox64Concat, TokenId>,87 ),88 Value = bool,89 QueryKind = ValueQuery,90 >;9192 #[pallet::storage]93 pub type AccountBalance<T: Config> = StorageNMap<94 Key = (95 Key<Twox64Concat, CollectionId>,96 // Owner97 Key<Blake2_128Concat, T::CrossAccountId>,98 ),99 Value = u32,100 QueryKind = ValueQuery,101 >;102103 #[pallet::storage]104 pub type Balance<T: Config> = StorageNMap<105 Key = (106 Key<Twox64Concat, CollectionId>,107 Key<Twox64Concat, TokenId>,108 // Owner109 Key<Blake2_128Concat, T::CrossAccountId>,110 ),111 Value = u128,112 QueryKind = ValueQuery,113 >;114115 #[pallet::storage]116 pub type Allowance<T: Config> = StorageNMap<117 Key = (118 Key<Twox64Concat, CollectionId>,119 Key<Twox64Concat, TokenId>,120 // Owner121 Key<Blake2_128, T::CrossAccountId>,122 // Spender123 Key<Blake2_128Concat, T::CrossAccountId>,124 ),125 Value = u128,126 QueryKind = ValueQuery,127 >;128}129130pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);131impl<T: Config> RefungibleHandle<T> {132 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {133 Self(inner)134 }135 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {136 self.0137 }138}139impl<T: Config> Deref for RefungibleHandle<T> {140 type Target = pallet_common::CollectionHandle<T>;141142 fn deref(&self) -> &Self::Target {143 &self.0144 }145}146147impl<T: Config> Pallet<T> {148 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {149 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)150 }151 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {152 <TotalSupply<T>>::contains_key((collection.id, token))153 }154}155156// unchecked calls skips any permission checks157impl<T: Config> Pallet<T> {158 pub fn init_collection(159 owner: T::AccountId,160 data: CreateCollectionData<T::AccountId>,161 ) -> Result<CollectionId, DispatchError> {162 <PalletCommon<T>>::init_collection(owner, data)163 }164 pub fn destroy_collection(165 collection: RefungibleHandle<T>,166 sender: &T::CrossAccountId,167 ) -> DispatchResult {168 let id = collection.id;169170 // =========171172 PalletCommon::destroy_collection(collection.0, sender)?;173174 <TokensMinted<T>>::remove(id);175 <TokensBurnt<T>>::remove(id);176 <TokenData<T>>::remove_prefix((id,), None);177 <TotalSupply<T>>::remove_prefix((id,), None);178 <Balance<T>>::remove_prefix((id,), None);179 <Allowance<T>>::remove_prefix((id,), None);180 <Owned<T>>::remove_prefix((id,), None);181 <AccountBalance<T>>::remove_prefix((id,), None);182 Ok(())183 }184185 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {186 let burnt = <TokensBurnt<T>>::get(collection.id)187 .checked_add(1)188 .ok_or(ArithmeticError::Overflow)?;189190 <TokensBurnt<T>>::insert(collection.id, burnt);191 <TokenData<T>>::remove((collection.id, token_id));192 <TotalSupply<T>>::remove((collection.id, token_id));193 <Balance<T>>::remove_prefix((collection.id, token_id), None);194 <Allowance<T>>::remove_prefix((collection.id, token_id), None);195 // TODO: ERC721 transfer event196 Ok(())197 }198199 pub fn burn(200 collection: &RefungibleHandle<T>,201 owner: &T::CrossAccountId,202 token: TokenId,203 amount: u128,204 ) -> DispatchResult {205 let total_supply = <TotalSupply<T>>::get((collection.id, token))206 .checked_sub(amount)207 .ok_or(<CommonError<T>>::TokenValueTooLow)?;208209 // This was probally last owner of this token?210 if total_supply == 0 {211 // Ensure user actually owns this amount212 ensure!(213 <Balance<T>>::get((collection.id, token, owner)) == amount,214 <CommonError<T>>::TokenValueTooLow215 );216 let account_balance = <AccountBalance<T>>::get((collection.id, owner))217 .checked_sub(1)218 // Should not occur219 .ok_or(ArithmeticError::Underflow)?;220221 // =========222223 <Owned<T>>::remove((collection.id, owner, token));224 <AccountBalance<T>>::insert((collection.id, owner), account_balance);225 Self::burn_token(collection, token)?;226 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(227 collection.id,228 token,229 owner.clone(),230 amount,231 ));232 return Ok(());233 }234235 let balance = <Balance<T>>::get((collection.id, token, owner))236 .checked_sub(amount)237 .ok_or(<CommonError<T>>::TokenValueTooLow)?;238 let account_balance = if balance == 0 {239 <AccountBalance<T>>::get((collection.id, owner))240 .checked_sub(1)241 // Should not occur242 .ok_or(ArithmeticError::Underflow)?243 } else {244 0245 };246247 // =========248249 if balance == 0 {250 <Owned<T>>::remove((collection.id, owner, token));251 <Balance<T>>::remove((collection.id, token, owner));252 <AccountBalance<T>>::insert((collection.id, owner), account_balance);253 } else {254 <Balance<T>>::insert((collection.id, token, owner), balance);255 }256 <TotalSupply<T>>::insert((collection.id, token), total_supply);257 // TODO: ERC20 transfer event258 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(259 collection.id,260 token,261 owner.clone(),262 amount,263 ));264 Ok(())265 }266267 pub fn transfer(268 collection: &RefungibleHandle<T>,269 from: &T::CrossAccountId,270 to: &T::CrossAccountId,271 token: TokenId,272 amount: u128,273 ) -> DispatchResult {274 ensure!(275 collection.limits.transfers_enabled(),276 <CommonError<T>>::TransferNotAllowed277 );278279 if collection.access == AccessMode::AllowList {280 collection.check_allowlist(from)?;281 collection.check_allowlist(to)?;282 }283 <PalletCommon<T>>::ensure_correct_receiver(to)?;284285 let balance_from = <Balance<T>>::get((collection.id, token, from))286 .checked_sub(amount)287 .ok_or(<CommonError<T>>::TokenValueTooLow)?;288 let mut create_target = false;289 let from_to_differ = from != to;290 let balance_to = if from != to {291 let old_balance = <Balance<T>>::get((collection.id, token, to));292 if old_balance == 0 {293 create_target = true;294 }295 Some(296 old_balance297 .checked_add(amount)298 .ok_or(ArithmeticError::Overflow)?,299 )300 } else {301 None302 };303304 let account_balance_from = if balance_from == 0 {305 Some(306 <AccountBalance<T>>::get((collection.id, from))307 .checked_sub(1)308 // Should not occur309 .ok_or(ArithmeticError::Underflow)?,310 )311 } else {312 None313 };314 // Account data is created in token, AccountBalance should be increased315 // But only if from != to as we shouldn't check overflow in this case316 let account_balance_to = if create_target && from_to_differ {317 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))318 .checked_add(1)319 .ok_or(ArithmeticError::Overflow)?;320 ensure!(321 account_balance_to < collection.limits.account_token_ownership_limit(),322 <CommonError<T>>::AccountTokenLimitExceeded,323 );324325 Some(account_balance_to)326 } else {327 None328 };329330 // =========331332 if let Some(balance_to) = balance_to {333 // from != to334 if balance_from == 0 {335 <Balance<T>>::remove((collection.id, token, from));336 } else {337 <Balance<T>>::insert((collection.id, token, from), balance_from);338 }339 <Balance<T>>::insert((collection.id, token, to), balance_to);340 if let Some(account_balance_from) = account_balance_from {341 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);342 <Owned<T>>::remove((collection.id, from, token));343 }344 if let Some(account_balance_to) = account_balance_to {345 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);346 <Owned<T>>::insert((collection.id, to, token), true);347 }348 }349350 // TODO: ERC20 transfer event351 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(352 collection.id,353 token,354 from.clone(),355 to.clone(),356 amount,357 ));358 Ok(())359 }360361 pub fn create_multiple_items(362 collection: &RefungibleHandle<T>,363 sender: &T::CrossAccountId,364 data: Vec<CreateItemData<T>>,365 ) -> DispatchResult {366 if !collection.is_owner_or_admin(sender) {367 ensure!(368 collection.mint_mode,369 <CommonError<T>>::PublicMintingNotAllowed370 );371 collection.check_allowlist(sender)?;372373 for item in data.iter() {374 for user in item.users.keys() {375 collection.check_allowlist(user)?;376 }377 }378 }379380 for item in data.iter() {381 for (owner, _) in item.users.iter() {382 <PalletCommon<T>>::ensure_correct_receiver(owner)?;383 }384 }385386 // Total pieces per tokens387 let totals = data388 .iter()389 .map(|data| {390 Ok(data391 .users392 .iter()393 .map(|u| u.1)394 .try_fold(0u128, |acc, v| acc.checked_add(*v))395 .ok_or(ArithmeticError::Overflow)?)396 })397 .collect::<Result<Vec<_>, DispatchError>>()?;398 for total in &totals {399 ensure!(400 *total <= MAX_REFUNGIBLE_PIECES,401 <Error<T>>::WrongRefungiblePieces402 );403 }404405 let first_token_id = <TokensMinted<T>>::get(collection.id);406 let tokens_minted = first_token_id407 .checked_add(data.len() as u32)408 .ok_or(ArithmeticError::Overflow)?;409 ensure!(410 tokens_minted < collection.limits.token_limit(),411 <CommonError<T>>::CollectionTokenLimitExceeded412 );413414 let mut balances = BTreeMap::new();415 for data in &data {416 for owner in data.users.keys() {417 let balance = balances418 .entry(owner)419 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));420 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;421422 ensure!(423 *balance <= collection.limits.account_token_ownership_limit(),424 <CommonError<T>>::AccountTokenLimitExceeded,425 );426 }427 }428429 // =========430431 <TokensMinted<T>>::insert(collection.id, tokens_minted);432 for (account, balance) in balances {433 <AccountBalance<T>>::insert((collection.id, account), balance);434 }435 for (i, token) in data.into_iter().enumerate() {436 let token_id = first_token_id + i as u32 + 1;437 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);438439 <TokenData<T>>::insert(440 (collection.id, token_id),441 ItemData {442 const_data: token.const_data,443 variable_data: token.variable_data,444 },445 );446 for (user, amount) in token.users.into_iter() {447 if amount == 0 {448 continue;449 }450 <Balance<T>>::insert((collection.id, token_id, &user), amount);451 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);452 // TODO: ERC20 transfer event453 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(454 collection.id,455 TokenId(token_id),456 user,457 amount,458 ));459 }460 }461 Ok(())462 }463464 pub fn set_allowance_unchecked(465 collection: &RefungibleHandle<T>,466 sender: &T::CrossAccountId,467 spender: &T::CrossAccountId,468 token: TokenId,469 amount: u128,470 ) {471 if amount == 0 {472 <Allowance<T>>::remove((collection.id, token, sender, spender));473 } else {474 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);475 }476 // TODO: ERC20 approval event477 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(478 collection.id,479 token,480 sender.clone(),481 spender.clone(),482 amount,483 ))484 }485486 pub fn set_allowance(487 collection: &RefungibleHandle<T>,488 sender: &T::CrossAccountId,489 spender: &T::CrossAccountId,490 token: TokenId,491 amount: u128,492 ) -> DispatchResult {493 if collection.access == AccessMode::AllowList {494 collection.check_allowlist(sender)?;495 collection.check_allowlist(spender)?;496 }497498 <PalletCommon<T>>::ensure_correct_receiver(spender)?;499500 if <Balance<T>>::get((collection.id, token, sender)) < amount {501 ensure!(502 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),503 <CommonError<T>>::CantApproveMoreThanOwned504 );505 }506507 // =========508509 Self::set_allowance_unchecked(collection, sender, spender, token, amount);510 Ok(())511 }512513 pub fn transfer_from(514 collection: &RefungibleHandle<T>,515 spender: &T::CrossAccountId,516 from: &T::CrossAccountId,517 to: &T::CrossAccountId,518 token: TokenId,519 amount: u128,520 ) -> DispatchResult {521 if spender.conv_eq(from) {522 return Self::transfer(collection, from, to, token, amount);523 }524 if collection.access == AccessMode::AllowList {525 // `from`, `to` checked in [`transfer`]526 collection.check_allowlist(spender)?;527 }528529 let allowance =530 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);531 if allowance.is_none() {532 ensure!(533 collection.ignores_allowance(spender),534 <CommonError<T>>::ApprovedValueTooLow535 );536 }537538 // =========539540 Self::transfer(collection, from, to, token, amount)?;541 if let Some(allowance) = allowance {542 Self::set_allowance_unchecked(collection, from, spender, token, allowance);543 }544 Ok(())545 }546547 pub fn burn_from(548 collection: &RefungibleHandle<T>,549 spender: &T::CrossAccountId,550 from: &T::CrossAccountId,551 token: TokenId,552 amount: u128,553 ) -> DispatchResult {554 if spender.conv_eq(from) {555 return Self::burn(collection, from, token, amount);556 }557 if collection.access == AccessMode::AllowList {558 // `from` checked in [`burn`]559 collection.check_allowlist(spender)?;560 }561562 let allowance =563 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);564 if allowance.is_none() {565 ensure!(566 collection.ignores_allowance(spender),567 <CommonError<T>>::ApprovedValueTooLow568 );569 }570571 // =========572573 Self::burn(collection, from, token, amount)?;574 if let Some(allowance) = allowance {575 Self::set_allowance_unchecked(collection, from, spender, token, allowance);576 }577 Ok(())578 }579580 pub fn set_variable_metadata(581 collection: &RefungibleHandle<T>,582 sender: &T::CrossAccountId,583 token: TokenId,584 data: BoundedVec<u8, CustomDataLimit>,585 ) -> DispatchResult {586 collection.check_can_update_meta(587 sender,588 &T::CrossAccountId::from_sub(collection.owner.clone()),589 )?;590591 let token_data = <TokenData<T>>::get((collection.id, token));592593 // =========594595 <TokenData<T>>::insert(596 (collection.id, token),597 ItemData {598 variable_data: data,599 ..token_data600 },601 );602 Ok(())603 }604605 /// Delegated to `create_multiple_items`606 pub fn create_item(607 collection: &RefungibleHandle<T>,608 sender: &T::CrossAccountId,609 data: CreateItemData<T>,610 ) -> DispatchResult {611 Self::create_multiple_items(collection, sender, vec![data])612 }613}1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use up_data_structs::{5 AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,6 CreateCollectionData, CreateRefungibleExData,7};8use pallet_common::{9 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,10};11use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};12use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};13use core::ops::Deref;14use codec::{Encode, Decode, MaxEncodedLen};15use scale_info::TypeInfo;1617pub use pallet::*;18#[cfg(feature = "runtime-benchmarks")]19pub mod benchmarking;20pub mod common;21pub mod erc;22pub mod weights;23pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2425#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]26pub struct ItemData {27 pub const_data: BoundedVec<u8, CustomDataLimit>,28 pub variable_data: BoundedVec<u8, CustomDataLimit>,29}3031#[frame_support::pallet]32pub mod pallet {33 use super::*;34 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};35 use up_data_structs::{CollectionId, TokenId};36 use super::weights::WeightInfo;3738 #[pallet::error]39 pub enum Error<T> {40 /// Not Refungible item data used to mint in Refungible collection.41 NotRefungibleDataUsedToMintFungibleCollectionToken,42 /// Maximum refungibility exceeded43 WrongRefungiblePieces,44 }4546 #[pallet::config]47 pub trait Config: frame_system::Config + pallet_common::Config {48 type WeightInfo: WeightInfo;49 }5051 #[pallet::pallet]52 #[pallet::generate_store(pub(super) trait Store)]53 pub struct Pallet<T>(_);5455 #[pallet::storage]56 pub type TokensMinted<T: Config> =57 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;58 #[pallet::storage]59 pub type TokensBurnt<T: Config> =60 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6162 #[pallet::storage]63 pub type TokenData<T: Config> = StorageNMap<64 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),65 Value = ItemData,66 QueryKind = ValueQuery,67 >;6869 #[pallet::storage]70 pub type TotalSupply<T: Config> = StorageNMap<71 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),72 Value = u128,73 QueryKind = ValueQuery,74 >;7576 /// Used to enumerate tokens owned by account77 #[pallet::storage]78 pub type Owned<T: Config> = StorageNMap<79 Key = (80 Key<Twox64Concat, CollectionId>,81 Key<Blake2_128Concat, T::CrossAccountId>,82 Key<Twox64Concat, TokenId>,83 ),84 Value = bool,85 QueryKind = ValueQuery,86 >;8788 #[pallet::storage]89 pub type AccountBalance<T: Config> = StorageNMap<90 Key = (91 Key<Twox64Concat, CollectionId>,92 // Owner93 Key<Blake2_128Concat, T::CrossAccountId>,94 ),95 Value = u32,96 QueryKind = ValueQuery,97 >;9899 #[pallet::storage]100 pub type Balance<T: Config> = StorageNMap<101 Key = (102 Key<Twox64Concat, CollectionId>,103 Key<Twox64Concat, TokenId>,104 // Owner105 Key<Blake2_128Concat, T::CrossAccountId>,106 ),107 Value = u128,108 QueryKind = ValueQuery,109 >;110111 #[pallet::storage]112 pub type Allowance<T: Config> = StorageNMap<113 Key = (114 Key<Twox64Concat, CollectionId>,115 Key<Twox64Concat, TokenId>,116 // Owner117 Key<Blake2_128, T::CrossAccountId>,118 // Spender119 Key<Blake2_128Concat, T::CrossAccountId>,120 ),121 Value = u128,122 QueryKind = ValueQuery,123 >;124}125126pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);127impl<T: Config> RefungibleHandle<T> {128 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {129 Self(inner)130 }131 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {132 self.0133 }134}135impl<T: Config> Deref for RefungibleHandle<T> {136 type Target = pallet_common::CollectionHandle<T>;137138 fn deref(&self) -> &Self::Target {139 &self.0140 }141}142143impl<T: Config> Pallet<T> {144 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {145 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)146 }147 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {148 <TotalSupply<T>>::contains_key((collection.id, token))149 }150}151152// unchecked calls skips any permission checks153impl<T: Config> Pallet<T> {154 pub fn init_collection(155 owner: T::AccountId,156 data: CreateCollectionData<T::AccountId>,157 ) -> Result<CollectionId, DispatchError> {158 <PalletCommon<T>>::init_collection(owner, data)159 }160 pub fn destroy_collection(161 collection: RefungibleHandle<T>,162 sender: &T::CrossAccountId,163 ) -> DispatchResult {164 let id = collection.id;165166 // =========167168 PalletCommon::destroy_collection(collection.0, sender)?;169170 <TokensMinted<T>>::remove(id);171 <TokensBurnt<T>>::remove(id);172 <TokenData<T>>::remove_prefix((id,), None);173 <TotalSupply<T>>::remove_prefix((id,), None);174 <Balance<T>>::remove_prefix((id,), None);175 <Allowance<T>>::remove_prefix((id,), None);176 <Owned<T>>::remove_prefix((id,), None);177 <AccountBalance<T>>::remove_prefix((id,), None);178 Ok(())179 }180181 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {182 let burnt = <TokensBurnt<T>>::get(collection.id)183 .checked_add(1)184 .ok_or(ArithmeticError::Overflow)?;185186 <TokensBurnt<T>>::insert(collection.id, burnt);187 <TokenData<T>>::remove((collection.id, token_id));188 <TotalSupply<T>>::remove((collection.id, token_id));189 <Balance<T>>::remove_prefix((collection.id, token_id), None);190 <Allowance<T>>::remove_prefix((collection.id, token_id), None);191 // TODO: ERC721 transfer event192 Ok(())193 }194195 pub fn burn(196 collection: &RefungibleHandle<T>,197 owner: &T::CrossAccountId,198 token: TokenId,199 amount: u128,200 ) -> DispatchResult {201 let total_supply = <TotalSupply<T>>::get((collection.id, token))202 .checked_sub(amount)203 .ok_or(<CommonError<T>>::TokenValueTooLow)?;204205 // This was probally last owner of this token?206 if total_supply == 0 {207 // Ensure user actually owns this amount208 ensure!(209 <Balance<T>>::get((collection.id, token, owner)) == amount,210 <CommonError<T>>::TokenValueTooLow211 );212 let account_balance = <AccountBalance<T>>::get((collection.id, owner))213 .checked_sub(1)214 // Should not occur215 .ok_or(ArithmeticError::Underflow)?;216217 // =========218219 <Owned<T>>::remove((collection.id, owner, token));220 <AccountBalance<T>>::insert((collection.id, owner), account_balance);221 Self::burn_token(collection, token)?;222 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(223 collection.id,224 token,225 owner.clone(),226 amount,227 ));228 return Ok(());229 }230231 let balance = <Balance<T>>::get((collection.id, token, owner))232 .checked_sub(amount)233 .ok_or(<CommonError<T>>::TokenValueTooLow)?;234 let account_balance = if balance == 0 {235 <AccountBalance<T>>::get((collection.id, owner))236 .checked_sub(1)237 // Should not occur238 .ok_or(ArithmeticError::Underflow)?239 } else {240 0241 };242243 // =========244245 if balance == 0 {246 <Owned<T>>::remove((collection.id, owner, token));247 <Balance<T>>::remove((collection.id, token, owner));248 <AccountBalance<T>>::insert((collection.id, owner), account_balance);249 } else {250 <Balance<T>>::insert((collection.id, token, owner), balance);251 }252 <TotalSupply<T>>::insert((collection.id, token), total_supply);253 // TODO: ERC20 transfer event254 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(255 collection.id,256 token,257 owner.clone(),258 amount,259 ));260 Ok(())261 }262263 pub fn transfer(264 collection: &RefungibleHandle<T>,265 from: &T::CrossAccountId,266 to: &T::CrossAccountId,267 token: TokenId,268 amount: u128,269 ) -> DispatchResult {270 ensure!(271 collection.limits.transfers_enabled(),272 <CommonError<T>>::TransferNotAllowed273 );274275 if collection.access == AccessMode::AllowList {276 collection.check_allowlist(from)?;277 collection.check_allowlist(to)?;278 }279 <PalletCommon<T>>::ensure_correct_receiver(to)?;280281 let balance_from = <Balance<T>>::get((collection.id, token, from))282 .checked_sub(amount)283 .ok_or(<CommonError<T>>::TokenValueTooLow)?;284 let mut create_target = false;285 let from_to_differ = from != to;286 let balance_to = if from != to {287 let old_balance = <Balance<T>>::get((collection.id, token, to));288 if old_balance == 0 {289 create_target = true;290 }291 Some(292 old_balance293 .checked_add(amount)294 .ok_or(ArithmeticError::Overflow)?,295 )296 } else {297 None298 };299300 let account_balance_from = if balance_from == 0 {301 Some(302 <AccountBalance<T>>::get((collection.id, from))303 .checked_sub(1)304 // Should not occur305 .ok_or(ArithmeticError::Underflow)?,306 )307 } else {308 None309 };310 // Account data is created in token, AccountBalance should be increased311 // But only if from != to as we shouldn't check overflow in this case312 let account_balance_to = if create_target && from_to_differ {313 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))314 .checked_add(1)315 .ok_or(ArithmeticError::Overflow)?;316 ensure!(317 account_balance_to < collection.limits.account_token_ownership_limit(),318 <CommonError<T>>::AccountTokenLimitExceeded,319 );320321 Some(account_balance_to)322 } else {323 None324 };325326 // =========327328 if let Some(balance_to) = balance_to {329 // from != to330 if balance_from == 0 {331 <Balance<T>>::remove((collection.id, token, from));332 } else {333 <Balance<T>>::insert((collection.id, token, from), balance_from);334 }335 <Balance<T>>::insert((collection.id, token, to), balance_to);336 if let Some(account_balance_from) = account_balance_from {337 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);338 <Owned<T>>::remove((collection.id, from, token));339 }340 if let Some(account_balance_to) = account_balance_to {341 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);342 <Owned<T>>::insert((collection.id, to, token), true);343 }344 }345346 // TODO: ERC20 transfer event347 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(348 collection.id,349 token,350 from.clone(),351 to.clone(),352 amount,353 ));354 Ok(())355 }356357 pub fn create_multiple_items(358 collection: &RefungibleHandle<T>,359 sender: &T::CrossAccountId,360 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,361 ) -> DispatchResult {362 if !collection.is_owner_or_admin(sender) {363 ensure!(364 collection.mint_mode,365 <CommonError<T>>::PublicMintingNotAllowed366 );367 collection.check_allowlist(sender)?;368369 for item in data.iter() {370 for user in item.users.keys() {371 collection.check_allowlist(user)?;372 }373 }374 }375376 for item in data.iter() {377 for (owner, _) in item.users.iter() {378 <PalletCommon<T>>::ensure_correct_receiver(owner)?;379 }380 }381382 // Total pieces per tokens383 let totals = data384 .iter()385 .map(|data| {386 Ok(data387 .users388 .iter()389 .map(|u| u.1)390 .try_fold(0u128, |acc, v| acc.checked_add(*v))391 .ok_or(ArithmeticError::Overflow)?)392 })393 .collect::<Result<Vec<_>, DispatchError>>()?;394 for total in &totals {395 ensure!(396 *total <= MAX_REFUNGIBLE_PIECES,397 <Error<T>>::WrongRefungiblePieces398 );399 }400401 let first_token_id = <TokensMinted<T>>::get(collection.id);402 let tokens_minted = first_token_id403 .checked_add(data.len() as u32)404 .ok_or(ArithmeticError::Overflow)?;405 ensure!(406 tokens_minted < collection.limits.token_limit(),407 <CommonError<T>>::CollectionTokenLimitExceeded408 );409410 let mut balances = BTreeMap::new();411 for data in &data {412 for owner in data.users.keys() {413 let balance = balances414 .entry(owner)415 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));416 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;417418 ensure!(419 *balance <= collection.limits.account_token_ownership_limit(),420 <CommonError<T>>::AccountTokenLimitExceeded,421 );422 }423 }424425 // =========426427 <TokensMinted<T>>::insert(collection.id, tokens_minted);428 for (account, balance) in balances {429 <AccountBalance<T>>::insert((collection.id, account), balance);430 }431 for (i, token) in data.into_iter().enumerate() {432 let token_id = first_token_id + i as u32 + 1;433 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);434435 <TokenData<T>>::insert(436 (collection.id, token_id),437 ItemData {438 const_data: token.const_data,439 variable_data: token.variable_data,440 },441 );442 for (user, amount) in token.users.into_iter() {443 if amount == 0 {444 continue;445 }446 <Balance<T>>::insert((collection.id, token_id, &user), amount);447 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);448 // TODO: ERC20 transfer event449 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(450 collection.id,451 TokenId(token_id),452 user,453 amount,454 ));455 }456 }457 Ok(())458 }459460 pub fn set_allowance_unchecked(461 collection: &RefungibleHandle<T>,462 sender: &T::CrossAccountId,463 spender: &T::CrossAccountId,464 token: TokenId,465 amount: u128,466 ) {467 if amount == 0 {468 <Allowance<T>>::remove((collection.id, token, sender, spender));469 } else {470 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);471 }472 // TODO: ERC20 approval event473 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(474 collection.id,475 token,476 sender.clone(),477 spender.clone(),478 amount,479 ))480 }481482 pub fn set_allowance(483 collection: &RefungibleHandle<T>,484 sender: &T::CrossAccountId,485 spender: &T::CrossAccountId,486 token: TokenId,487 amount: u128,488 ) -> DispatchResult {489 if collection.access == AccessMode::AllowList {490 collection.check_allowlist(sender)?;491 collection.check_allowlist(spender)?;492 }493494 <PalletCommon<T>>::ensure_correct_receiver(spender)?;495496 if <Balance<T>>::get((collection.id, token, sender)) < amount {497 ensure!(498 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),499 <CommonError<T>>::CantApproveMoreThanOwned500 );501 }502503 // =========504505 Self::set_allowance_unchecked(collection, sender, spender, token, amount);506 Ok(())507 }508509 pub fn transfer_from(510 collection: &RefungibleHandle<T>,511 spender: &T::CrossAccountId,512 from: &T::CrossAccountId,513 to: &T::CrossAccountId,514 token: TokenId,515 amount: u128,516 ) -> DispatchResult {517 if spender.conv_eq(from) {518 return Self::transfer(collection, from, to, token, amount);519 }520 if collection.access == AccessMode::AllowList {521 // `from`, `to` checked in [`transfer`]522 collection.check_allowlist(spender)?;523 }524525 let allowance =526 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);527 if allowance.is_none() {528 ensure!(529 collection.ignores_allowance(spender),530 <CommonError<T>>::ApprovedValueTooLow531 );532 }533534 // =========535536 Self::transfer(collection, from, to, token, amount)?;537 if let Some(allowance) = allowance {538 Self::set_allowance_unchecked(collection, from, spender, token, allowance);539 }540 Ok(())541 }542543 pub fn burn_from(544 collection: &RefungibleHandle<T>,545 spender: &T::CrossAccountId,546 from: &T::CrossAccountId,547 token: TokenId,548 amount: u128,549 ) -> DispatchResult {550 if spender.conv_eq(from) {551 return Self::burn(collection, from, token, amount);552 }553 if collection.access == AccessMode::AllowList {554 // `from` checked in [`burn`]555 collection.check_allowlist(spender)?;556 }557558 let allowance =559 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);560 if allowance.is_none() {561 ensure!(562 collection.ignores_allowance(spender),563 <CommonError<T>>::ApprovedValueTooLow564 );565 }566567 // =========568569 Self::burn(collection, from, token, amount)?;570 if let Some(allowance) = allowance {571 Self::set_allowance_unchecked(collection, from, spender, token, allowance);572 }573 Ok(())574 }575576 pub fn set_variable_metadata(577 collection: &RefungibleHandle<T>,578 sender: &T::CrossAccountId,579 token: TokenId,580 data: BoundedVec<u8, CustomDataLimit>,581 ) -> DispatchResult {582 collection.check_can_update_meta(583 sender,584 &T::CrossAccountId::from_sub(collection.owner.clone()),585 )?;586587 let token_data = <TokenData<T>>::get((collection.id, token));588589 // =========590591 <TokenData<T>>::insert(592 (collection.id, token),593 ItemData {594 variable_data: data,595 ..token_data596 },597 );598 Ok(())599 }600601 /// Delegated to `create_multiple_items`602 pub fn create_item(603 collection: &RefungibleHandle<T>,604 sender: &T::CrossAccountId,605 data: CreateRefungibleExData<T::CrossAccountId>,606 ) -> DispatchResult {607 Self::create_multiple_items(collection, sender, vec![data])608 }609}pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -34,6 +34,8 @@
pub trait WeightInfo {
fn create_item() -> Weight;
fn create_multiple_items(b: u32, ) -> Weight;
+ fn create_multiple_items_ex_multiple_items(b: u32, ) -> Weight;
+ fn create_multiple_items_ex_multiple_owners(b: u32, ) -> Weight;
fn burn_item_partial() -> Weight;
fn burn_item_fully() -> Weight;
fn transfer_normal() -> Weight;
@@ -77,6 +79,36 @@
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(b as Weight)))
}
+ // Storage: Refungible TokensMinted (r:1 w:1)
+ // Storage: Refungible AccountBalance (r:4 w:4)
+ // Storage: Refungible Balance (r:0 w:4)
+ // Storage: Refungible TotalSupply (r:0 w:4)
+ // Storage: Refungible TokenData (r:0 w:4)
+ // Storage: Refungible Owned (r:0 w:4)
+ fn create_multiple_items_ex_multiple_items(b: u32, ) -> Weight {
+ (11_953_000 as Weight)
+ // Standard Error: 27_000
+ .saturating_add((10_775_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))
+ .saturating_add(T::DbWeight::get().writes((5 as Weight).saturating_mul(b as Weight)))
+ }
+ // Storage: Refungible TokensMinted (r:1 w:1)
+ // Storage: Refungible TotalSupply (r:0 w:1)
+ // Storage: Refungible TokenData (r:0 w:1)
+ // Storage: Refungible AccountBalance (r:4 w:4)
+ // Storage: Refungible Balance (r:0 w:4)
+ // Storage: Refungible Owned (r:0 w:4)
+ fn create_multiple_items_ex_multiple_owners(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 13_000
+ .saturating_add((8_528_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))
+ .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(b as Weight)))
+ }
// Storage: Refungible TotalSupply (r:1 w:1)
// Storage: Refungible Balance (r:1 w:1)
// Storage: Refungible AccountBalance (r:1 w:1)
@@ -215,6 +247,36 @@
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
.saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(b as Weight)))
}
+ // Storage: Refungible TokensMinted (r:1 w:1)
+ // Storage: Refungible AccountBalance (r:4 w:4)
+ // Storage: Refungible Balance (r:0 w:4)
+ // Storage: Refungible TotalSupply (r:0 w:4)
+ // Storage: Refungible TokenData (r:0 w:4)
+ // Storage: Refungible Owned (r:0 w:4)
+ fn create_multiple_items_ex_multiple_items(b: u32, ) -> Weight {
+ (11_953_000 as Weight)
+ // Standard Error: 27_000
+ .saturating_add((10_775_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))
+ .saturating_add(RocksDbWeight::get().writes((5 as Weight).saturating_mul(b as Weight)))
+ }
+ // Storage: Refungible TokensMinted (r:1 w:1)
+ // Storage: Refungible TotalSupply (r:0 w:1)
+ // Storage: Refungible TokenData (r:0 w:1)
+ // Storage: Refungible AccountBalance (r:4 w:4)
+ // Storage: Refungible Balance (r:0 w:4)
+ // Storage: Refungible Owned (r:0 w:4)
+ fn create_multiple_items_ex_multiple_owners(b: u32, ) -> Weight {
+ (0 as Weight)
+ // Standard Error: 13_000
+ .saturating_add((8_528_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))
+ .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(b as Weight)))
+ }
// Storage: Refungible TotalSupply (r:1 w:1)
// Storage: Refungible Balance (r:1 w:1)
// Storage: Refungible AccountBalance (r:1 w:1)
pallets/unique/src/common.rsdiffbeforeafterboth--- a/pallets/unique/src/common.rs
+++ b/pallets/unique/src/common.rs
@@ -5,6 +5,7 @@
use pallet_fungible::{common::CommonWeights as FungibleWeights};
use pallet_nonfungible::{common::CommonWeights as NonfungibleWeights};
use pallet_refungible::{common::CommonWeights as RefungibleWeights};
+use up_data_structs::CreateItemExData;
use crate::{Config, dispatch::dispatch_weight};
@@ -17,7 +18,7 @@
}
pub struct CommonWeights<T: Config>(PhantomData<T>);
-impl<T: Config> CommonWeightInfo for CommonWeights<T> {
+impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
fn create_item() -> up_data_structs::Weight {
dispatch_weight::<T>() + max_weight_of!(create_item())
}
@@ -26,6 +27,10 @@
dispatch_weight::<T>() + max_weight_of!(create_multiple_items(amount))
}
+ fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(create_multiple_items_ex(data))
+ }
+
fn burn_item() -> Weight {
dispatch_weight::<T>() + max_weight_of!(burn_item())
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -40,7 +40,7 @@
OFFCHAIN_SCHEMA_LIMIT, MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH,
MAX_TOKEN_PREFIX_LENGTH, AccessMode, CreateItemData, CollectionLimits, CollectionId,
CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
- CreateCollectionData, CustomDataLimit,
+ CreateCollectionData, CustomDataLimit, CreateItemExData,
};
use pallet_common::{
account::CrossAccountId, CollectionHandle, Pallet as PalletCommon, Error as CommonError,
@@ -735,6 +735,14 @@
dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data))
}
+ #[weight = <CommonWeights<T>>::create_multiple_items_ex(&data)]
+ #[transactional]
+ pub fn create_multiple_items_ex(origin, collection_id: CollectionId, data: CreateItemExData<T::CrossAccountId>) -> DispatchResultWithPostInfo {
+ let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+
+ dispatch_call::<T, _>(collection_id, |d| d.create_multiple_items_ex(sender, data))
+ }
+
// TODO! transaction weight
/// Set transfers_enabled value for particular collection
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -1,6 +1,11 @@
#![cfg_attr(not(feature = "std"), no_std)]
-use core::convert::{TryFrom, TryInto};
+use core::{
+ convert::{TryFrom, TryInto},
+ fmt,
+};
+use frame_support::storage::bounded_btree_map::BoundedBTreeMap;
+use sp_std::collections::btree_map::BTreeMap;
#[cfg(feature = "serde")]
pub use serde::{Serialize, Deserialize};
@@ -525,6 +530,47 @@
ReFungible(CreateReFungibleData),
}
+#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
+#[derivative(Debug)]
+pub struct CreateNftExData<CrossAccountId> {
+ #[derivative(Debug(format_with = "bounded_debug"))]
+ pub const_data: BoundedVec<u8, CustomDataLimit>,
+ #[derivative(Debug(format_with = "bounded_debug"))]
+ pub variable_data: BoundedVec<u8, CustomDataLimit>,
+ pub owner: CrossAccountId,
+}
+
+#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
+#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]
+pub struct CreateRefungibleExData<CrossAccountId> {
+ #[derivative(Debug(format_with = "bounded_debug"))]
+ pub const_data: BoundedVec<u8, CustomDataLimit>,
+ #[derivative(Debug(format_with = "bounded_debug"))]
+ pub variable_data: BoundedVec<u8, CustomDataLimit>,
+ #[derivative(Debug(format_with = "bounded_map_debug"))]
+ pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,
+}
+
+#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]
+#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]
+pub enum CreateItemExData<CrossAccountId> {
+ NFT(
+ #[derivative(Debug(format_with = "bounded_debug"))]
+ BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,
+ ),
+ Fungible(
+ #[derivative(Debug(format_with = "bounded_map_debug"))]
+ BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,
+ ),
+ /// Many tokens, each may have only one owner
+ RefungibleMultipleItems(
+ #[derivative(Debug(format_with = "bounded_debug"))]
+ BoundedVec<CreateRefungibleExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,
+ ),
+ /// Single token, which may have many owners
+ RefungibleMultipleOwners(CreateRefungibleExData<CrossAccountId>),
+}
+
impl CreateItemData {
pub fn data_size(&self) -> usize {
match self {