1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use up_data_structs::{5 AccessMode, CUSTOM_DATA_LIMIT, Collection, CollectionId, CustomDataLimit,6 MAX_REFUNGIBLE_PIECES, TokenId,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};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 struct CreateItemData<T: Config> {24 pub const_data: BoundedVec<u8, CustomDataLimit>,25 pub variable_data: BoundedVec<u8, CustomDataLimit>,26 pub users: BTreeMap<T::CrossAccountId, u128>,27}28pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2930#[derive(Encode, Decode, Default, TypeInfo)]31pub struct ItemData {32 pub const_data: Vec<u8>,33 pub variable_data: Vec<u8>,34}3536#[frame_support::pallet]37pub mod pallet {38 use super::*;39 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};40 use up_data_structs::{CollectionId, TokenId};41 use super::weights::WeightInfo;4243 #[pallet::error]44 pub enum Error<T> {45 46 NotRefungibleDataUsedToMintFungibleCollectionToken,47 48 WrongRefungiblePieces,49 }5051 #[pallet::config]52 pub trait Config: frame_system::Config + pallet_common::Config {53 type WeightInfo: WeightInfo;54 }5556 #[pallet::pallet]57 #[pallet::generate_store(pub trait Store)]58 pub struct Pallet<T>(_);5960 #[pallet::storage]61 pub type TokensMinted<T: Config> =62 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;63 #[pallet::storage]64 pub type TokensBurnt<T: Config> =65 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6667 #[pallet::storage]68 pub type TokenData<T: Config> = StorageNMap<69 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),70 Value = ItemData,71 QueryKind = ValueQuery,72 >;7374 #[pallet::storage]75 pub type TotalSupply<T: Config> = StorageNMap<76 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),77 Value = u128,78 QueryKind = ValueQuery,79 >;8081 82 #[pallet::storage]83 pub type Owned<T: Config> = StorageNMap<84 Key = (85 Key<Twox64Concat, CollectionId>,86 Key<Blake2_128Concat, T::CrossAccountId>,87 Key<Twox64Concat, TokenId>,88 ),89 Value = bool,90 QueryKind = ValueQuery,91 >;9293 #[pallet::storage]94 pub type AccountBalance<T: Config> = StorageNMap<95 Key = (96 Key<Twox64Concat, CollectionId>,97 98 Key<Blake2_128Concat, T::CrossAccountId>,99 ),100 Value = u32,101 QueryKind = ValueQuery,102 >;103104 #[pallet::storage]105 pub type Balance<T: Config> = StorageNMap<106 Key = (107 Key<Twox64Concat, CollectionId>,108 Key<Twox64Concat, TokenId>,109 110 Key<Blake2_128Concat, T::CrossAccountId>,111 ),112 Value = u128,113 QueryKind = ValueQuery,114 >;115116 #[pallet::storage]117 pub type Allowance<T: Config> = StorageNMap<118 Key = (119 Key<Twox64Concat, CollectionId>,120 Key<Twox64Concat, TokenId>,121 122 Key<Blake2_128, T::CrossAccountId>,123 124 Key<Blake2_128Concat, T::CrossAccountId>,125 ),126 Value = u128,127 QueryKind = ValueQuery,128 >;129}130131pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);132impl<T: Config> RefungibleHandle<T> {133 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {134 Self(inner)135 }136 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {137 self.0138 }139}140impl<T: Config> Deref for RefungibleHandle<T> {141 type Target = pallet_common::CollectionHandle<T>;142143 fn deref(&self) -> &Self::Target {144 &self.0145 }146}147148impl<T: Config> Pallet<T> {149 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {150 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)151 }152 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {153 <TotalSupply<T>>::contains_key((collection.id, token))154 }155}156157158impl<T: Config> Pallet<T> {159 pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {160 <PalletCommon<T>>::init_collection(data)161 }162 pub fn destroy_collection(163 collection: RefungibleHandle<T>,164 sender: &T::CrossAccountId,165 ) -> DispatchResult {166 let id = collection.id;167168 169170 PalletCommon::destroy_collection(collection.0, sender)?;171172 <TokensMinted<T>>::remove(id);173 <TokensBurnt<T>>::remove(id);174 <TokenData<T>>::remove_prefix((id,), None);175 <TotalSupply<T>>::remove_prefix((id,), None);176 <Balance<T>>::remove_prefix((id,), None);177 <Allowance<T>>::remove_prefix((id,), None);178 <Owned<T>>::remove_prefix((id,), None);179 <AccountBalance<T>>::remove_prefix((id,), None);180 Ok(())181 }182183 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {184 let burnt = <TokensBurnt<T>>::get(collection.id)185 .checked_add(1)186 .ok_or(ArithmeticError::Overflow)?;187188 <TokensBurnt<T>>::insert(collection.id, burnt);189 <TokenData<T>>::remove((collection.id, token_id));190 <TotalSupply<T>>::remove((collection.id, token_id));191 <Balance<T>>::remove_prefix((collection.id, token_id), None);192 <Allowance<T>>::remove_prefix((collection.id, token_id), None);193 194 return Ok(());195 }196197 pub fn burn(198 collection: &RefungibleHandle<T>,199 owner: &T::CrossAccountId,200 token: TokenId,201 amount: u128,202 ) -> DispatchResult {203 let total_supply = <TotalSupply<T>>::get((collection.id, token))204 .checked_sub(amount)205 .ok_or(<CommonError<T>>::TokenValueTooLow)?;206207 208 if total_supply == 0 {209 210 ensure!(211 <Balance<T>>::get((collection.id, token, owner)) == amount,212 <CommonError<T>>::TokenValueTooLow213 );214 let account_balance = <AccountBalance<T>>::get((collection.id, owner))215 .checked_sub(1)216 217 .ok_or(ArithmeticError::Underflow)?;218219 220221 <Owned<T>>::remove((collection.id, owner, token));222 <AccountBalance<T>>::insert((collection.id, owner), account_balance);223 Self::burn_token(collection, token)?;224 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(225 collection.id,226 token,227 owner.clone(),228 amount,229 ));230 return Ok(());231 }232233 let balance = <Balance<T>>::get((collection.id, token, owner))234 .checked_sub(amount)235 .ok_or(<CommonError<T>>::TokenValueTooLow)?;236 let account_balance = if balance == 0 {237 <AccountBalance<T>>::get((collection.id, owner))238 .checked_sub(1)239 240 .ok_or(ArithmeticError::Underflow)?241 } else {242 0243 };244245 246247 if balance == 0 {248 <Owned<T>>::remove((collection.id, owner, token));249 <Balance<T>>::remove((collection.id, token, owner));250 <AccountBalance<T>>::insert((collection.id, owner), account_balance);251 } else {252 <Balance<T>>::insert((collection.id, token, owner), balance);253 }254 <TotalSupply<T>>::insert((collection.id, token), total_supply);255 256 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(257 collection.id,258 token,259 owner.clone(),260 amount,261 ));262 Ok(())263 }264265 pub fn transfer(266 collection: &RefungibleHandle<T>,267 from: &T::CrossAccountId,268 to: &T::CrossAccountId,269 token: TokenId,270 amount: u128,271 ) -> DispatchResult {272 ensure!(273 collection.limits.transfers_enabled(),274 <CommonError<T>>::TransferNotAllowed275 );276277 if collection.access == AccessMode::AllowList {278 collection.check_allowlist(from)?;279 collection.check_allowlist(to)?;280 }281 <PalletCommon<T>>::ensure_correct_receiver(to)?;282283 let balance_from = <Balance<T>>::get((collection.id, token, from))284 .checked_sub(amount)285 .ok_or(<CommonError<T>>::TokenValueTooLow)?;286 let mut create_target = false;287 let from_to_differ = from != to;288 let balance_to = if from != to {289 let old_balance = <Balance<T>>::get((collection.id, token, to));290 if old_balance == 0 {291 create_target = true;292 }293 Some(294 old_balance295 .checked_add(amount)296 .ok_or(ArithmeticError::Overflow)?,297 )298 } else {299 None300 };301302 let account_balance_from = if balance_from == 0 {303 Some(304 <AccountBalance<T>>::get((collection.id, from))305 .checked_sub(1)306 307 .ok_or(ArithmeticError::Underflow)?,308 )309 } else {310 None311 };312 313 314 let account_balance_to = if create_target && from_to_differ {315 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))316 .checked_add(1)317 .ok_or(ArithmeticError::Overflow)?;318 ensure!(319 account_balance_to < collection.limits.account_token_ownership_limit(),320 <CommonError<T>>::AccountTokenLimitExceeded,321 );322323 Some(account_balance_to)324 } else {325 None326 };327328 329330 if let Some(balance_to) = balance_to {331 332 if balance_from == 0 {333 <Balance<T>>::remove((collection.id, token, from));334 } else {335 <Balance<T>>::insert((collection.id, token, from), balance_from);336 }337 <Balance<T>>::insert((collection.id, token, to), balance_to);338 if let Some(account_balance_from) = account_balance_from {339 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);340 <Owned<T>>::remove((collection.id, from, token));341 }342 if let Some(account_balance_to) = account_balance_to {343 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);344 <Owned<T>>::insert((collection.id, to, token), true);345 }346 }347348 349 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(350 collection.id,351 token,352 from.clone(),353 to.clone(),354 amount,355 ));356 Ok(())357 }358359 pub fn create_multiple_items(360 collection: &RefungibleHandle<T>,361 sender: &T::CrossAccountId,362 data: Vec<CreateItemData<T>>,363 ) -> DispatchResult {364 let unrestricted_minting = collection.is_owner_or_admin(sender)?;365 if !unrestricted_minting {366 ensure!(367 collection.mint_mode,368 <CommonError<T>>::PublicMintingNotAllowed369 );370 collection.check_allowlist(sender)?;371372 for item in data.iter() {373 for (user, _) in &item.users {374 collection.check_allowlist(&user)?;375 }376 }377 }378379 for item in data.iter() {380 for (owner, _) in item.users.iter() {381 <PalletCommon<T>>::ensure_correct_receiver(owner)?;382 }383 }384385 386 let totals = data387 .iter()388 .map(|data| {389 Ok(data390 .users391 .iter()392 .map(|u| u.1)393 .try_fold(0u128, |acc, v| acc.checked_add(*v))394 .ok_or(ArithmeticError::Overflow)?)395 })396 .collect::<Result<Vec<_>, DispatchError>>()?;397 for total in &totals {398 ensure!(399 *total <= MAX_REFUNGIBLE_PIECES,400 <Error<T>>::WrongRefungiblePieces401 );402 }403404 let first_token_id = <TokensMinted<T>>::get(collection.id);405 let tokens_minted = first_token_id406 .checked_add(data.len() as u32)407 .ok_or(ArithmeticError::Overflow)?;408 ensure!(409 tokens_minted < collection.limits.token_limit(),410 <CommonError<T>>::CollectionTokenLimitExceeded411 );412413 let mut balances = BTreeMap::new();414 for data in &data {415 for (owner, _) in &data.users {416 let balance = balances417 .entry(owner)418 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));419 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;420421 ensure!(422 *balance <= collection.limits.account_token_ownership_limit(),423 <CommonError<T>>::AccountTokenLimitExceeded,424 );425 }426 }427428 429430 <TokensMinted<T>>::insert(collection.id, tokens_minted);431 for (account, balance) in balances {432 <AccountBalance<T>>::insert((collection.id, account), balance);433 }434 for (i, token) in data.into_iter().enumerate() {435 let token_id = first_token_id + i as u32 + 1;436 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);437438 <TokenData<T>>::insert(439 (collection.id, token_id),440 ItemData {441 const_data: token.const_data.into(),442 variable_data: token.variable_data.into(),443 },444 );445 for (user, amount) in token.users.into_iter() {446 if amount == 0 {447 continue;448 }449 <Balance<T>>::insert((collection.id, token_id, &user), amount);450 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);451 452 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(453 collection.id,454 TokenId(token_id),455 user,456 amount,457 ));458 }459 }460 Ok(())461 }462463 pub fn set_allowance_unchecked(464 collection: &RefungibleHandle<T>,465 sender: &T::CrossAccountId,466 spender: &T::CrossAccountId,467 token: TokenId,468 amount: u128,469 ) {470 if amount == 0 {471 <Allowance<T>>::remove((collection.id, token, sender, spender));472 } else {473 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);474 }475 476 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(477 collection.id,478 token,479 sender.clone(),480 spender.clone(),481 amount,482 ))483 }484485 pub fn set_allowance(486 collection: &RefungibleHandle<T>,487 sender: &T::CrossAccountId,488 spender: &T::CrossAccountId,489 token: TokenId,490 amount: u128,491 ) -> DispatchResult {492 if collection.access == AccessMode::AllowList {493 collection.check_allowlist(&sender)?;494 collection.check_allowlist(&spender)?;495 }496497 <PalletCommon<T>>::ensure_correct_receiver(spender)?;498499 if <Balance<T>>::get((collection.id, token, sender)) < amount {500 ensure!(501 collection.ignores_owned_amount(sender)? && Self::token_exists(collection, token),502 <CommonError<T>>::CantApproveMoreThanOwned503 );504 }505506 507508 Self::set_allowance_unchecked(collection, sender, spender, token, amount);509 Ok(())510 }511512 pub fn transfer_from(513 collection: &RefungibleHandle<T>,514 spender: &T::CrossAccountId,515 from: &T::CrossAccountId,516 to: &T::CrossAccountId,517 token: TokenId,518 amount: u128,519 ) -> DispatchResult {520 if spender.conv_eq(from) {521 return Self::transfer(collection, from, to, token, amount);522 }523 if collection.access == AccessMode::AllowList {524 525 collection.check_allowlist(spender)?;526 }527528 let allowance =529 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);530 if allowance.is_none() {531 ensure!(532 collection.ignores_allowance(spender)?,533 <CommonError<T>>::TokenValueNotEnough534 );535 }536537 538539 Self::transfer(collection, from, to, token, amount)?;540 if let Some(allowance) = allowance {541 Self::set_allowance_unchecked(collection, from, spender, token, allowance);542 }543 Ok(())544 }545546 pub fn burn_from(547 collection: &RefungibleHandle<T>,548 spender: &T::CrossAccountId,549 from: &T::CrossAccountId,550 token: TokenId,551 amount: u128,552 ) -> DispatchResult {553 if spender.conv_eq(from) {554 return Self::burn(collection, from, token, amount);555 }556 if collection.access == AccessMode::AllowList {557 558 collection.check_allowlist(spender)?;559 }560561 let allowance =562 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);563 if allowance.is_none() {564 ensure!(565 collection.ignores_allowance(spender)?,566 <CommonError<T>>::TokenValueNotEnough567 );568 }569570 571572 Self::burn(collection, from, token, amount)?;573 if let Some(allowance) = allowance {574 Self::set_allowance_unchecked(collection, from, spender, token, allowance);575 }576 Ok(())577 }578579 pub fn set_variable_metadata(580 collection: &RefungibleHandle<T>,581 sender: &T::CrossAccountId,582 token: TokenId,583 data: Vec<u8>,584 ) -> DispatchResult {585 ensure!(586 data.len() as u32 <= CUSTOM_DATA_LIMIT,587 <CommonError<T>>::TokenVariableDataLimitExceeded588 );589 collection.check_can_update_meta(590 sender,591 &T::CrossAccountId::from_sub(collection.owner.clone()),592 )?;593594 collection.consume_sstore()?;595 let token_data = <TokenData<T>>::get((collection.id, token));596597 598599 <TokenData<T>>::insert(600 (collection.id, token),601 ItemData {602 variable_data: data,603 ..token_data604 },605 );606 Ok(())607 }608609 610 pub fn create_item(611 collection: &RefungibleHandle<T>,612 sender: &T::CrossAccountId,613 data: CreateItemData<T>,614 ) -> DispatchResult {615 Self::create_multiple_items(collection, sender, vec![data])616 }617}