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::{26 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,27};28use pallet_structure::Pallet as PalletStructure;29use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};30use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};31use core::ops::Deref;32use codec::{Encode, Decode, MaxEncodedLen};33use scale_info::TypeInfo;3435pub use pallet::*;36#[cfg(feature = "runtime-benchmarks")]37pub mod benchmarking;38pub mod common;39pub mod erc;40pub mod weights;41pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;4243#[struct_versioning::versioned(version = 2, upper)]44#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]45pub struct ItemData {46 pub const_data: BoundedVec<u8, CustomDataLimit>,4748 #[version(..2)]49 pub variable_data: BoundedVec<u8, CustomDataLimit>,50}5152#[frame_support::pallet]53pub mod pallet {54 use super::*;55 use frame_support::{56 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,57 traits::StorageVersion,58 };59 use frame_system::pallet_prelude::*;60 use up_data_structs::{CollectionId, TokenId};61 use super::weights::WeightInfo;6263 #[pallet::error]64 pub enum Error<T> {65 66 NotRefungibleDataUsedToMintFungibleCollectionToken,67 68 WrongRefungiblePieces,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::AccountId,203 data: CreateCollectionData<T::AccountId>,204 ) -> Result<CollectionId, DispatchError> {205 <PalletCommon<T>>::init_collection(owner, data)206 }207 pub fn destroy_collection(208 collection: RefungibleHandle<T>,209 sender: &T::CrossAccountId,210 ) -> DispatchResult {211 let id = collection.id;212213 214215 PalletCommon::destroy_collection(collection.0, sender)?;216217 <TokensMinted<T>>::remove(id);218 <TokensBurnt<T>>::remove(id);219 <TokenData<T>>::remove_prefix((id,), None);220 <TotalSupply<T>>::remove_prefix((id,), None);221 <Balance<T>>::remove_prefix((id,), None);222 <Allowance<T>>::remove_prefix((id,), None);223 <Owned<T>>::remove_prefix((id,), None);224 <AccountBalance<T>>::remove_prefix((id,), None);225 Ok(())226 }227228 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {229 let burnt = <TokensBurnt<T>>::get(collection.id)230 .checked_add(1)231 .ok_or(ArithmeticError::Overflow)?;232233 <TokensBurnt<T>>::insert(collection.id, burnt);234 <TokenData<T>>::remove((collection.id, token_id));235 <TotalSupply<T>>::remove((collection.id, token_id));236 <Balance<T>>::remove_prefix((collection.id, token_id), None);237 <Allowance<T>>::remove_prefix((collection.id, token_id), None);238 239 Ok(())240 }241242 pub fn burn(243 collection: &RefungibleHandle<T>,244 owner: &T::CrossAccountId,245 token: TokenId,246 amount: u128,247 ) -> DispatchResult {248 Self::burn_item_unchecked(collection, owner, token, amount)?;249250 251 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(252 collection.id,253 token,254 owner.clone(),255 amount,256 ));257258 Ok(())259 }260261 pub fn burn_item_unchecked(262 collection: &RefungibleHandle<T>,263 owner: &T::CrossAccountId,264 token: TokenId,265 amount: u128,266 ) -> DispatchResult {267 let total_supply = <TotalSupply<T>>::get((collection.id, token))268 .checked_sub(amount)269 .ok_or(<CommonError<T>>::TokenValueTooLow)?;270271 272 if total_supply == 0 {273 274 ensure!(275 <Balance<T>>::get((collection.id, token, owner)) == amount,276 <CommonError<T>>::TokenValueTooLow277 );278 let account_balance = <AccountBalance<T>>::get((collection.id, owner))279 .checked_sub(1)280 281 .ok_or(ArithmeticError::Underflow)?;282283 284285 <Owned<T>>::remove((collection.id, owner, token));286 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);287 <AccountBalance<T>>::insert((collection.id, owner), account_balance);288 Self::burn_token(collection, token)?;289 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(290 collection.id,291 token,292 owner.clone(),293 amount,294 ));295 return Ok(());296 }297298 let balance = <Balance<T>>::get((collection.id, token, owner))299 .checked_sub(amount)300 .ok_or(<CommonError<T>>::TokenValueTooLow)?;301 let account_balance = if balance == 0 {302 <AccountBalance<T>>::get((collection.id, owner))303 .checked_sub(1)304 305 .ok_or(ArithmeticError::Underflow)?306 } else {307 0308 };309310 311312 if balance == 0 {313 <Owned<T>>::remove((collection.id, owner, token));314 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);315 <Balance<T>>::remove((collection.id, token, owner));316 <AccountBalance<T>>::insert((collection.id, owner), account_balance);317 } else {318 <Balance<T>>::insert((collection.id, token, owner), balance);319 }320 <TotalSupply<T>>::insert((collection.id, token), total_supply);321 Ok(())322 }323324 pub fn transfer(325 collection: &RefungibleHandle<T>,326 from: &T::CrossAccountId,327 to: &T::CrossAccountId,328 token: TokenId,329 amount: u128,330 nesting_budget: &dyn Budget,331 ) -> DispatchResult {332 ensure!(333 collection.limits.transfers_enabled(),334 <CommonError<T>>::TransferNotAllowed335 );336337 if collection.permissions.access() == AccessMode::AllowList {338 collection.check_allowlist(from)?;339 collection.check_allowlist(to)?;340 }341 <PalletCommon<T>>::ensure_correct_receiver(to)?;342343 let balance_from = <Balance<T>>::get((collection.id, token, from))344 .checked_sub(amount)345 .ok_or(<CommonError<T>>::TokenValueTooLow)?;346 let mut create_target = false;347 let from_to_differ = from != to;348 let balance_to = if from != to {349 let old_balance = <Balance<T>>::get((collection.id, token, to));350 if old_balance == 0 {351 create_target = true;352 }353 Some(354 old_balance355 .checked_add(amount)356 .ok_or(ArithmeticError::Overflow)?,357 )358 } else {359 None360 };361362 let account_balance_from = if balance_from == 0 {363 Some(364 <AccountBalance<T>>::get((collection.id, from))365 .checked_sub(1)366 367 .ok_or(ArithmeticError::Underflow)?,368 )369 } else {370 None371 };372 373 374 let account_balance_to = if create_target && from_to_differ {375 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))376 .checked_add(1)377 .ok_or(ArithmeticError::Overflow)?;378 ensure!(379 account_balance_to < collection.limits.account_token_ownership_limit(),380 <CommonError<T>>::AccountTokenLimitExceeded,381 );382383 Some(account_balance_to)384 } else {385 None386 };387388 389390 <PalletStructure<T>>::try_nest_if_sent_to_token(391 from.clone(),392 to,393 collection.id,394 token,395 nesting_budget396 )?;397398 if let Some(balance_to) = balance_to {399 400 if balance_from == 0 {401 <Balance<T>>::remove((collection.id, token, from));402 } else {403 <Balance<T>>::insert((collection.id, token, from), balance_from);404 }405 <Balance<T>>::insert((collection.id, token, to), balance_to);406 if let Some(account_balance_from) = account_balance_from {407 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);408 <Owned<T>>::remove((collection.id, from, token));409 }410 if let Some(account_balance_to) = account_balance_to {411 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);412 <Owned<T>>::insert((collection.id, to, token), true);413 }414 }415416 417 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(418 collection.id,419 token,420 from.clone(),421 to.clone(),422 amount,423 ));424 Ok(())425 }426427 pub fn create_multiple_items(428 collection: &RefungibleHandle<T>,429 sender: &T::CrossAccountId,430 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,431 nesting_budget: &dyn Budget,432 ) -> DispatchResult {433 if !collection.is_owner_or_admin(sender) {434 ensure!(435 collection.permissions.mint_mode(),436 <CommonError<T>>::PublicMintingNotAllowed437 );438 collection.check_allowlist(sender)?;439440 for item in data.iter() {441 for user in item.users.keys() {442 collection.check_allowlist(user)?;443 }444 }445 }446447 for item in data.iter() {448 for (owner, _) in item.users.iter() {449 <PalletCommon<T>>::ensure_correct_receiver(owner)?;450 }451 }452453 454 let totals = data455 .iter()456 .map(|data| {457 Ok(data458 .users459 .iter()460 .map(|u| u.1)461 .try_fold(0u128, |acc, v| acc.checked_add(*v))462 .ok_or(ArithmeticError::Overflow)?)463 })464 .collect::<Result<Vec<_>, DispatchError>>()?;465 for total in &totals {466 ensure!(467 *total <= MAX_REFUNGIBLE_PIECES,468 <Error<T>>::WrongRefungiblePieces469 );470 }471472 let first_token_id = <TokensMinted<T>>::get(collection.id);473 let tokens_minted = first_token_id474 .checked_add(data.len() as u32)475 .ok_or(ArithmeticError::Overflow)?;476 ensure!(477 tokens_minted < collection.limits.token_limit(),478 <CommonError<T>>::CollectionTokenLimitExceeded479 );480481 let mut balances = BTreeMap::new();482 for data in &data {483 for owner in data.users.keys() {484 let balance = balances485 .entry(owner)486 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));487 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;488489 ensure!(490 *balance <= collection.limits.account_token_ownership_limit(),491 <CommonError<T>>::AccountTokenLimitExceeded,492 );493 }494 }495496 for (i, token) in data.iter().enumerate() {497 let token_id = TokenId(first_token_id + i as u32 + 1);498 for (to, _) in token.users.iter() {499500 <PalletStructure<T>>::check_nesting(501 sender.clone(),502 to,503 collection.id,504 token_id,505 nesting_budget,506 )?;507 }508 }509510 511512 <TokensMinted<T>>::insert(collection.id, tokens_minted);513 for (account, balance) in balances {514 <AccountBalance<T>>::insert((collection.id, account), balance);515 }516 for (i, token) in data.into_iter().enumerate() {517 let token_id = first_token_id + i as u32 + 1;518 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);519520 <TokenData<T>>::insert(521 (collection.id, token_id),522 ItemData {523 const_data: token.const_data,524 },525 );526527 for (user, amount) in token.users.into_iter() {528 if amount == 0 {529 continue;530 }531 <Balance<T>>::insert((collection.id, token_id, &user), amount);532 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);533 <PalletStructure<T>>::nest_if_sent_to_token(&user, collection.id, TokenId(token_id));534535 536 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(537 collection.id,538 TokenId(token_id),539 user,540 amount,541 ));542 }543 }544 Ok(())545 }546547 pub fn set_allowance_unchecked(548 collection: &RefungibleHandle<T>,549 sender: &T::CrossAccountId,550 spender: &T::CrossAccountId,551 token: TokenId,552 amount: u128,553 ) {554 if amount == 0 {555 <Allowance<T>>::remove((collection.id, token, sender, spender));556 } else {557 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);558 }559 560 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(561 collection.id,562 token,563 sender.clone(),564 spender.clone(),565 amount,566 ))567 }568569 pub fn set_allowance(570 collection: &RefungibleHandle<T>,571 sender: &T::CrossAccountId,572 spender: &T::CrossAccountId,573 token: TokenId,574 amount: u128,575 ) -> DispatchResult {576 if collection.permissions.access() == AccessMode::AllowList {577 collection.check_allowlist(sender)?;578 collection.check_allowlist(spender)?;579 }580581 <PalletCommon<T>>::ensure_correct_receiver(spender)?;582583 if <Balance<T>>::get((collection.id, token, sender)) < amount {584 ensure!(585 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),586 <CommonError<T>>::CantApproveMoreThanOwned587 );588 }589590 591592 Self::set_allowance_unchecked(collection, sender, spender, token, amount);593 Ok(())594 }595596 597 fn check_allowed(598 collection: &RefungibleHandle<T>,599 spender: &T::CrossAccountId,600 from: &T::CrossAccountId,601 token: TokenId,602 amount: u128,603 nesting_budget: &dyn Budget,604 ) -> Result<Option<u128>, DispatchError> {605 if spender.conv_eq(from) {606 return Ok(None);607 }608 if collection.permissions.access() == AccessMode::AllowList {609 610 collection.check_allowlist(spender)?;611 }612 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {613 614 ensure!(615 <PalletStructure<T>>::check_indirectly_owned(616 spender.clone(),617 source.0,618 source.1,619 None,620 nesting_budget621 )?,622 <CommonError<T>>::ApprovedValueTooLow,623 );624 return Ok(None);625 }626 let allowance =627 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);628 if allowance.is_none() {629 ensure!(630 collection.ignores_allowance(spender),631 <CommonError<T>>::ApprovedValueTooLow632 );633 }634 Ok(allowance)635 }636637 pub fn transfer_from(638 collection: &RefungibleHandle<T>,639 spender: &T::CrossAccountId,640 from: &T::CrossAccountId,641 to: &T::CrossAccountId,642 token: TokenId,643 amount: u128,644 nesting_budget: &dyn Budget,645 ) -> DispatchResult {646 let allowance =647 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;648649 650651 Self::transfer(collection, from, to, token, amount, nesting_budget)?;652 if let Some(allowance) = allowance {653 Self::set_allowance_unchecked(collection, from, spender, token, allowance);654 }655 Ok(())656 }657658 pub fn burn_from(659 collection: &RefungibleHandle<T>,660 spender: &T::CrossAccountId,661 from: &T::CrossAccountId,662 token: TokenId,663 amount: u128,664 nesting_budget: &dyn Budget,665 ) -> DispatchResult {666 let allowance =667 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;668669 670671 Self::burn(collection, from, token, amount)?;672 if let Some(allowance) = allowance {673 Self::set_allowance_unchecked(collection, from, spender, token, allowance);674 }675 Ok(())676 }677678 679 pub fn create_item(680 collection: &RefungibleHandle<T>,681 sender: &T::CrossAccountId,682 data: CreateRefungibleExData<T::CrossAccountId>,683 nesting_budget: &dyn Budget,684 ) -> DispatchResult {685 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)686 }687}