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, 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 45 NotRefungibleDataUsedToMintFungibleCollectionToken,46 47 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 81 #[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 97 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 109 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 121 Key<Blake2_128, T::CrossAccountId>,122 123 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}155156157impl<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 196 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 210 if total_supply == 0 {211 212 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 219 .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 242 .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 258 <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 309 .ok_or(ArithmeticError::Underflow)?,310 )311 } else {312 None313 };314 315 316 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 334 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 351 <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 387 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 453 <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 477 <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 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 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 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}