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,6 CreateCollectionData, CreateRefungibleExData,7};8use pallet_common::{9 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,10};11use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};12use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};13use core::ops::Deref;14use codec::{Encode, Decode, MaxEncodedLen};15use scale_info::TypeInfo;1617pub use pallet::*;18#[cfg(feature = "runtime-benchmarks")]19pub mod benchmarking;20pub mod common;21pub mod erc;22pub mod weights;23pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2425#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]26pub struct ItemData {27 pub const_data: BoundedVec<u8, CustomDataLimit>,28 pub variable_data: BoundedVec<u8, CustomDataLimit>,29}3031#[frame_support::pallet]32pub mod pallet {33 use super::*;34 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};35 use up_data_structs::{CollectionId, TokenId};36 use super::weights::WeightInfo;3738 #[pallet::error]39 pub enum Error<T> {40 41 NotRefungibleDataUsedToMintFungibleCollectionToken,42 43 WrongRefungiblePieces,44 }4546 #[pallet::config]47 pub trait Config: frame_system::Config + pallet_common::Config {48 type WeightInfo: WeightInfo;49 }5051 #[pallet::pallet]52 #[pallet::generate_store(pub(super) trait Store)]53 pub struct Pallet<T>(_);5455 #[pallet::storage]56 pub type TokensMinted<T: Config> =57 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;58 #[pallet::storage]59 pub type TokensBurnt<T: Config> =60 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6162 #[pallet::storage]63 pub type TokenData<T: Config> = StorageNMap<64 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),65 Value = ItemData,66 QueryKind = ValueQuery,67 >;6869 #[pallet::storage]70 pub type TotalSupply<T: Config> = StorageNMap<71 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),72 Value = u128,73 QueryKind = ValueQuery,74 >;7576 77 #[pallet::storage]78 pub type Owned<T: Config> = StorageNMap<79 Key = (80 Key<Twox64Concat, CollectionId>,81 Key<Blake2_128Concat, T::CrossAccountId>,82 Key<Twox64Concat, TokenId>,83 ),84 Value = bool,85 QueryKind = ValueQuery,86 >;8788 #[pallet::storage]89 pub type AccountBalance<T: Config> = StorageNMap<90 Key = (91 Key<Twox64Concat, CollectionId>,92 93 Key<Blake2_128Concat, T::CrossAccountId>,94 ),95 Value = u32,96 QueryKind = ValueQuery,97 >;9899 #[pallet::storage]100 pub type Balance<T: Config> = StorageNMap<101 Key = (102 Key<Twox64Concat, CollectionId>,103 Key<Twox64Concat, TokenId>,104 105 Key<Blake2_128Concat, T::CrossAccountId>,106 ),107 Value = u128,108 QueryKind = ValueQuery,109 >;110111 #[pallet::storage]112 pub type Allowance<T: Config> = StorageNMap<113 Key = (114 Key<Twox64Concat, CollectionId>,115 Key<Twox64Concat, TokenId>,116 117 Key<Blake2_128, T::CrossAccountId>,118 119 Key<Blake2_128Concat, T::CrossAccountId>,120 ),121 Value = u128,122 QueryKind = ValueQuery,123 >;124}125126pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);127impl<T: Config> RefungibleHandle<T> {128 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {129 Self(inner)130 }131 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {132 self.0133 }134}135impl<T: Config> Deref for RefungibleHandle<T> {136 type Target = pallet_common::CollectionHandle<T>;137138 fn deref(&self) -> &Self::Target {139 &self.0140 }141}142143impl<T: Config> Pallet<T> {144 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {145 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)146 }147 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {148 <TotalSupply<T>>::contains_key((collection.id, token))149 }150}151152153impl<T: Config> Pallet<T> {154 pub fn init_collection(155 owner: T::AccountId,156 data: CreateCollectionData<T::AccountId>,157 ) -> Result<CollectionId, DispatchError> {158 <PalletCommon<T>>::init_collection(owner, data)159 }160 pub fn destroy_collection(161 collection: RefungibleHandle<T>,162 sender: &T::CrossAccountId,163 ) -> DispatchResult {164 let id = collection.id;165166 167168 PalletCommon::destroy_collection(collection.0, sender)?;169170 <TokensMinted<T>>::remove(id);171 <TokensBurnt<T>>::remove(id);172 <TokenData<T>>::remove_prefix((id,), None);173 <TotalSupply<T>>::remove_prefix((id,), None);174 <Balance<T>>::remove_prefix((id,), None);175 <Allowance<T>>::remove_prefix((id,), None);176 <Owned<T>>::remove_prefix((id,), None);177 <AccountBalance<T>>::remove_prefix((id,), None);178 Ok(())179 }180181 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {182 let burnt = <TokensBurnt<T>>::get(collection.id)183 .checked_add(1)184 .ok_or(ArithmeticError::Overflow)?;185186 <TokensBurnt<T>>::insert(collection.id, burnt);187 <TokenData<T>>::remove((collection.id, token_id));188 <TotalSupply<T>>::remove((collection.id, token_id));189 <Balance<T>>::remove_prefix((collection.id, token_id), None);190 <Allowance<T>>::remove_prefix((collection.id, token_id), None);191 192 Ok(())193 }194195 pub fn burn(196 collection: &RefungibleHandle<T>,197 owner: &T::CrossAccountId,198 token: TokenId,199 amount: u128,200 ) -> DispatchResult {201 let total_supply = <TotalSupply<T>>::get((collection.id, token))202 .checked_sub(amount)203 .ok_or(<CommonError<T>>::TokenValueTooLow)?;204205 206 if total_supply == 0 {207 208 ensure!(209 <Balance<T>>::get((collection.id, token, owner)) == amount,210 <CommonError<T>>::TokenValueTooLow211 );212 let account_balance = <AccountBalance<T>>::get((collection.id, owner))213 .checked_sub(1)214 215 .ok_or(ArithmeticError::Underflow)?;216217 218219 <Owned<T>>::remove((collection.id, owner, token));220 <AccountBalance<T>>::insert((collection.id, owner), account_balance);221 Self::burn_token(collection, token)?;222 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(223 collection.id,224 token,225 owner.clone(),226 amount,227 ));228 return Ok(());229 }230231 let balance = <Balance<T>>::get((collection.id, token, owner))232 .checked_sub(amount)233 .ok_or(<CommonError<T>>::TokenValueTooLow)?;234 let account_balance = if balance == 0 {235 <AccountBalance<T>>::get((collection.id, owner))236 .checked_sub(1)237 238 .ok_or(ArithmeticError::Underflow)?239 } else {240 0241 };242243 244245 if balance == 0 {246 <Owned<T>>::remove((collection.id, owner, token));247 <Balance<T>>::remove((collection.id, token, owner));248 <AccountBalance<T>>::insert((collection.id, owner), account_balance);249 } else {250 <Balance<T>>::insert((collection.id, token, owner), balance);251 }252 <TotalSupply<T>>::insert((collection.id, token), total_supply);253 254 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(255 collection.id,256 token,257 owner.clone(),258 amount,259 ));260 Ok(())261 }262263 pub fn transfer(264 collection: &RefungibleHandle<T>,265 from: &T::CrossAccountId,266 to: &T::CrossAccountId,267 token: TokenId,268 amount: u128,269 ) -> DispatchResult {270 ensure!(271 collection.limits.transfers_enabled(),272 <CommonError<T>>::TransferNotAllowed273 );274275 if collection.access == AccessMode::AllowList {276 collection.check_allowlist(from)?;277 collection.check_allowlist(to)?;278 }279 <PalletCommon<T>>::ensure_correct_receiver(to)?;280281 let balance_from = <Balance<T>>::get((collection.id, token, from))282 .checked_sub(amount)283 .ok_or(<CommonError<T>>::TokenValueTooLow)?;284 let mut create_target = false;285 let from_to_differ = from != to;286 let balance_to = if from != to {287 let old_balance = <Balance<T>>::get((collection.id, token, to));288 if old_balance == 0 {289 create_target = true;290 }291 Some(292 old_balance293 .checked_add(amount)294 .ok_or(ArithmeticError::Overflow)?,295 )296 } else {297 None298 };299300 let account_balance_from = if balance_from == 0 {301 Some(302 <AccountBalance<T>>::get((collection.id, from))303 .checked_sub(1)304 305 .ok_or(ArithmeticError::Underflow)?,306 )307 } else {308 None309 };310 311 312 let account_balance_to = if create_target && from_to_differ {313 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))314 .checked_add(1)315 .ok_or(ArithmeticError::Overflow)?;316 ensure!(317 account_balance_to < collection.limits.account_token_ownership_limit(),318 <CommonError<T>>::AccountTokenLimitExceeded,319 );320321 Some(account_balance_to)322 } else {323 None324 };325326 327328 if let Some(balance_to) = balance_to {329 330 if balance_from == 0 {331 <Balance<T>>::remove((collection.id, token, from));332 } else {333 <Balance<T>>::insert((collection.id, token, from), balance_from);334 }335 <Balance<T>>::insert((collection.id, token, to), balance_to);336 if let Some(account_balance_from) = account_balance_from {337 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);338 <Owned<T>>::remove((collection.id, from, token));339 }340 if let Some(account_balance_to) = account_balance_to {341 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);342 <Owned<T>>::insert((collection.id, to, token), true);343 }344 }345346 347 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(348 collection.id,349 token,350 from.clone(),351 to.clone(),352 amount,353 ));354 Ok(())355 }356357 pub fn create_multiple_items(358 collection: &RefungibleHandle<T>,359 sender: &T::CrossAccountId,360 data: Vec<CreateRefungibleExData<T::CrossAccountId>>,361 ) -> DispatchResult {362 if !collection.is_owner_or_admin(sender) {363 ensure!(364 collection.mint_mode,365 <CommonError<T>>::PublicMintingNotAllowed366 );367 collection.check_allowlist(sender)?;368369 for item in data.iter() {370 for user in item.users.keys() {371 collection.check_allowlist(user)?;372 }373 }374 }375376 for item in data.iter() {377 for (owner, _) in item.users.iter() {378 <PalletCommon<T>>::ensure_correct_receiver(owner)?;379 }380 }381382 383 let totals = data384 .iter()385 .map(|data| {386 Ok(data387 .users388 .iter()389 .map(|u| u.1)390 .try_fold(0u128, |acc, v| acc.checked_add(*v))391 .ok_or(ArithmeticError::Overflow)?)392 })393 .collect::<Result<Vec<_>, DispatchError>>()?;394 for total in &totals {395 ensure!(396 *total <= MAX_REFUNGIBLE_PIECES,397 <Error<T>>::WrongRefungiblePieces398 );399 }400401 let first_token_id = <TokensMinted<T>>::get(collection.id);402 let tokens_minted = first_token_id403 .checked_add(data.len() as u32)404 .ok_or(ArithmeticError::Overflow)?;405 ensure!(406 tokens_minted < collection.limits.token_limit(),407 <CommonError<T>>::CollectionTokenLimitExceeded408 );409410 let mut balances = BTreeMap::new();411 for data in &data {412 for owner in data.users.keys() {413 let balance = balances414 .entry(owner)415 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));416 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;417418 ensure!(419 *balance <= collection.limits.account_token_ownership_limit(),420 <CommonError<T>>::AccountTokenLimitExceeded,421 );422 }423 }424425 426427 <TokensMinted<T>>::insert(collection.id, tokens_minted);428 for (account, balance) in balances {429 <AccountBalance<T>>::insert((collection.id, account), balance);430 }431 for (i, token) in data.into_iter().enumerate() {432 let token_id = first_token_id + i as u32 + 1;433 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);434435 <TokenData<T>>::insert(436 (collection.id, token_id),437 ItemData {438 const_data: token.const_data,439 variable_data: token.variable_data,440 },441 );442 for (user, amount) in token.users.into_iter() {443 if amount == 0 {444 continue;445 }446 <Balance<T>>::insert((collection.id, token_id, &user), amount);447 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);448 449 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(450 collection.id,451 TokenId(token_id),452 user,453 amount,454 ));455 }456 }457 Ok(())458 }459460 pub fn set_allowance_unchecked(461 collection: &RefungibleHandle<T>,462 sender: &T::CrossAccountId,463 spender: &T::CrossAccountId,464 token: TokenId,465 amount: u128,466 ) {467 if amount == 0 {468 <Allowance<T>>::remove((collection.id, token, sender, spender));469 } else {470 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);471 }472 473 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(474 collection.id,475 token,476 sender.clone(),477 spender.clone(),478 amount,479 ))480 }481482 pub fn set_allowance(483 collection: &RefungibleHandle<T>,484 sender: &T::CrossAccountId,485 spender: &T::CrossAccountId,486 token: TokenId,487 amount: u128,488 ) -> DispatchResult {489 if collection.access == AccessMode::AllowList {490 collection.check_allowlist(sender)?;491 collection.check_allowlist(spender)?;492 }493494 <PalletCommon<T>>::ensure_correct_receiver(spender)?;495496 if <Balance<T>>::get((collection.id, token, sender)) < amount {497 ensure!(498 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),499 <CommonError<T>>::CantApproveMoreThanOwned500 );501 }502503 504505 Self::set_allowance_unchecked(collection, sender, spender, token, amount);506 Ok(())507 }508509 pub fn transfer_from(510 collection: &RefungibleHandle<T>,511 spender: &T::CrossAccountId,512 from: &T::CrossAccountId,513 to: &T::CrossAccountId,514 token: TokenId,515 amount: u128,516 ) -> DispatchResult {517 if spender.conv_eq(from) {518 return Self::transfer(collection, from, to, token, amount);519 }520 if collection.access == AccessMode::AllowList {521 522 collection.check_allowlist(spender)?;523 }524525 let allowance =526 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);527 if allowance.is_none() {528 ensure!(529 collection.ignores_allowance(spender),530 <CommonError<T>>::ApprovedValueTooLow531 );532 }533534 535536 Self::transfer(collection, from, to, token, amount)?;537 if let Some(allowance) = allowance {538 Self::set_allowance_unchecked(collection, from, spender, token, allowance);539 }540 Ok(())541 }542543 pub fn burn_from(544 collection: &RefungibleHandle<T>,545 spender: &T::CrossAccountId,546 from: &T::CrossAccountId,547 token: TokenId,548 amount: u128,549 ) -> DispatchResult {550 if spender.conv_eq(from) {551 return Self::burn(collection, from, token, amount);552 }553 if collection.access == AccessMode::AllowList {554 555 collection.check_allowlist(spender)?;556 }557558 let allowance =559 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);560 if allowance.is_none() {561 ensure!(562 collection.ignores_allowance(spender),563 <CommonError<T>>::ApprovedValueTooLow564 );565 }566567 568569 Self::burn(collection, from, token, amount)?;570 if let Some(allowance) = allowance {571 Self::set_allowance_unchecked(collection, from, spender, token, allowance);572 }573 Ok(())574 }575576 pub fn set_variable_metadata(577 collection: &RefungibleHandle<T>,578 sender: &T::CrossAccountId,579 token: TokenId,580 data: BoundedVec<u8, CustomDataLimit>,581 ) -> DispatchResult {582 collection.check_can_update_meta(583 sender,584 &T::CrossAccountId::from_sub(collection.owner.clone()),585 )?;586587 let token_data = <TokenData<T>>::get((collection.id, token));588589 590591 <TokenData<T>>::insert(592 (collection.id, token),593 ItemData {594 variable_data: data,595 ..token_data596 },597 );598 Ok(())599 }600601 602 pub fn create_item(603 collection: &RefungibleHandle<T>,604 sender: &T::CrossAccountId,605 data: CreateRefungibleExData<T::CrossAccountId>,606 ) -> DispatchResult {607 Self::create_multiple_items(collection, sender, vec![data])608 }609}