12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788#![cfg_attr(not(feature = "std"), no_std)]8990use frame_support::{ensure, BoundedVec};91use up_data_structs::{92 AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,93 CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping, budget::Budget,94};95use pallet_evm::account::CrossAccountId;96use pallet_common::{Error as CommonError, Event as CommonEvent, Pallet as PalletCommon};97use pallet_structure::Pallet as PalletStructure;98use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};99use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};100use core::ops::Deref;101use codec::{Encode, Decode, MaxEncodedLen};102use scale_info::TypeInfo;103104pub use pallet::*;105#[cfg(feature = "runtime-benchmarks")]106pub mod benchmarking;107pub mod common;108pub mod erc;109pub mod weights;110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[struct_versioning::versioned(version = 2, upper)]113#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]114pub struct ItemData {115 pub const_data: BoundedVec<u8, CustomDataLimit>,116117 #[version(..2)]118 pub variable_data: BoundedVec<u8, CustomDataLimit>,119}120121#[frame_support::pallet]122pub mod pallet {123 use super::*;124 use frame_support::{125 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,126 traits::StorageVersion,127 };128 use frame_system::pallet_prelude::*;129 use up_data_structs::{CollectionId, TokenId};130 use super::weights::WeightInfo;131132 #[pallet::error]133 pub enum Error<T> {134 135 NotRefungibleDataUsedToMintFungibleCollectionToken,136 137 WrongRefungiblePieces,138 139 RepartitionWhileNotOwningAllPieces,140 141 RefungibleDisallowsNesting,142 143 SettingPropertiesNotAllowed,144 }145146 #[pallet::config]147 pub trait Config:148 frame_system::Config + pallet_common::Config + pallet_structure::Config149 {150 type WeightInfo: WeightInfo;151 }152153 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);154155 #[pallet::pallet]156 #[pallet::storage_version(STORAGE_VERSION)]157 #[pallet::generate_store(pub(super) trait Store)]158 pub struct Pallet<T>(_);159160 161 #[pallet::storage]162 pub type TokensMinted<T: Config> =163 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;164165 166 #[pallet::storage]167 pub type TokensBurnt<T: Config> =168 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;169170 171 #[pallet::storage]172 pub type TokenData<T: Config> = StorageNMap<173 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),174 Value = ItemData,175 QueryKind = ValueQuery,176 >;177178 179 #[pallet::storage]180 pub type TotalSupply<T: Config> = StorageNMap<181 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),182 Value = u128,183 QueryKind = ValueQuery,184 >;185186 187 #[pallet::storage]188 pub type Owned<T: Config> = StorageNMap<189 Key = (190 Key<Twox64Concat, CollectionId>,191 Key<Blake2_128Concat, T::CrossAccountId>,192 Key<Twox64Concat, TokenId>,193 ),194 Value = bool,195 QueryKind = ValueQuery,196 >;197198 199 #[pallet::storage]200 pub type AccountBalance<T: Config> = StorageNMap<201 Key = (202 Key<Twox64Concat, CollectionId>,203 204 Key<Blake2_128Concat, T::CrossAccountId>,205 ),206 Value = u32,207 QueryKind = ValueQuery,208 >;209210 211 #[pallet::storage]212 pub type Balance<T: Config> = StorageNMap<213 Key = (214 Key<Twox64Concat, CollectionId>,215 Key<Twox64Concat, TokenId>,216 217 Key<Blake2_128Concat, T::CrossAccountId>,218 ),219 Value = u128,220 QueryKind = ValueQuery,221 >;222223 224 #[pallet::storage]225 pub type Allowance<T: Config> = StorageNMap<226 Key = (227 Key<Twox64Concat, CollectionId>,228 Key<Twox64Concat, TokenId>,229 230 Key<Blake2_128, T::CrossAccountId>,231 232 Key<Blake2_128Concat, T::CrossAccountId>,233 ),234 Value = u128,235 QueryKind = ValueQuery,236 >;237238 #[pallet::hooks]239 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {240 fn on_runtime_upgrade() -> Weight {241 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {242 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {243 Some(<ItemDataVersion2>::from(v))244 })245 }246247 0248 }249 }250}251252pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);253impl<T: Config> RefungibleHandle<T> {254 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {255 Self(inner)256 }257 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {258 self.0259 }260}261impl<T: Config> Deref for RefungibleHandle<T> {262 type Target = pallet_common::CollectionHandle<T>;263264 fn deref(&self) -> &Self::Target {265 &self.0266 }267}268269impl<T: Config> Pallet<T> {270 271 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {272 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)273 }274275 276 277 278 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {279 <TotalSupply<T>>::contains_key((collection.id, token))280 }281}282283284impl<T: Config> Pallet<T> {285 286 287 288 289 290 pub fn init_collection(291 owner: T::CrossAccountId,292 data: CreateCollectionData<T::AccountId>,293 ) -> Result<CollectionId, DispatchError> {294 <PalletCommon<T>>::init_collection(owner, data, false)295 }296297 298 299 300 301 pub fn destroy_collection(302 collection: RefungibleHandle<T>,303 sender: &T::CrossAccountId,304 ) -> DispatchResult {305 let id = collection.id;306307 if Self::collection_has_tokens(id) {308 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());309 }310311 312313 PalletCommon::destroy_collection(collection.0, sender)?;314315 <TokensMinted<T>>::remove(id);316 <TokensBurnt<T>>::remove(id);317 <TokenData<T>>::remove_prefix((id,), None);318 <TotalSupply<T>>::remove_prefix((id,), None);319 <Balance<T>>::remove_prefix((id,), None);320 <Allowance<T>>::remove_prefix((id,), None);321 <Owned<T>>::remove_prefix((id,), None);322 <AccountBalance<T>>::remove_prefix((id,), None);323 Ok(())324 }325326 fn collection_has_tokens(collection_id: CollectionId) -> bool {327 <TokenData<T>>::iter_prefix((collection_id,))328 .next()329 .is_some()330 }331332 pub fn burn_token_unchecked(333 collection: &RefungibleHandle<T>,334 token_id: TokenId,335 ) -> DispatchResult {336 let burnt = <TokensBurnt<T>>::get(collection.id)337 .checked_add(1)338 .ok_or(ArithmeticError::Overflow)?;339340 <TokensBurnt<T>>::insert(collection.id, burnt);341 <TokenData<T>>::remove((collection.id, token_id));342 <TotalSupply<T>>::remove((collection.id, token_id));343 <Balance<T>>::remove_prefix((collection.id, token_id), None);344 <Allowance<T>>::remove_prefix((collection.id, token_id), None);345 346 Ok(())347 }348349 350 351 352 353 354 355 356 357 358 359 pub fn burn(360 collection: &RefungibleHandle<T>,361 owner: &T::CrossAccountId,362 token: TokenId,363 amount: u128,364 ) -> DispatchResult {365 let total_supply = <TotalSupply<T>>::get((collection.id, token))366 .checked_sub(amount)367 .ok_or(<CommonError<T>>::TokenValueTooLow)?;368369 370 if total_supply == 0 {371 372 ensure!(373 <Balance<T>>::get((collection.id, token, owner)) == amount,374 <CommonError<T>>::TokenValueTooLow375 );376 let account_balance = <AccountBalance<T>>::get((collection.id, owner))377 .checked_sub(1)378 379 .ok_or(ArithmeticError::Underflow)?;380381 382383 <Owned<T>>::remove((collection.id, owner, token));384 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);385 <AccountBalance<T>>::insert((collection.id, owner), account_balance);386 Self::burn_token_unchecked(collection, token)?;387 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(388 collection.id,389 token,390 owner.clone(),391 amount,392 ));393 return Ok(());394 }395396 let balance = <Balance<T>>::get((collection.id, token, owner))397 .checked_sub(amount)398 .ok_or(<CommonError<T>>::TokenValueTooLow)?;399 let account_balance = if balance == 0 {400 <AccountBalance<T>>::get((collection.id, owner))401 .checked_sub(1)402 403 .ok_or(ArithmeticError::Underflow)?404 } else {405 0406 };407408 409410 if balance == 0 {411 <Owned<T>>::remove((collection.id, owner, token));412 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);413 <Balance<T>>::remove((collection.id, token, owner));414 <AccountBalance<T>>::insert((collection.id, owner), account_balance);415 } else {416 <Balance<T>>::insert((collection.id, token, owner), balance);417 }418 <TotalSupply<T>>::insert((collection.id, token), total_supply);419 420 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(421 collection.id,422 token,423 owner.clone(),424 amount,425 ));426 Ok(())427 }428429 430 431 432 433 434 435 436 437 438 pub fn transfer(439 collection: &RefungibleHandle<T>,440 from: &T::CrossAccountId,441 to: &T::CrossAccountId,442 token: TokenId,443 amount: u128,444 nesting_budget: &dyn Budget,445 ) -> DispatchResult {446 ensure!(447 collection.limits.transfers_enabled(),448 <CommonError<T>>::TransferNotAllowed449 );450451 if collection.permissions.access() == AccessMode::AllowList {452 collection.check_allowlist(from)?;453 collection.check_allowlist(to)?;454 }455 <PalletCommon<T>>::ensure_correct_receiver(to)?;456457 let balance_from = <Balance<T>>::get((collection.id, token, from))458 .checked_sub(amount)459 .ok_or(<CommonError<T>>::TokenValueTooLow)?;460 let mut create_target = false;461 let from_to_differ = from != to;462 let balance_to = if from != to {463 let old_balance = <Balance<T>>::get((collection.id, token, to));464 if old_balance == 0 {465 create_target = true;466 }467 Some(468 old_balance469 .checked_add(amount)470 .ok_or(ArithmeticError::Overflow)?,471 )472 } else {473 None474 };475476 let account_balance_from = if balance_from == 0 {477 Some(478 <AccountBalance<T>>::get((collection.id, from))479 .checked_sub(1)480 481 .ok_or(ArithmeticError::Underflow)?,482 )483 } else {484 None485 };486 487 488 let account_balance_to = if create_target && from_to_differ {489 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))490 .checked_add(1)491 .ok_or(ArithmeticError::Overflow)?;492 ensure!(493 account_balance_to < collection.limits.account_token_ownership_limit(),494 <CommonError<T>>::AccountTokenLimitExceeded,495 );496497 Some(account_balance_to)498 } else {499 None500 };501502 503504 <PalletStructure<T>>::nest_if_sent_to_token(505 from.clone(),506 to,507 collection.id,508 token,509 nesting_budget,510 )?;511512 if let Some(balance_to) = balance_to {513 514 if balance_from == 0 {515 <Balance<T>>::remove((collection.id, token, from));516 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);517 } else {518 <Balance<T>>::insert((collection.id, token, from), balance_from);519 }520 <Balance<T>>::insert((collection.id, token, to), balance_to);521 if let Some(account_balance_from) = account_balance_from {522 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);523 <Owned<T>>::remove((collection.id, from, token));524 }525 if let Some(account_balance_to) = account_balance_to {526 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);527 <Owned<T>>::insert((collection.id, to, token), true);528 }529 }530531 532 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(533 collection.id,534 token,535 from.clone(),536 to.clone(),537 amount,538 ));539 Ok(())540 }541542 543 544 545 546 547 pub fn create_multiple_items(548 collection: &RefungibleHandle<T>,549 sender: &T::CrossAccountId,550 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,551 nesting_budget: &dyn Budget,552 ) -> DispatchResult {553 if !collection.is_owner_or_admin(sender) {554 ensure!(555 collection.permissions.mint_mode(),556 <CommonError<T>>::PublicMintingNotAllowed557 );558 collection.check_allowlist(sender)?;559560 for item in data.iter() {561 for user in item.users.keys() {562 collection.check_allowlist(user)?;563 }564 }565 }566567 for item in data.iter() {568 for (owner, _) in item.users.iter() {569 <PalletCommon<T>>::ensure_correct_receiver(owner)?;570 }571 }572573 574 let totals = data575 .iter()576 .map(|data| {577 Ok(data578 .users579 .iter()580 .map(|u| u.1)581 .try_fold(0u128, |acc, v| acc.checked_add(*v))582 .ok_or(ArithmeticError::Overflow)?)583 })584 .collect::<Result<Vec<_>, DispatchError>>()?;585 for total in &totals {586 ensure!(587 *total <= MAX_REFUNGIBLE_PIECES,588 <Error<T>>::WrongRefungiblePieces589 );590 }591592 let first_token_id = <TokensMinted<T>>::get(collection.id);593 let tokens_minted = first_token_id594 .checked_add(data.len() as u32)595 .ok_or(ArithmeticError::Overflow)?;596 ensure!(597 tokens_minted < collection.limits.token_limit(),598 <CommonError<T>>::CollectionTokenLimitExceeded599 );600601 let mut balances = BTreeMap::new();602 for data in &data {603 for owner in data.users.keys() {604 let balance = balances605 .entry(owner)606 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));607 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;608609 ensure!(610 *balance <= collection.limits.account_token_ownership_limit(),611 <CommonError<T>>::AccountTokenLimitExceeded,612 );613 }614 }615616 for (i, token) in data.iter().enumerate() {617 let token_id = TokenId(first_token_id + i as u32 + 1);618 for (to, _) in token.users.iter() {619 <PalletStructure<T>>::check_nesting(620 sender.clone(),621 to,622 collection.id,623 token_id,624 nesting_budget,625 )?;626 }627 }628629 630631 <TokensMinted<T>>::insert(collection.id, tokens_minted);632 for (account, balance) in balances {633 <AccountBalance<T>>::insert((collection.id, account), balance);634 }635 for (i, token) in data.into_iter().enumerate() {636 let token_id = first_token_id + i as u32 + 1;637 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);638639 <TokenData<T>>::insert(640 (collection.id, token_id),641 ItemData {642 const_data: token.const_data,643 },644 );645646 for (user, amount) in token.users.into_iter() {647 if amount == 0 {648 continue;649 }650 <Balance<T>>::insert((collection.id, token_id, &user), amount);651 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);652 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(653 &user,654 collection.id,655 TokenId(token_id),656 );657658 659 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(660 collection.id,661 TokenId(token_id),662 user,663 amount,664 ));665 }666 }667 Ok(())668 }669670 pub fn set_allowance_unchecked(671 collection: &RefungibleHandle<T>,672 sender: &T::CrossAccountId,673 spender: &T::CrossAccountId,674 token: TokenId,675 amount: u128,676 ) {677 if amount == 0 {678 <Allowance<T>>::remove((collection.id, token, sender, spender));679 } else {680 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);681 }682 683 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(684 collection.id,685 token,686 sender.clone(),687 spender.clone(),688 amount,689 ))690 }691692 693 694 695 pub fn set_allowance(696 collection: &RefungibleHandle<T>,697 sender: &T::CrossAccountId,698 spender: &T::CrossAccountId,699 token: TokenId,700 amount: u128,701 ) -> DispatchResult {702 if collection.permissions.access() == AccessMode::AllowList {703 collection.check_allowlist(sender)?;704 collection.check_allowlist(spender)?;705 }706707 <PalletCommon<T>>::ensure_correct_receiver(spender)?;708709 if <Balance<T>>::get((collection.id, token, sender)) < amount {710 ensure!(711 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),712 <CommonError<T>>::CantApproveMoreThanOwned713 );714 }715716 717718 Self::set_allowance_unchecked(collection, sender, spender, token, amount);719 Ok(())720 }721722 723 fn check_allowed(724 collection: &RefungibleHandle<T>,725 spender: &T::CrossAccountId,726 from: &T::CrossAccountId,727 token: TokenId,728 amount: u128,729 nesting_budget: &dyn Budget,730 ) -> Result<Option<u128>, DispatchError> {731 if spender.conv_eq(from) {732 return Ok(None);733 }734 if collection.permissions.access() == AccessMode::AllowList {735 736 collection.check_allowlist(spender)?;737 }738 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {739 740 ensure!(741 <PalletStructure<T>>::check_indirectly_owned(742 spender.clone(),743 source.0,744 source.1,745 None,746 nesting_budget747 )?,748 <CommonError<T>>::ApprovedValueTooLow,749 );750 return Ok(None);751 }752 let allowance =753 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);754 if allowance.is_none() {755 ensure!(756 collection.ignores_allowance(spender),757 <CommonError<T>>::ApprovedValueTooLow758 );759 }760 Ok(allowance)761 }762763 764 765 766 767 768 769 pub fn transfer_from(770 collection: &RefungibleHandle<T>,771 spender: &T::CrossAccountId,772 from: &T::CrossAccountId,773 to: &T::CrossAccountId,774 token: TokenId,775 amount: u128,776 nesting_budget: &dyn Budget,777 ) -> DispatchResult {778 let allowance =779 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;780781 782783 Self::transfer(collection, from, to, token, amount, nesting_budget)?;784 if let Some(allowance) = allowance {785 Self::set_allowance_unchecked(collection, from, spender, token, allowance);786 }787 Ok(())788 }789790 791 792 793 794 795 796 pub fn burn_from(797 collection: &RefungibleHandle<T>,798 spender: &T::CrossAccountId,799 from: &T::CrossAccountId,800 token: TokenId,801 amount: u128,802 nesting_budget: &dyn Budget,803 ) -> DispatchResult {804 let allowance =805 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;806807 808809 Self::burn(collection, from, token, amount)?;810 if let Some(allowance) = allowance {811 Self::set_allowance_unchecked(collection, from, spender, token, allowance);812 }813 Ok(())814 }815816 817 818 819 820 821 822 823 pub fn create_item(824 collection: &RefungibleHandle<T>,825 sender: &T::CrossAccountId,826 data: CreateRefungibleExData<T::CrossAccountId>,827 nesting_budget: &dyn Budget,828 ) -> DispatchResult {829 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)830 }831832 833 834 835 836 837 838 pub fn repartition(839 collection: &RefungibleHandle<T>,840 owner: &T::CrossAccountId,841 token: TokenId,842 amount: u128,843 ) -> DispatchResult {844 ensure!(845 amount <= MAX_REFUNGIBLE_PIECES,846 <Error<T>>::WrongRefungiblePieces847 );848 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);849 850 let total_supply = <TotalSupply<T>>::get((collection.id, token));851 let balance = <Balance<T>>::get((collection.id, token, owner));852 ensure!(853 total_supply == balance,854 <Error<T>>::RepartitionWhileNotOwningAllPieces855 );856857 <Balance<T>>::insert((collection.id, token, owner), amount);858 <TotalSupply<T>>::insert((collection.id, token), amount);859 Ok(())860 }861862 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {863 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()864 }865}