1234567891011121314151617#![cfg_attr(not(feature = "std"), no_std)]1819use frame_support::{ensure, BoundedVec};20use up_data_structs::{21 AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,22 CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping, budget::Budget,23};24use pallet_evm::account::CrossAccountId;25use pallet_common::{Error as CommonError, Event as CommonEvent, Pallet as PalletCommon};26use pallet_structure::Pallet as PalletStructure;27use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};28use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};29use core::ops::Deref;30use codec::{Encode, Decode, MaxEncodedLen};31use scale_info::TypeInfo;3233pub use pallet::*;34#[cfg(feature = "runtime-benchmarks")]35pub mod benchmarking;36pub mod common;37pub mod erc;38pub mod weights;39pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4041#[struct_versioning::versioned(version = 2, upper)]42#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]43pub struct ItemData {44 pub const_data: BoundedVec<u8, CustomDataLimit>,4546 #[version(..2)]47 pub variable_data: BoundedVec<u8, CustomDataLimit>,48}4950#[frame_support::pallet]51pub mod pallet {52 use super::*;53 use frame_support::{54 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,55 traits::StorageVersion,56 };57 use frame_system::pallet_prelude::*;58 use up_data_structs::{CollectionId, TokenId};59 use super::weights::WeightInfo;6061 #[pallet::error]62 pub enum Error<T> {63 64 NotRefungibleDataUsedToMintFungibleCollectionToken,65 66 WrongRefungiblePieces,67 68 RepartitionWhileNotOwningAllPieces,69 70 RefungibleDisallowsNesting,71 72 SettingPropertiesNotAllowed,73 }7475 #[pallet::config]76 pub trait Config:77 frame_system::Config + pallet_common::Config + pallet_structure::Config78 {79 type WeightInfo: WeightInfo;80 }8182 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);8384 #[pallet::pallet]85 #[pallet::storage_version(STORAGE_VERSION)]86 #[pallet::generate_store(pub(super) trait Store)]87 pub struct Pallet<T>(_);8889 #[pallet::storage]90 pub type TokensMinted<T: Config> =91 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;92 #[pallet::storage]93 pub type TokensBurnt<T: Config> =94 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;9596 #[pallet::storage]97 pub type TokenData<T: Config> = StorageNMap<98 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),99 Value = ItemData,100 QueryKind = ValueQuery,101 >;102103 #[pallet::storage]104 pub type TotalSupply<T: Config> = StorageNMap<105 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),106 Value = u128,107 QueryKind = ValueQuery,108 >;109110 111 #[pallet::storage]112 pub type Owned<T: Config> = StorageNMap<113 Key = (114 Key<Twox64Concat, CollectionId>,115 Key<Blake2_128Concat, T::CrossAccountId>,116 Key<Twox64Concat, TokenId>,117 ),118 Value = bool,119 QueryKind = ValueQuery,120 >;121122 #[pallet::storage]123 pub type AccountBalance<T: Config> = StorageNMap<124 Key = (125 Key<Twox64Concat, CollectionId>,126 127 Key<Blake2_128Concat, T::CrossAccountId>,128 ),129 Value = u32,130 QueryKind = ValueQuery,131 >;132133 #[pallet::storage]134 pub type Balance<T: Config> = StorageNMap<135 Key = (136 Key<Twox64Concat, CollectionId>,137 Key<Twox64Concat, TokenId>,138 139 Key<Blake2_128Concat, T::CrossAccountId>,140 ),141 Value = u128,142 QueryKind = ValueQuery,143 >;144145 #[pallet::storage]146 pub type Allowance<T: Config> = StorageNMap<147 Key = (148 Key<Twox64Concat, CollectionId>,149 Key<Twox64Concat, TokenId>,150 151 Key<Blake2_128, T::CrossAccountId>,152 153 Key<Blake2_128Concat, T::CrossAccountId>,154 ),155 Value = u128,156 QueryKind = ValueQuery,157 >;158159 #[pallet::hooks]160 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {161 fn on_runtime_upgrade() -> Weight {162 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {163 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {164 Some(<ItemDataVersion2>::from(v))165 })166 }167168 0169 }170 }171}172173pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);174impl<T: Config> RefungibleHandle<T> {175 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {176 Self(inner)177 }178 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {179 self.0180 }181}182impl<T: Config> Deref for RefungibleHandle<T> {183 type Target = pallet_common::CollectionHandle<T>;184185 fn deref(&self) -> &Self::Target {186 &self.0187 }188}189190impl<T: Config> Pallet<T> {191 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {192 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)193 }194 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {195 <TotalSupply<T>>::contains_key((collection.id, token))196 }197}198199200impl<T: Config> Pallet<T> {201 pub fn init_collection(202 owner: T::CrossAccountId,203 data: CreateCollectionData<T::AccountId>,204 ) -> Result<CollectionId, DispatchError> {205 <PalletCommon<T>>::init_collection(owner, data, false)206 }207 pub fn destroy_collection(208 collection: RefungibleHandle<T>,209 sender: &T::CrossAccountId,210 ) -> DispatchResult {211 let id = collection.id;212213 if Self::collection_has_tokens(id) {214 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());215 }216217 218219 PalletCommon::destroy_collection(collection.0, sender)?;220221 <TokensMinted<T>>::remove(id);222 <TokensBurnt<T>>::remove(id);223 <TokenData<T>>::remove_prefix((id,), None);224 <TotalSupply<T>>::remove_prefix((id,), None);225 <Balance<T>>::remove_prefix((id,), None);226 <Allowance<T>>::remove_prefix((id,), None);227 <Owned<T>>::remove_prefix((id,), None);228 <AccountBalance<T>>::remove_prefix((id,), None);229 Ok(())230 }231232 fn collection_has_tokens(collection_id: CollectionId) -> bool {233 <TokenData<T>>::iter_prefix((collection_id,))234 .next()235 .is_some()236 }237238 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {239 let burnt = <TokensBurnt<T>>::get(collection.id)240 .checked_add(1)241 .ok_or(ArithmeticError::Overflow)?;242243 <TokensBurnt<T>>::insert(collection.id, burnt);244 <TokenData<T>>::remove((collection.id, token_id));245 <TotalSupply<T>>::remove((collection.id, token_id));246 <Balance<T>>::remove_prefix((collection.id, token_id), None);247 <Allowance<T>>::remove_prefix((collection.id, token_id), None);248 249 Ok(())250 }251252 pub fn burn(253 collection: &RefungibleHandle<T>,254 owner: &T::CrossAccountId,255 token: TokenId,256 amount: u128,257 ) -> DispatchResult {258 let total_supply = <TotalSupply<T>>::get((collection.id, token))259 .checked_sub(amount)260 .ok_or(<CommonError<T>>::TokenValueTooLow)?;261262 263 if total_supply == 0 {264 265 ensure!(266 <Balance<T>>::get((collection.id, token, owner)) == amount,267 <CommonError<T>>::TokenValueTooLow268 );269 let account_balance = <AccountBalance<T>>::get((collection.id, owner))270 .checked_sub(1)271 272 .ok_or(ArithmeticError::Underflow)?;273274 275276 <Owned<T>>::remove((collection.id, owner, token));277 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);278 <AccountBalance<T>>::insert((collection.id, owner), account_balance);279 Self::burn_token(collection, token)?;280 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(281 collection.id,282 token,283 owner.clone(),284 amount,285 ));286 return Ok(());287 }288289 let balance = <Balance<T>>::get((collection.id, token, owner))290 .checked_sub(amount)291 .ok_or(<CommonError<T>>::TokenValueTooLow)?;292 let account_balance = if balance == 0 {293 <AccountBalance<T>>::get((collection.id, owner))294 .checked_sub(1)295 296 .ok_or(ArithmeticError::Underflow)?297 } else {298 0299 };300301 302303 if balance == 0 {304 <Owned<T>>::remove((collection.id, owner, token));305 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);306 <Balance<T>>::remove((collection.id, token, owner));307 <AccountBalance<T>>::insert((collection.id, owner), account_balance);308 } else {309 <Balance<T>>::insert((collection.id, token, owner), balance);310 }311 <TotalSupply<T>>::insert((collection.id, token), total_supply);312 313 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(314 collection.id,315 token,316 owner.clone(),317 amount,318 ));319 Ok(())320 }321322 pub fn transfer(323 collection: &RefungibleHandle<T>,324 from: &T::CrossAccountId,325 to: &T::CrossAccountId,326 token: TokenId,327 amount: u128,328 nesting_budget: &dyn Budget,329 ) -> DispatchResult {330 ensure!(331 collection.limits.transfers_enabled(),332 <CommonError<T>>::TransferNotAllowed333 );334335 if collection.permissions.access() == AccessMode::AllowList {336 collection.check_allowlist(from)?;337 collection.check_allowlist(to)?;338 }339 <PalletCommon<T>>::ensure_correct_receiver(to)?;340341 let balance_from = <Balance<T>>::get((collection.id, token, from))342 .checked_sub(amount)343 .ok_or(<CommonError<T>>::TokenValueTooLow)?;344 let mut create_target = false;345 let from_to_differ = from != to;346 let balance_to = if from != to {347 let old_balance = <Balance<T>>::get((collection.id, token, to));348 if old_balance == 0 {349 create_target = true;350 }351 Some(352 old_balance353 .checked_add(amount)354 .ok_or(ArithmeticError::Overflow)?,355 )356 } else {357 None358 };359360 let account_balance_from = if balance_from == 0 {361 Some(362 <AccountBalance<T>>::get((collection.id, from))363 .checked_sub(1)364 365 .ok_or(ArithmeticError::Underflow)?,366 )367 } else {368 None369 };370 371 372 let account_balance_to = if create_target && from_to_differ {373 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))374 .checked_add(1)375 .ok_or(ArithmeticError::Overflow)?;376 ensure!(377 account_balance_to < collection.limits.account_token_ownership_limit(),378 <CommonError<T>>::AccountTokenLimitExceeded,379 );380381 Some(account_balance_to)382 } else {383 None384 };385386 387388 <PalletStructure<T>>::nest_if_sent_to_token(389 from.clone(),390 to,391 collection.id,392 token,393 nesting_budget,394 )?;395396 if let Some(balance_to) = balance_to {397 398 if balance_from == 0 {399 <Balance<T>>::remove((collection.id, token, from));400 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);401 } else {402 <Balance<T>>::insert((collection.id, token, from), balance_from);403 }404 <Balance<T>>::insert((collection.id, token, to), balance_to);405 if let Some(account_balance_from) = account_balance_from {406 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);407 <Owned<T>>::remove((collection.id, from, token));408 }409 if let Some(account_balance_to) = account_balance_to {410 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);411 <Owned<T>>::insert((collection.id, to, token), true);412 }413 }414415 416 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(417 collection.id,418 token,419 from.clone(),420 to.clone(),421 amount,422 ));423 Ok(())424 }425426 pub fn create_multiple_items(427 collection: &RefungibleHandle<T>,428 sender: &T::CrossAccountId,429 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,430 nesting_budget: &dyn Budget,431 ) -> DispatchResult {432 if !collection.is_owner_or_admin(sender) {433 ensure!(434 collection.permissions.mint_mode(),435 <CommonError<T>>::PublicMintingNotAllowed436 );437 collection.check_allowlist(sender)?;438439 for item in data.iter() {440 for user in item.users.keys() {441 collection.check_allowlist(user)?;442 }443 }444 }445446 for item in data.iter() {447 for (owner, _) in item.users.iter() {448 <PalletCommon<T>>::ensure_correct_receiver(owner)?;449 }450 }451452 453 let totals = data454 .iter()455 .map(|data| {456 Ok(data457 .users458 .iter()459 .map(|u| u.1)460 .try_fold(0u128, |acc, v| acc.checked_add(*v))461 .ok_or(ArithmeticError::Overflow)?)462 })463 .collect::<Result<Vec<_>, DispatchError>>()?;464 for total in &totals {465 ensure!(466 *total <= MAX_REFUNGIBLE_PIECES,467 <Error<T>>::WrongRefungiblePieces468 );469 }470471 let first_token_id = <TokensMinted<T>>::get(collection.id);472 let tokens_minted = first_token_id473 .checked_add(data.len() as u32)474 .ok_or(ArithmeticError::Overflow)?;475 ensure!(476 tokens_minted < collection.limits.token_limit(),477 <CommonError<T>>::CollectionTokenLimitExceeded478 );479480 let mut balances = BTreeMap::new();481 for data in &data {482 for owner in data.users.keys() {483 let balance = balances484 .entry(owner)485 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));486 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;487488 ensure!(489 *balance <= collection.limits.account_token_ownership_limit(),490 <CommonError<T>>::AccountTokenLimitExceeded,491 );492 }493 }494495 for (i, token) in data.iter().enumerate() {496 let token_id = TokenId(first_token_id + i as u32 + 1);497 for (to, _) in token.users.iter() {498 <PalletStructure<T>>::check_nesting(499 sender.clone(),500 to,501 collection.id,502 token_id,503 nesting_budget,504 )?;505 }506 }507508 509510 <TokensMinted<T>>::insert(collection.id, tokens_minted);511 for (account, balance) in balances {512 <AccountBalance<T>>::insert((collection.id, account), balance);513 }514 for (i, token) in data.into_iter().enumerate() {515 let token_id = first_token_id + i as u32 + 1;516 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);517518 <TokenData<T>>::insert(519 (collection.id, token_id),520 ItemData {521 const_data: token.const_data,522 },523 );524525 for (user, amount) in token.users.into_iter() {526 if amount == 0 {527 continue;528 }529 <Balance<T>>::insert((collection.id, token_id, &user), amount);530 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);531 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(532 &user,533 collection.id,534 TokenId(token_id),535 );536537 538 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(539 collection.id,540 TokenId(token_id),541 user,542 amount,543 ));544 }545 }546 Ok(())547 }548549 pub fn set_allowance_unchecked(550 collection: &RefungibleHandle<T>,551 sender: &T::CrossAccountId,552 spender: &T::CrossAccountId,553 token: TokenId,554 amount: u128,555 ) {556 if amount == 0 {557 <Allowance<T>>::remove((collection.id, token, sender, spender));558 } else {559 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);560 }561 562 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(563 collection.id,564 token,565 sender.clone(),566 spender.clone(),567 amount,568 ))569 }570571 pub fn set_allowance(572 collection: &RefungibleHandle<T>,573 sender: &T::CrossAccountId,574 spender: &T::CrossAccountId,575 token: TokenId,576 amount: u128,577 ) -> DispatchResult {578 if collection.permissions.access() == AccessMode::AllowList {579 collection.check_allowlist(sender)?;580 collection.check_allowlist(spender)?;581 }582583 <PalletCommon<T>>::ensure_correct_receiver(spender)?;584585 if <Balance<T>>::get((collection.id, token, sender)) < amount {586 ensure!(587 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),588 <CommonError<T>>::CantApproveMoreThanOwned589 );590 }591592 593594 Self::set_allowance_unchecked(collection, sender, spender, token, amount);595 Ok(())596 }597598 599 fn check_allowed(600 collection: &RefungibleHandle<T>,601 spender: &T::CrossAccountId,602 from: &T::CrossAccountId,603 token: TokenId,604 amount: u128,605 nesting_budget: &dyn Budget,606 ) -> Result<Option<u128>, DispatchError> {607 if spender.conv_eq(from) {608 return Ok(None);609 }610 if collection.permissions.access() == AccessMode::AllowList {611 612 collection.check_allowlist(spender)?;613 }614 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {615 616 ensure!(617 <PalletStructure<T>>::check_indirectly_owned(618 spender.clone(),619 source.0,620 source.1,621 None,622 nesting_budget623 )?,624 <CommonError<T>>::ApprovedValueTooLow,625 );626 return Ok(None);627 }628 let allowance =629 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);630 if allowance.is_none() {631 ensure!(632 collection.ignores_allowance(spender),633 <CommonError<T>>::ApprovedValueTooLow634 );635 }636 Ok(allowance)637 }638639 pub fn transfer_from(640 collection: &RefungibleHandle<T>,641 spender: &T::CrossAccountId,642 from: &T::CrossAccountId,643 to: &T::CrossAccountId,644 token: TokenId,645 amount: u128,646 nesting_budget: &dyn Budget,647 ) -> DispatchResult {648 let allowance =649 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;650651 652653 Self::transfer(collection, from, to, token, amount, nesting_budget)?;654 if let Some(allowance) = allowance {655 Self::set_allowance_unchecked(collection, from, spender, token, allowance);656 }657 Ok(())658 }659660 pub fn burn_from(661 collection: &RefungibleHandle<T>,662 spender: &T::CrossAccountId,663 from: &T::CrossAccountId,664 token: TokenId,665 amount: u128,666 nesting_budget: &dyn Budget,667 ) -> DispatchResult {668 let allowance =669 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;670671 672673 Self::burn(collection, from, token, amount)?;674 if let Some(allowance) = allowance {675 Self::set_allowance_unchecked(collection, from, spender, token, allowance);676 }677 Ok(())678 }679680 681 pub fn create_item(682 collection: &RefungibleHandle<T>,683 sender: &T::CrossAccountId,684 data: CreateRefungibleExData<T::CrossAccountId>,685 nesting_budget: &dyn Budget,686 ) -> DispatchResult {687 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)688 }689690 pub fn repartition(691 collection: &RefungibleHandle<T>,692 owner: &T::CrossAccountId,693 token: TokenId,694 amount: u128,695 ) -> DispatchResult {696 ensure!(697 amount <= MAX_REFUNGIBLE_PIECES,698 <Error<T>>::WrongRefungiblePieces699 );700 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);701 702 let total_supply = <TotalSupply<T>>::get((collection.id, token));703 let balance = <Balance<T>>::get((collection.id, token, owner));704 ensure!(705 total_supply == balance,706 <Error<T>>::RepartitionWhileNotOwningAllPieces707 );708709 <Balance<T>>::insert((collection.id, token, owner), amount);710 <TotalSupply<T>>::insert((collection.id, token), amount);711 Ok(())712 }713714 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {715 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()716 }717}