difftreelog
fix code style
in: master
4 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -13,9 +13,8 @@
use pallet_evm::GasWeightMapping;
use up_data_structs::{
COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,
- MAX_TOKEN_PREFIX_LENGTH,
- COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo, TokenId, Weight,
- WithdrawReasons, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode,
+ MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo,
+ TokenId, Weight, WithdrawReasons, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode,
NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,
REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,
CustomDataLimit, CreateCollectionData, SponsorshipState,
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -3,8 +3,7 @@
use erc::ERC721Events;
use frame_support::{BoundedVec, ensure};
use up_data_structs::{
- AccessMode, Collection, CollectionId, CustomDataLimit, TokenId,
- CreateCollectionData,
+ AccessMode, Collection, CollectionId, CustomDataLimit, TokenId, CreateCollectionData,
};
use pallet_common::{
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,
pallets/refungible/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use up_data_structs::{5 AccessMode, Collection, CollectionId, CustomDataLimit,6 MAX_REFUNGIBLE_PIECES, TokenId, CreateCollectionData,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 struct CreateItemData<T: Config> {24 pub const_data: BoundedVec<u8, CustomDataLimit>,25 pub variable_data: BoundedVec<u8, CustomDataLimit>,26 pub users: BTreeMap<T::CrossAccountId, u128>,27}28pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2930#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]31pub struct ItemData {32 pub const_data: BoundedVec<u8, CustomDataLimit>,33 pub variable_data: BoundedVec<u8, CustomDataLimit>,34}3536#[frame_support::pallet]37pub mod pallet {38 use super::*;39 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};40 use up_data_structs::{CollectionId, TokenId};41 use super::weights::WeightInfo;4243 #[pallet::error]44 pub enum Error<T> {45 /// Not Refungible item data used to mint in Refungible collection.46 NotRefungibleDataUsedToMintFungibleCollectionToken,47 /// Maximum refungibility exceeded48 WrongRefungiblePieces,49 }5051 #[pallet::config]52 pub trait Config: frame_system::Config + pallet_common::Config {53 type WeightInfo: WeightInfo;54 }5556 #[pallet::pallet]57 #[pallet::generate_store(pub(super) trait Store)]58 pub struct Pallet<T>(_);5960 #[pallet::storage]61 pub type TokensMinted<T: Config> =62 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;63 #[pallet::storage]64 pub type TokensBurnt<T: Config> =65 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6667 #[pallet::storage]68 pub type TokenData<T: Config> = StorageNMap<69 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),70 Value = ItemData,71 QueryKind = ValueQuery,72 >;7374 #[pallet::storage]75 pub type TotalSupply<T: Config> = StorageNMap<76 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),77 Value = u128,78 QueryKind = ValueQuery,79 >;8081 /// Used to enumerate tokens owned by account82 #[pallet::storage]83 pub type Owned<T: Config> = StorageNMap<84 Key = (85 Key<Twox64Concat, CollectionId>,86 Key<Blake2_128Concat, T::CrossAccountId>,87 Key<Twox64Concat, TokenId>,88 ),89 Value = bool,90 QueryKind = ValueQuery,91 >;9293 #[pallet::storage]94 pub type AccountBalance<T: Config> = StorageNMap<95 Key = (96 Key<Twox64Concat, CollectionId>,97 // Owner98 Key<Blake2_128Concat, T::CrossAccountId>,99 ),100 Value = u32,101 QueryKind = ValueQuery,102 >;103104 #[pallet::storage]105 pub type Balance<T: Config> = StorageNMap<106 Key = (107 Key<Twox64Concat, CollectionId>,108 Key<Twox64Concat, TokenId>,109 // Owner110 Key<Blake2_128Concat, T::CrossAccountId>,111 ),112 Value = u128,113 QueryKind = ValueQuery,114 >;115116 #[pallet::storage]117 pub type Allowance<T: Config> = StorageNMap<118 Key = (119 Key<Twox64Concat, CollectionId>,120 Key<Twox64Concat, TokenId>,121 // Owner122 Key<Blake2_128, T::CrossAccountId>,123 // Spender124 Key<Blake2_128Concat, T::CrossAccountId>,125 ),126 Value = u128,127 QueryKind = ValueQuery,128 >;129}130131pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);132impl<T: Config> RefungibleHandle<T> {133 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {134 Self(inner)135 }136 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {137 self.0138 }139}140impl<T: Config> Deref for RefungibleHandle<T> {141 type Target = pallet_common::CollectionHandle<T>;142143 fn deref(&self) -> &Self::Target {144 &self.0145 }146}147148impl<T: Config> Pallet<T> {149 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {150 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)151 }152 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {153 <TotalSupply<T>>::contains_key((collection.id, token))154 }155}156157// unchecked calls skips any permission checks158impl<T: Config> Pallet<T> {159 pub fn init_collection(160 owner: T::AccountId,161 data: CreateCollectionData<T::AccountId>,162 ) -> Result<CollectionId, DispatchError> {163 <PalletCommon<T>>::init_collection(owner, data)164 }165 pub fn destroy_collection(166 collection: RefungibleHandle<T>,167 sender: &T::CrossAccountId,168 ) -> DispatchResult {169 let id = collection.id;170171 // =========172173 PalletCommon::destroy_collection(collection.0, sender)?;174175 <TokensMinted<T>>::remove(id);176 <TokensBurnt<T>>::remove(id);177 <TokenData<T>>::remove_prefix((id,), None);178 <TotalSupply<T>>::remove_prefix((id,), None);179 <Balance<T>>::remove_prefix((id,), None);180 <Allowance<T>>::remove_prefix((id,), None);181 <Owned<T>>::remove_prefix((id,), None);182 <AccountBalance<T>>::remove_prefix((id,), None);183 Ok(())184 }185186 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {187 let burnt = <TokensBurnt<T>>::get(collection.id)188 .checked_add(1)189 .ok_or(ArithmeticError::Overflow)?;190191 <TokensBurnt<T>>::insert(collection.id, burnt);192 <TokenData<T>>::remove((collection.id, token_id));193 <TotalSupply<T>>::remove((collection.id, token_id));194 <Balance<T>>::remove_prefix((collection.id, token_id), None);195 <Allowance<T>>::remove_prefix((collection.id, token_id), None);196 // TODO: ERC721 transfer event197 Ok(())198 }199200 pub fn burn(201 collection: &RefungibleHandle<T>,202 owner: &T::CrossAccountId,203 token: TokenId,204 amount: u128,205 ) -> DispatchResult {206 let total_supply = <TotalSupply<T>>::get((collection.id, token))207 .checked_sub(amount)208 .ok_or(<CommonError<T>>::TokenValueTooLow)?;209210 // This was probally last owner of this token?211 if total_supply == 0 {212 // Ensure user actually owns this amount213 ensure!(214 <Balance<T>>::get((collection.id, token, owner)) == amount,215 <CommonError<T>>::TokenValueTooLow216 );217 let account_balance = <AccountBalance<T>>::get((collection.id, owner))218 .checked_sub(1)219 // Should not occur220 .ok_or(ArithmeticError::Underflow)?;221222 // =========223224 <Owned<T>>::remove((collection.id, owner, token));225 <AccountBalance<T>>::insert((collection.id, owner), account_balance);226 Self::burn_token(collection, token)?;227 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(228 collection.id,229 token,230 owner.clone(),231 amount,232 ));233 return Ok(());234 }235236 let balance = <Balance<T>>::get((collection.id, token, owner))237 .checked_sub(amount)238 .ok_or(<CommonError<T>>::TokenValueTooLow)?;239 let account_balance = if balance == 0 {240 <AccountBalance<T>>::get((collection.id, owner))241 .checked_sub(1)242 // Should not occur243 .ok_or(ArithmeticError::Underflow)?244 } else {245 0246 };247248 // =========249250 if balance == 0 {251 <Owned<T>>::remove((collection.id, owner, token));252 <Balance<T>>::remove((collection.id, token, owner));253 <AccountBalance<T>>::insert((collection.id, owner), account_balance);254 } else {255 <Balance<T>>::insert((collection.id, token, owner), balance);256 }257 <TotalSupply<T>>::insert((collection.id, token), total_supply);258 // TODO: ERC20 transfer event259 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(260 collection.id,261 token,262 owner.clone(),263 amount,264 ));265 Ok(())266 }267268 pub fn transfer(269 collection: &RefungibleHandle<T>,270 from: &T::CrossAccountId,271 to: &T::CrossAccountId,272 token: TokenId,273 amount: u128,274 ) -> DispatchResult {275 ensure!(276 collection.limits.transfers_enabled(),277 <CommonError<T>>::TransferNotAllowed278 );279280 if collection.access == AccessMode::AllowList {281 collection.check_allowlist(from)?;282 collection.check_allowlist(to)?;283 }284 <PalletCommon<T>>::ensure_correct_receiver(to)?;285286 let balance_from = <Balance<T>>::get((collection.id, token, from))287 .checked_sub(amount)288 .ok_or(<CommonError<T>>::TokenValueTooLow)?;289 let mut create_target = false;290 let from_to_differ = from != to;291 let balance_to = if from != to {292 let old_balance = <Balance<T>>::get((collection.id, token, to));293 if old_balance == 0 {294 create_target = true;295 }296 Some(297 old_balance298 .checked_add(amount)299 .ok_or(ArithmeticError::Overflow)?,300 )301 } else {302 None303 };304305 let account_balance_from = if balance_from == 0 {306 Some(307 <AccountBalance<T>>::get((collection.id, from))308 .checked_sub(1)309 // Should not occur310 .ok_or(ArithmeticError::Underflow)?,311 )312 } else {313 None314 };315 // Account data is created in token, AccountBalance should be increased316 // But only if from != to as we shouldn't check overflow in this case317 let account_balance_to = if create_target && from_to_differ {318 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))319 .checked_add(1)320 .ok_or(ArithmeticError::Overflow)?;321 ensure!(322 account_balance_to < collection.limits.account_token_ownership_limit(),323 <CommonError<T>>::AccountTokenLimitExceeded,324 );325326 Some(account_balance_to)327 } else {328 None329 };330331 // =========332333 if let Some(balance_to) = balance_to {334 // from != to335 if balance_from == 0 {336 <Balance<T>>::remove((collection.id, token, from));337 } else {338 <Balance<T>>::insert((collection.id, token, from), balance_from);339 }340 <Balance<T>>::insert((collection.id, token, to), balance_to);341 if let Some(account_balance_from) = account_balance_from {342 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);343 <Owned<T>>::remove((collection.id, from, token));344 }345 if let Some(account_balance_to) = account_balance_to {346 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);347 <Owned<T>>::insert((collection.id, to, token), true);348 }349 }350351 // TODO: ERC20 transfer event352 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(353 collection.id,354 token,355 from.clone(),356 to.clone(),357 amount,358 ));359 Ok(())360 }361362 pub fn create_multiple_items(363 collection: &RefungibleHandle<T>,364 sender: &T::CrossAccountId,365 data: Vec<CreateItemData<T>>,366 ) -> DispatchResult {367 if !collection.is_owner_or_admin(sender) {368 ensure!(369 collection.mint_mode,370 <CommonError<T>>::PublicMintingNotAllowed371 );372 collection.check_allowlist(sender)?;373374 for item in data.iter() {375 for user in item.users.keys() {376 collection.check_allowlist(user)?;377 }378 }379 }380381 for item in data.iter() {382 for (owner, _) in item.users.iter() {383 <PalletCommon<T>>::ensure_correct_receiver(owner)?;384 }385 }386387 // Total pieces per tokens388 let totals = data389 .iter()390 .map(|data| {391 Ok(data392 .users393 .iter()394 .map(|u| u.1)395 .try_fold(0u128, |acc, v| acc.checked_add(*v))396 .ok_or(ArithmeticError::Overflow)?)397 })398 .collect::<Result<Vec<_>, DispatchError>>()?;399 for total in &totals {400 ensure!(401 *total <= MAX_REFUNGIBLE_PIECES,402 <Error<T>>::WrongRefungiblePieces403 );404 }405406 let first_token_id = <TokensMinted<T>>::get(collection.id);407 let tokens_minted = first_token_id408 .checked_add(data.len() as u32)409 .ok_or(ArithmeticError::Overflow)?;410 ensure!(411 tokens_minted < collection.limits.token_limit(),412 <CommonError<T>>::CollectionTokenLimitExceeded413 );414415 let mut balances = BTreeMap::new();416 for data in &data {417 for owner in data.users.keys() {418 let balance = balances419 .entry(owner)420 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));421 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;422423 ensure!(424 *balance <= collection.limits.account_token_ownership_limit(),425 <CommonError<T>>::AccountTokenLimitExceeded,426 );427 }428 }429430 // =========431432 <TokensMinted<T>>::insert(collection.id, tokens_minted);433 for (account, balance) in balances {434 <AccountBalance<T>>::insert((collection.id, account), balance);435 }436 for (i, token) in data.into_iter().enumerate() {437 let token_id = first_token_id + i as u32 + 1;438 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);439440 <TokenData<T>>::insert(441 (collection.id, token_id),442 ItemData {443 const_data: token.const_data,444 variable_data: token.variable_data,445 },446 );447 for (user, amount) in token.users.into_iter() {448 if amount == 0 {449 continue;450 }451 <Balance<T>>::insert((collection.id, token_id, &user), amount);452 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);453 // TODO: ERC20 transfer event454 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(455 collection.id,456 TokenId(token_id),457 user,458 amount,459 ));460 }461 }462 Ok(())463 }464465 pub fn set_allowance_unchecked(466 collection: &RefungibleHandle<T>,467 sender: &T::CrossAccountId,468 spender: &T::CrossAccountId,469 token: TokenId,470 amount: u128,471 ) {472 if amount == 0 {473 <Allowance<T>>::remove((collection.id, token, sender, spender));474 } else {475 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);476 }477 // TODO: ERC20 approval event478 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(479 collection.id,480 token,481 sender.clone(),482 spender.clone(),483 amount,484 ))485 }486487 pub fn set_allowance(488 collection: &RefungibleHandle<T>,489 sender: &T::CrossAccountId,490 spender: &T::CrossAccountId,491 token: TokenId,492 amount: u128,493 ) -> DispatchResult {494 if collection.access == AccessMode::AllowList {495 collection.check_allowlist(sender)?;496 collection.check_allowlist(spender)?;497 }498499 <PalletCommon<T>>::ensure_correct_receiver(spender)?;500501 if <Balance<T>>::get((collection.id, token, sender)) < amount {502 ensure!(503 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),504 <CommonError<T>>::CantApproveMoreThanOwned505 );506 }507508 // =========509510 Self::set_allowance_unchecked(collection, sender, spender, token, amount);511 Ok(())512 }513514 pub fn transfer_from(515 collection: &RefungibleHandle<T>,516 spender: &T::CrossAccountId,517 from: &T::CrossAccountId,518 to: &T::CrossAccountId,519 token: TokenId,520 amount: u128,521 ) -> DispatchResult {522 if spender.conv_eq(from) {523 return Self::transfer(collection, from, to, token, amount);524 }525 if collection.access == AccessMode::AllowList {526 // `from`, `to` checked in [`transfer`]527 collection.check_allowlist(spender)?;528 }529530 let allowance =531 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);532 if allowance.is_none() {533 ensure!(534 collection.ignores_allowance(spender),535 <CommonError<T>>::TokenValueNotEnough536 );537 }538539 // =========540541 Self::transfer(collection, from, to, token, amount)?;542 if let Some(allowance) = allowance {543 Self::set_allowance_unchecked(collection, from, spender, token, allowance);544 }545 Ok(())546 }547548 pub fn burn_from(549 collection: &RefungibleHandle<T>,550 spender: &T::CrossAccountId,551 from: &T::CrossAccountId,552 token: TokenId,553 amount: u128,554 ) -> DispatchResult {555 if spender.conv_eq(from) {556 return Self::burn(collection, from, token, amount);557 }558 if collection.access == AccessMode::AllowList {559 // `from` checked in [`burn`]560 collection.check_allowlist(spender)?;561 }562563 let allowance =564 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);565 if allowance.is_none() {566 ensure!(567 collection.ignores_allowance(spender),568 <CommonError<T>>::TokenValueNotEnough569 );570 }571572 // =========573574 Self::burn(collection, from, token, amount)?;575 if let Some(allowance) = allowance {576 Self::set_allowance_unchecked(collection, from, spender, token, allowance);577 }578 Ok(())579 }580581 pub fn set_variable_metadata(582 collection: &RefungibleHandle<T>,583 sender: &T::CrossAccountId,584 token: TokenId,585 data: BoundedVec<u8, CustomDataLimit>,586 ) -> DispatchResult {587 collection.check_can_update_meta(588 sender,589 &T::CrossAccountId::from_sub(collection.owner.clone()),590 )?;591592 let token_data = <TokenData<T>>::get((collection.id, token));593594 // =========595596 <TokenData<T>>::insert(597 (collection.id, token),598 ItemData {599 variable_data: data,600 ..token_data601 },602 );603 Ok(())604 }605606 /// Delegated to `create_multiple_items`607 pub fn create_item(608 collection: &RefungibleHandle<T>,609 sender: &T::CrossAccountId,610 data: CreateItemData<T>,611 ) -> DispatchResult {612 Self::create_multiple_items(collection, sender, vec![data])613 }614}1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use up_data_structs::{5 AccessMode, Collection, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,6 CreateCollectionData,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 struct CreateItemData<T: Config> {24 pub const_data: BoundedVec<u8, CustomDataLimit>,25 pub variable_data: BoundedVec<u8, CustomDataLimit>,26 pub users: BTreeMap<T::CrossAccountId, u128>,27}28pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2930#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]31pub struct ItemData {32 pub const_data: BoundedVec<u8, CustomDataLimit>,33 pub variable_data: BoundedVec<u8, CustomDataLimit>,34}3536#[frame_support::pallet]37pub mod pallet {38 use super::*;39 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};40 use up_data_structs::{CollectionId, TokenId};41 use super::weights::WeightInfo;4243 #[pallet::error]44 pub enum Error<T> {45 /// Not Refungible item data used to mint in Refungible collection.46 NotRefungibleDataUsedToMintFungibleCollectionToken,47 /// Maximum refungibility exceeded48 WrongRefungiblePieces,49 }5051 #[pallet::config]52 pub trait Config: frame_system::Config + pallet_common::Config {53 type WeightInfo: WeightInfo;54 }5556 #[pallet::pallet]57 #[pallet::generate_store(pub(super) trait Store)]58 pub struct Pallet<T>(_);5960 #[pallet::storage]61 pub type TokensMinted<T: Config> =62 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;63 #[pallet::storage]64 pub type TokensBurnt<T: Config> =65 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6667 #[pallet::storage]68 pub type TokenData<T: Config> = StorageNMap<69 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),70 Value = ItemData,71 QueryKind = ValueQuery,72 >;7374 #[pallet::storage]75 pub type TotalSupply<T: Config> = StorageNMap<76 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),77 Value = u128,78 QueryKind = ValueQuery,79 >;8081 /// Used to enumerate tokens owned by account82 #[pallet::storage]83 pub type Owned<T: Config> = StorageNMap<84 Key = (85 Key<Twox64Concat, CollectionId>,86 Key<Blake2_128Concat, T::CrossAccountId>,87 Key<Twox64Concat, TokenId>,88 ),89 Value = bool,90 QueryKind = ValueQuery,91 >;9293 #[pallet::storage]94 pub type AccountBalance<T: Config> = StorageNMap<95 Key = (96 Key<Twox64Concat, CollectionId>,97 // Owner98 Key<Blake2_128Concat, T::CrossAccountId>,99 ),100 Value = u32,101 QueryKind = ValueQuery,102 >;103104 #[pallet::storage]105 pub type Balance<T: Config> = StorageNMap<106 Key = (107 Key<Twox64Concat, CollectionId>,108 Key<Twox64Concat, TokenId>,109 // Owner110 Key<Blake2_128Concat, T::CrossAccountId>,111 ),112 Value = u128,113 QueryKind = ValueQuery,114 >;115116 #[pallet::storage]117 pub type Allowance<T: Config> = StorageNMap<118 Key = (119 Key<Twox64Concat, CollectionId>,120 Key<Twox64Concat, TokenId>,121 // Owner122 Key<Blake2_128, T::CrossAccountId>,123 // Spender124 Key<Blake2_128Concat, T::CrossAccountId>,125 ),126 Value = u128,127 QueryKind = ValueQuery,128 >;129}130131pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);132impl<T: Config> RefungibleHandle<T> {133 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {134 Self(inner)135 }136 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {137 self.0138 }139}140impl<T: Config> Deref for RefungibleHandle<T> {141 type Target = pallet_common::CollectionHandle<T>;142143 fn deref(&self) -> &Self::Target {144 &self.0145 }146}147148impl<T: Config> Pallet<T> {149 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {150 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)151 }152 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {153 <TotalSupply<T>>::contains_key((collection.id, token))154 }155}156157// unchecked calls skips any permission checks158impl<T: Config> Pallet<T> {159 pub fn init_collection(160 owner: T::AccountId,161 data: CreateCollectionData<T::AccountId>,162 ) -> Result<CollectionId, DispatchError> {163 <PalletCommon<T>>::init_collection(owner, data)164 }165 pub fn destroy_collection(166 collection: RefungibleHandle<T>,167 sender: &T::CrossAccountId,168 ) -> DispatchResult {169 let id = collection.id;170171 // =========172173 PalletCommon::destroy_collection(collection.0, sender)?;174175 <TokensMinted<T>>::remove(id);176 <TokensBurnt<T>>::remove(id);177 <TokenData<T>>::remove_prefix((id,), None);178 <TotalSupply<T>>::remove_prefix((id,), None);179 <Balance<T>>::remove_prefix((id,), None);180 <Allowance<T>>::remove_prefix((id,), None);181 <Owned<T>>::remove_prefix((id,), None);182 <AccountBalance<T>>::remove_prefix((id,), None);183 Ok(())184 }185186 pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {187 let burnt = <TokensBurnt<T>>::get(collection.id)188 .checked_add(1)189 .ok_or(ArithmeticError::Overflow)?;190191 <TokensBurnt<T>>::insert(collection.id, burnt);192 <TokenData<T>>::remove((collection.id, token_id));193 <TotalSupply<T>>::remove((collection.id, token_id));194 <Balance<T>>::remove_prefix((collection.id, token_id), None);195 <Allowance<T>>::remove_prefix((collection.id, token_id), None);196 // TODO: ERC721 transfer event197 Ok(())198 }199200 pub fn burn(201 collection: &RefungibleHandle<T>,202 owner: &T::CrossAccountId,203 token: TokenId,204 amount: u128,205 ) -> DispatchResult {206 let total_supply = <TotalSupply<T>>::get((collection.id, token))207 .checked_sub(amount)208 .ok_or(<CommonError<T>>::TokenValueTooLow)?;209210 // This was probally last owner of this token?211 if total_supply == 0 {212 // Ensure user actually owns this amount213 ensure!(214 <Balance<T>>::get((collection.id, token, owner)) == amount,215 <CommonError<T>>::TokenValueTooLow216 );217 let account_balance = <AccountBalance<T>>::get((collection.id, owner))218 .checked_sub(1)219 // Should not occur220 .ok_or(ArithmeticError::Underflow)?;221222 // =========223224 <Owned<T>>::remove((collection.id, owner, token));225 <AccountBalance<T>>::insert((collection.id, owner), account_balance);226 Self::burn_token(collection, token)?;227 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(228 collection.id,229 token,230 owner.clone(),231 amount,232 ));233 return Ok(());234 }235236 let balance = <Balance<T>>::get((collection.id, token, owner))237 .checked_sub(amount)238 .ok_or(<CommonError<T>>::TokenValueTooLow)?;239 let account_balance = if balance == 0 {240 <AccountBalance<T>>::get((collection.id, owner))241 .checked_sub(1)242 // Should not occur243 .ok_or(ArithmeticError::Underflow)?244 } else {245 0246 };247248 // =========249250 if balance == 0 {251 <Owned<T>>::remove((collection.id, owner, token));252 <Balance<T>>::remove((collection.id, token, owner));253 <AccountBalance<T>>::insert((collection.id, owner), account_balance);254 } else {255 <Balance<T>>::insert((collection.id, token, owner), balance);256 }257 <TotalSupply<T>>::insert((collection.id, token), total_supply);258 // TODO: ERC20 transfer event259 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(260 collection.id,261 token,262 owner.clone(),263 amount,264 ));265 Ok(())266 }267268 pub fn transfer(269 collection: &RefungibleHandle<T>,270 from: &T::CrossAccountId,271 to: &T::CrossAccountId,272 token: TokenId,273 amount: u128,274 ) -> DispatchResult {275 ensure!(276 collection.limits.transfers_enabled(),277 <CommonError<T>>::TransferNotAllowed278 );279280 if collection.access == AccessMode::AllowList {281 collection.check_allowlist(from)?;282 collection.check_allowlist(to)?;283 }284 <PalletCommon<T>>::ensure_correct_receiver(to)?;285286 let balance_from = <Balance<T>>::get((collection.id, token, from))287 .checked_sub(amount)288 .ok_or(<CommonError<T>>::TokenValueTooLow)?;289 let mut create_target = false;290 let from_to_differ = from != to;291 let balance_to = if from != to {292 let old_balance = <Balance<T>>::get((collection.id, token, to));293 if old_balance == 0 {294 create_target = true;295 }296 Some(297 old_balance298 .checked_add(amount)299 .ok_or(ArithmeticError::Overflow)?,300 )301 } else {302 None303 };304305 let account_balance_from = if balance_from == 0 {306 Some(307 <AccountBalance<T>>::get((collection.id, from))308 .checked_sub(1)309 // Should not occur310 .ok_or(ArithmeticError::Underflow)?,311 )312 } else {313 None314 };315 // Account data is created in token, AccountBalance should be increased316 // But only if from != to as we shouldn't check overflow in this case317 let account_balance_to = if create_target && from_to_differ {318 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))319 .checked_add(1)320 .ok_or(ArithmeticError::Overflow)?;321 ensure!(322 account_balance_to < collection.limits.account_token_ownership_limit(),323 <CommonError<T>>::AccountTokenLimitExceeded,324 );325326 Some(account_balance_to)327 } else {328 None329 };330331 // =========332333 if let Some(balance_to) = balance_to {334 // from != to335 if balance_from == 0 {336 <Balance<T>>::remove((collection.id, token, from));337 } else {338 <Balance<T>>::insert((collection.id, token, from), balance_from);339 }340 <Balance<T>>::insert((collection.id, token, to), balance_to);341 if let Some(account_balance_from) = account_balance_from {342 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);343 <Owned<T>>::remove((collection.id, from, token));344 }345 if let Some(account_balance_to) = account_balance_to {346 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);347 <Owned<T>>::insert((collection.id, to, token), true);348 }349 }350351 // TODO: ERC20 transfer event352 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(353 collection.id,354 token,355 from.clone(),356 to.clone(),357 amount,358 ));359 Ok(())360 }361362 pub fn create_multiple_items(363 collection: &RefungibleHandle<T>,364 sender: &T::CrossAccountId,365 data: Vec<CreateItemData<T>>,366 ) -> DispatchResult {367 if !collection.is_owner_or_admin(sender) {368 ensure!(369 collection.mint_mode,370 <CommonError<T>>::PublicMintingNotAllowed371 );372 collection.check_allowlist(sender)?;373374 for item in data.iter() {375 for user in item.users.keys() {376 collection.check_allowlist(user)?;377 }378 }379 }380381 for item in data.iter() {382 for (owner, _) in item.users.iter() {383 <PalletCommon<T>>::ensure_correct_receiver(owner)?;384 }385 }386387 // Total pieces per tokens388 let totals = data389 .iter()390 .map(|data| {391 Ok(data392 .users393 .iter()394 .map(|u| u.1)395 .try_fold(0u128, |acc, v| acc.checked_add(*v))396 .ok_or(ArithmeticError::Overflow)?)397 })398 .collect::<Result<Vec<_>, DispatchError>>()?;399 for total in &totals {400 ensure!(401 *total <= MAX_REFUNGIBLE_PIECES,402 <Error<T>>::WrongRefungiblePieces403 );404 }405406 let first_token_id = <TokensMinted<T>>::get(collection.id);407 let tokens_minted = first_token_id408 .checked_add(data.len() as u32)409 .ok_or(ArithmeticError::Overflow)?;410 ensure!(411 tokens_minted < collection.limits.token_limit(),412 <CommonError<T>>::CollectionTokenLimitExceeded413 );414415 let mut balances = BTreeMap::new();416 for data in &data {417 for owner in data.users.keys() {418 let balance = balances419 .entry(owner)420 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));421 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;422423 ensure!(424 *balance <= collection.limits.account_token_ownership_limit(),425 <CommonError<T>>::AccountTokenLimitExceeded,426 );427 }428 }429430 // =========431432 <TokensMinted<T>>::insert(collection.id, tokens_minted);433 for (account, balance) in balances {434 <AccountBalance<T>>::insert((collection.id, account), balance);435 }436 for (i, token) in data.into_iter().enumerate() {437 let token_id = first_token_id + i as u32 + 1;438 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);439440 <TokenData<T>>::insert(441 (collection.id, token_id),442 ItemData {443 const_data: token.const_data,444 variable_data: token.variable_data,445 },446 );447 for (user, amount) in token.users.into_iter() {448 if amount == 0 {449 continue;450 }451 <Balance<T>>::insert((collection.id, token_id, &user), amount);452 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);453 // TODO: ERC20 transfer event454 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(455 collection.id,456 TokenId(token_id),457 user,458 amount,459 ));460 }461 }462 Ok(())463 }464465 pub fn set_allowance_unchecked(466 collection: &RefungibleHandle<T>,467 sender: &T::CrossAccountId,468 spender: &T::CrossAccountId,469 token: TokenId,470 amount: u128,471 ) {472 if amount == 0 {473 <Allowance<T>>::remove((collection.id, token, sender, spender));474 } else {475 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);476 }477 // TODO: ERC20 approval event478 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(479 collection.id,480 token,481 sender.clone(),482 spender.clone(),483 amount,484 ))485 }486487 pub fn set_allowance(488 collection: &RefungibleHandle<T>,489 sender: &T::CrossAccountId,490 spender: &T::CrossAccountId,491 token: TokenId,492 amount: u128,493 ) -> DispatchResult {494 if collection.access == AccessMode::AllowList {495 collection.check_allowlist(sender)?;496 collection.check_allowlist(spender)?;497 }498499 <PalletCommon<T>>::ensure_correct_receiver(spender)?;500501 if <Balance<T>>::get((collection.id, token, sender)) < amount {502 ensure!(503 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),504 <CommonError<T>>::CantApproveMoreThanOwned505 );506 }507508 // =========509510 Self::set_allowance_unchecked(collection, sender, spender, token, amount);511 Ok(())512 }513514 pub fn transfer_from(515 collection: &RefungibleHandle<T>,516 spender: &T::CrossAccountId,517 from: &T::CrossAccountId,518 to: &T::CrossAccountId,519 token: TokenId,520 amount: u128,521 ) -> DispatchResult {522 if spender.conv_eq(from) {523 return Self::transfer(collection, from, to, token, amount);524 }525 if collection.access == AccessMode::AllowList {526 // `from`, `to` checked in [`transfer`]527 collection.check_allowlist(spender)?;528 }529530 let allowance =531 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);532 if allowance.is_none() {533 ensure!(534 collection.ignores_allowance(spender),535 <CommonError<T>>::TokenValueNotEnough536 );537 }538539 // =========540541 Self::transfer(collection, from, to, token, amount)?;542 if let Some(allowance) = allowance {543 Self::set_allowance_unchecked(collection, from, spender, token, allowance);544 }545 Ok(())546 }547548 pub fn burn_from(549 collection: &RefungibleHandle<T>,550 spender: &T::CrossAccountId,551 from: &T::CrossAccountId,552 token: TokenId,553 amount: u128,554 ) -> DispatchResult {555 if spender.conv_eq(from) {556 return Self::burn(collection, from, token, amount);557 }558 if collection.access == AccessMode::AllowList {559 // `from` checked in [`burn`]560 collection.check_allowlist(spender)?;561 }562563 let allowance =564 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);565 if allowance.is_none() {566 ensure!(567 collection.ignores_allowance(spender),568 <CommonError<T>>::TokenValueNotEnough569 );570 }571572 // =========573574 Self::burn(collection, from, token, amount)?;575 if let Some(allowance) = allowance {576 Self::set_allowance_unchecked(collection, from, spender, token, allowance);577 }578 Ok(())579 }580581 pub fn set_variable_metadata(582 collection: &RefungibleHandle<T>,583 sender: &T::CrossAccountId,584 token: TokenId,585 data: BoundedVec<u8, CustomDataLimit>,586 ) -> DispatchResult {587 collection.check_can_update_meta(588 sender,589 &T::CrossAccountId::from_sub(collection.owner.clone()),590 )?;591592 let token_data = <TokenData<T>>::get((collection.id, token));593594 // =========595596 <TokenData<T>>::insert(597 (collection.id, token),598 ItemData {599 variable_data: data,600 ..token_data601 },602 );603 Ok(())604 }605606 /// Delegated to `create_multiple_items`607 pub fn create_item(608 collection: &RefungibleHandle<T>,609 sender: &T::CrossAccountId,610 data: CreateItemData<T>,611 ) -> DispatchResult {612 Self::create_multiple_items(collection, sender, vec![data])613 }614}pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -36,9 +36,8 @@
use frame_system::{self as system, ensure_signed};
use sp_runtime::{sp_std::prelude::Vec};
use up_data_structs::{
- MAX_DECIMAL_POINTS,
- VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
- MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH,
+ MAX_DECIMAL_POINTS, VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
+ OFFCHAIN_SCHEMA_LIMIT, MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH,
MAX_TOKEN_PREFIX_LENGTH, AccessMode, Collection, CreateItemData, CollectionLimits,
CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
CreateCollectionData, CustomDataLimit,