1#![cfg_attr(not(feature = "std"), no_std)]23use erc::ERC721Events;4use frame_support::{BoundedVec, ensure};5use up_data_structs::{AccessMode, Collection, CollectionId, CustomDataLimit, TokenId};6use pallet_common::{7 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,8};9use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};10use sp_core::H160;11use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};12use sp_std::{vec::Vec, vec};13use core::ops::Deref;14use sp_std::collections::btree_map::BTreeMap;15use codec::{Encode, Decode, MaxEncodedLen};16use scale_info::TypeInfo;1718pub use pallet::*;19#[cfg(feature = "runtime-benchmarks")]20pub mod benchmarking;21pub mod common;22pub mod erc;23pub mod weights;2425pub struct CreateItemData<T: Config> {26 pub const_data: BoundedVec<u8, CustomDataLimit>,27 pub variable_data: BoundedVec<u8, CustomDataLimit>,28 pub owner: T::CrossAccountId,29}30pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;3132#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]33pub struct ItemData<CrossAccountId> {34 pub const_data: BoundedVec<u8, CustomDataLimit>,35 pub variable_data: BoundedVec<u8, CustomDataLimit>,36 pub owner: CrossAccountId,37}3839#[frame_support::pallet]40pub mod pallet {41 use super::*;42 use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};43 use up_data_structs::{CollectionId, TokenId};44 use super::weights::WeightInfo;4546 #[pallet::error]47 pub enum Error<T> {48 49 NotNonfungibleDataUsedToMintFungibleCollectionToken,50 51 NonfungibleItemsHaveNoAmount,52 }5354 #[pallet::config]55 pub trait Config: frame_system::Config + pallet_common::Config {56 type WeightInfo: WeightInfo;57 }5859 #[pallet::pallet]60 #[pallet::generate_store(pub(super) trait Store)]61 pub struct Pallet<T>(_);6263 #[pallet::storage]64 pub type TokensMinted<T: Config> =65 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;66 #[pallet::storage]67 pub type TokensBurnt<T: Config> =68 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6970 #[pallet::storage]71 pub type TokenData<T: Config> = StorageNMap<72 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),73 Value = ItemData<T::CrossAccountId>,74 QueryKind = OptionQuery,75 >;7677 78 #[pallet::storage]79 pub type Owned<T: Config> = StorageNMap<80 Key = (81 Key<Twox64Concat, CollectionId>,82 Key<Blake2_128Concat, T::CrossAccountId>,83 Key<Twox64Concat, TokenId>,84 ),85 Value = bool,86 QueryKind = ValueQuery,87 >;8889 #[pallet::storage]90 pub type AccountBalance<T: Config> = StorageNMap<91 Key = (92 Key<Twox64Concat, CollectionId>,93 Key<Blake2_128Concat, T::CrossAccountId>,94 ),95 Value = u32,96 QueryKind = ValueQuery,97 >;9899 #[pallet::storage]100 pub type Allowance<T: Config> = StorageNMap<101 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),102 Value = T::CrossAccountId,103 QueryKind = OptionQuery,104 >;105}106107pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);108impl<T: Config> NonfungibleHandle<T> {109 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {110 Self(inner)111 }112 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {113 self.0114 }115}116impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {117 fn recorder(&self) -> &SubstrateRecorder<T> {118 self.0.recorder()119 }120 fn into_recorder(self) -> SubstrateRecorder<T> {121 self.0.into_recorder()122 }123}124impl<T: Config> Deref for NonfungibleHandle<T> {125 type Target = pallet_common::CollectionHandle<T>;126127 fn deref(&self) -> &Self::Target {128 &self.0129 }130}131132impl<T: Config> Pallet<T> {133 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {134 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)135 }136 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {137 <TokenData<T>>::contains_key((collection.id, token))138 }139}140141142impl<T: Config> Pallet<T> {143 pub fn init_collection(data: Collection<T::AccountId>) -> Result<CollectionId, DispatchError> {144 <PalletCommon<T>>::init_collection(data)145 }146 pub fn destroy_collection(147 collection: NonfungibleHandle<T>,148 sender: &T::CrossAccountId,149 ) -> DispatchResult {150 let id = collection.id;151152 153154 PalletCommon::destroy_collection(collection.0, sender)?;155156 <TokenData<T>>::remove_prefix((id,), None);157 <Owned<T>>::remove_prefix((id,), None);158 <TokensMinted<T>>::remove(id);159 <TokensBurnt<T>>::remove(id);160 <Allowance<T>>::remove_prefix((id,), None);161 <AccountBalance<T>>::remove_prefix((id,), None);162 Ok(())163 }164165 pub fn burn(166 collection: &NonfungibleHandle<T>,167 sender: &T::CrossAccountId,168 token: TokenId,169 ) -> DispatchResult {170 let token_data =171 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;172 ensure!(173 &token_data.owner == sender174 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),175 <CommonError<T>>::NoPermission176 );177178 if collection.access == AccessMode::AllowList {179 collection.check_allowlist(sender)?;180 }181182 let burnt = <TokensBurnt<T>>::get(collection.id)183 .checked_add(1)184 .ok_or(ArithmeticError::Overflow)?;185186 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))187 .checked_sub(1)188 .ok_or(ArithmeticError::Overflow)?;189190 if balance == 0 {191 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));192 } else {193 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);194 }195 196197 <Owned<T>>::remove((collection.id, &token_data.owner, token));198 <TokensBurnt<T>>::insert(collection.id, burnt);199 <TokenData<T>>::remove((collection.id, token));200 let old_spender = <Allowance<T>>::take((collection.id, token));201202 if let Some(old_spender) = old_spender {203 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(204 collection.id,205 token,206 sender.clone(),207 old_spender,208 0,209 ));210 }211212 collection.log_mirrored(ERC721Events::Transfer {213 from: *token_data.owner.as_eth(),214 to: H160::default(),215 token_id: token.into(),216 });217 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(218 collection.id,219 token,220 token_data.owner,221 1,222 ));223 Ok(())224 }225226 pub fn transfer(227 collection: &NonfungibleHandle<T>,228 from: &T::CrossAccountId,229 to: &T::CrossAccountId,230 token: TokenId,231 ) -> DispatchResult {232 ensure!(233 collection.limits.transfers_enabled(),234 <CommonError<T>>::TransferNotAllowed235 );236237 let token_data =238 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;239 ensure!(240 &token_data.owner == from241 || (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),242 <CommonError<T>>::NoPermission243 );244245 if collection.access == AccessMode::AllowList {246 collection.check_allowlist(from)?;247 collection.check_allowlist(to)?;248 }249 <PalletCommon<T>>::ensure_correct_receiver(to)?;250251 let balance_from = <AccountBalance<T>>::get((collection.id, from))252 .checked_sub(1)253 .ok_or(<CommonError<T>>::TokenValueTooLow)?;254 let balance_to = if from != to {255 let balance_to = <AccountBalance<T>>::get((collection.id, to))256 .checked_add(1)257 .ok_or(ArithmeticError::Overflow)?;258259 ensure!(260 balance_to < collection.limits.account_token_ownership_limit(),261 <CommonError<T>>::AccountTokenLimitExceeded,262 );263264 Some(balance_to)265 } else {266 None267 };268269 270271 <TokenData<T>>::insert(272 (collection.id, token),273 ItemData {274 owner: to.clone(),275 ..token_data276 },277 );278279 if let Some(balance_to) = balance_to {280 281 if balance_from == 0 {282 <AccountBalance<T>>::remove((collection.id, from));283 } else {284 <AccountBalance<T>>::insert((collection.id, from), balance_from);285 }286 <AccountBalance<T>>::insert((collection.id, to), balance_to);287 <Owned<T>>::remove((collection.id, from, token));288 <Owned<T>>::insert((collection.id, to, token), true);289 }290 Self::set_allowance_unchecked(collection, from, token, None, true);291292 collection.log_mirrored(ERC721Events::Transfer {293 from: *from.as_eth(),294 to: *to.as_eth(),295 token_id: token.into(),296 });297 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(298 collection.id,299 token,300 from.clone(),301 to.clone(),302 1,303 ));304 Ok(())305 }306307 pub fn create_multiple_items(308 collection: &NonfungibleHandle<T>,309 sender: &T::CrossAccountId,310 data: Vec<CreateItemData<T>>,311 ) -> DispatchResult {312 if !collection.is_owner_or_admin(sender) {313 ensure!(314 collection.mint_mode,315 <CommonError<T>>::PublicMintingNotAllowed316 );317 collection.check_allowlist(sender)?;318319 for item in data.iter() {320 collection.check_allowlist(&item.owner)?;321 }322 }323324 for data in data.iter() {325 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;326 }327328 let first_token = <TokensMinted<T>>::get(collection.id);329 let tokens_minted = first_token330 .checked_add(data.len() as u32)331 .ok_or(ArithmeticError::Overflow)?;332 ensure!(333 tokens_minted <= collection.limits.token_limit(),334 <CommonError<T>>::CollectionTokenLimitExceeded335 );336337 let mut balances = BTreeMap::new();338 for data in &data {339 let balance = balances340 .entry(&data.owner)341 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));342 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;343344 ensure!(345 *balance <= collection.limits.account_token_ownership_limit(),346 <CommonError<T>>::AccountTokenLimitExceeded,347 );348 }349350 351352 <TokensMinted<T>>::insert(collection.id, tokens_minted);353 for (account, balance) in balances {354 <AccountBalance<T>>::insert((collection.id, account), balance);355 }356 for (i, data) in data.into_iter().enumerate() {357 let token = first_token + i as u32 + 1;358359 <TokenData<T>>::insert(360 (collection.id, token),361 ItemData {362 const_data: data.const_data,363 variable_data: data.variable_data,364 owner: data.owner.clone(),365 },366 );367 <Owned<T>>::insert((collection.id, &data.owner, token), true);368369 collection.log_mirrored(ERC721Events::Transfer {370 from: H160::default(),371 to: *data.owner.as_eth(),372 token_id: token.into(),373 });374 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(375 collection.id,376 TokenId(token),377 data.owner.clone(),378 1,379 ));380 }381 Ok(())382 }383384 pub fn set_allowance_unchecked(385 collection: &NonfungibleHandle<T>,386 sender: &T::CrossAccountId,387 token: TokenId,388 spender: Option<&T::CrossAccountId>,389 assume_implicit_eth: bool,390 ) {391 if let Some(spender) = spender {392 let old_spender = <Allowance<T>>::get((collection.id, token));393 <Allowance<T>>::insert((collection.id, token), spender);394 395 396 collection.log_mirrored(ERC721Events::Approval {397 owner: *sender.as_eth(),398 approved: *spender.as_eth(),399 token_id: token.into(),400 });401 402 403 if old_spender.as_ref() != Some(spender) {404 if let Some(old_owner) = old_spender {405 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(406 collection.id,407 token,408 sender.clone(),409 old_owner,410 0,411 ));412 }413 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(414 collection.id,415 token,416 sender.clone(),417 spender.clone(),418 1,419 ));420 }421 } else {422 let old_spender = <Allowance<T>>::take((collection.id, token));423 if !assume_implicit_eth {424 425 426 collection.log_mirrored(ERC721Events::Approval {427 owner: *sender.as_eth(),428 approved: H160::default(),429 token_id: token.into(),430 });431 }432 433 434 if let Some(old_spender) = old_spender {435 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(436 collection.id,437 token,438 sender.clone(),439 old_spender,440 0,441 ));442 }443 }444 }445446 pub fn set_allowance(447 collection: &NonfungibleHandle<T>,448 sender: &T::CrossAccountId,449 token: TokenId,450 spender: Option<&T::CrossAccountId>,451 ) -> DispatchResult {452 if collection.access == AccessMode::AllowList {453 collection.check_allowlist(sender)?;454 if let Some(spender) = spender {455 collection.check_allowlist(spender)?;456 }457 }458459 if let Some(spender) = spender {460 <PalletCommon<T>>::ensure_correct_receiver(spender)?;461 }462 let token_data =463 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;464 if &token_data.owner != sender {465 ensure!(466 collection.ignores_owned_amount(sender),467 <CommonError<T>>::CantApproveMoreThanOwned468 );469 }470471 472473 Self::set_allowance_unchecked(collection, sender, token, spender, false);474 Ok(())475 }476477 pub fn transfer_from(478 collection: &NonfungibleHandle<T>,479 spender: &T::CrossAccountId,480 from: &T::CrossAccountId,481 to: &T::CrossAccountId,482 token: TokenId,483 ) -> DispatchResult {484 if spender.conv_eq(from) {485 return Self::transfer(collection, from, to, token);486 }487 if collection.access == AccessMode::AllowList {488 489 collection.check_allowlist(spender)?;490 }491492 if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {493 ensure!(494 collection.ignores_allowance(spender),495 <CommonError<T>>::TokenValueNotEnough496 );497 }498499 500501 Self::transfer(collection, from, to, token)?;502 503 Ok(())504 }505506 pub fn burn_from(507 collection: &NonfungibleHandle<T>,508 spender: &T::CrossAccountId,509 from: &T::CrossAccountId,510 token: TokenId,511 ) -> DispatchResult {512 if spender.conv_eq(from) {513 return Self::burn(collection, from, token);514 }515 if collection.access == AccessMode::AllowList {516 517 collection.check_allowlist(spender)?;518 }519520 if <Allowance<T>>::get((collection.id, token)).as_ref() != Some(spender) {521 ensure!(522 collection.ignores_allowance(spender),523 <CommonError<T>>::TokenValueNotEnough524 );525 }526527 528529 Self::burn(collection, from, token)530 }531532 pub fn set_variable_metadata(533 collection: &NonfungibleHandle<T>,534 sender: &T::CrossAccountId,535 token: TokenId,536 data: BoundedVec<u8, CustomDataLimit>,537 ) -> DispatchResult {538 let token_data =539 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;540 collection.check_can_update_meta(sender, &token_data.owner)?;541542 543544 <TokenData<T>>::insert(545 (collection.id, token),546 ItemData {547 variable_data: data,548 ..token_data549 },550 );551 Ok(())552 }553554 555 pub fn create_item(556 collection: &NonfungibleHandle<T>,557 sender: &T::CrossAccountId,558 data: CreateItemData<T>,559 ) -> DispatchResult {560 Self::create_multiple_items(collection, sender, vec![data])561 }562}