difftreelog
fix(fungible) mint resets total supply
in: master
1 file changed
pallets/fungible/src/lib.rsdiffbeforeafterboth1#![cfg_attr(not(feature = "std"), no_std)]23use core::ops::Deref;4use frame_support::{ensure};5use nft_data_structs::{AccessMode, Collection, CollectionId, TokenId};6use pallet_common::{7 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,8};9use sp_core::H160;10use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};11use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};1213pub use pallet::*;1415use crate::erc::ERC20Events;16#[cfg(feature = "runtime-benchmarks")]17pub mod benchmarking;18pub mod common;19pub mod erc;20pub mod weights;2122pub type CreateItemData<T> = (<T as pallet_common::Config>::CrossAccountId, u128);23pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2425#[frame_support::pallet]26pub mod pallet {27 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};28 use nft_data_structs::CollectionId;29 use super::weights::WeightInfo;3031 #[pallet::error]32 pub enum Error<T> {33 /// Not Fungible item data used to mint in Fungible collection.34 NotFungibleDataUsedToMintFungibleCollectionToken,35 /// Not default id passed as TokenId argument36 FungibleItemsHaveNoId,37 /// Tried to set data for fungible item38 FungibleItemsHaveData,39 }4041 #[pallet::config]42 pub trait Config: frame_system::Config + pallet_common::Config {43 type WeightInfo: WeightInfo;44 }4546 #[pallet::pallet]47 #[pallet::generate_store(pub(super) trait Store)]48 pub struct Pallet<T>(_);4950 #[pallet::storage]51 pub(super) type TotalSupply<T: Config> =52 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;5354 #[pallet::storage]55 pub(super) type Balance<T: Config> = StorageNMap<56 Key = (57 Key<Twox64Concat, CollectionId>,58 Key<Blake2_128Concat, T::CrossAccountId>,59 ),60 Value = u128,61 QueryKind = ValueQuery,62 >;6364 #[pallet::storage]65 pub(super) type Allowance<T: Config> = StorageNMap<66 Key = (67 Key<Twox64Concat, CollectionId>,68 Key<Blake2_128, T::CrossAccountId>,69 Key<Blake2_128Concat, T::CrossAccountId>,70 ),71 Value = u128,72 QueryKind = ValueQuery,73 >;74}7576pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);77impl<T: Config> FungibleHandle<T> {78 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {79 Self(inner)80 }81 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {82 self.083 }84}85impl<T: Config> Deref for FungibleHandle<T> {86 type Target = pallet_common::CollectionHandle<T>;8788 fn deref(&self) -> &Self::Target {89 &self.090 }91}9293impl<T: Config> Pallet<T> {94 pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {95 PalletCommon::init_collection(data)96 }97 pub fn destroy_collection(98 collection: FungibleHandle<T>,99 sender: &T::CrossAccountId,100 ) -> DispatchResult {101 let id = collection.id;102103 // =========104105 PalletCommon::destroy_collection(collection.0, sender)?;106107 <TotalSupply<T>>::remove(id);108 <Balance<T>>::remove_prefix((id,), None);109 <Allowance<T>>::remove_prefix((id,), None);110 Ok(())111 }112113 pub fn burn(114 collection: &FungibleHandle<T>,115 owner: &T::CrossAccountId,116 amount: u128,117 ) -> DispatchResult {118 let total_supply = <TotalSupply<T>>::get(collection.id)119 .checked_sub(amount)120 .ok_or(<CommonError<T>>::TokenValueTooLow)?;121122 let balance = <Balance<T>>::get((collection.id, owner))123 .checked_sub(amount)124 .ok_or(<CommonError<T>>::TokenValueTooLow)?;125126 if collection.access == AccessMode::WhiteList {127 collection.check_allowlist(owner)?;128 }129130 // =========131132 if balance == 0 {133 <Balance<T>>::remove((collection.id, owner));134 } else {135 <Balance<T>>::insert((collection.id, owner), balance);136 }137 <TotalSupply<T>>::insert(collection.id, total_supply);138139 collection.log_infallible(ERC20Events::Transfer {140 from: *owner.as_eth(),141 to: H160::default(),142 value: amount.into(),143 });144 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(145 collection.id,146 TokenId::default(),147 owner.clone(),148 amount,149 ));150 Ok(())151 }152153 pub fn transfer(154 collection: &FungibleHandle<T>,155 from: &T::CrossAccountId,156 to: &T::CrossAccountId,157 amount: u128,158 ) -> DispatchResult {159 ensure!(160 collection.limits.transfers_enabled(),161 <CommonError<T>>::TransferNotAllowed,162 );163164 if collection.access == AccessMode::WhiteList {165 collection.check_allowlist(from)?;166 collection.check_allowlist(to)?;167 }168 <PalletCommon<T>>::ensure_correct_receiver(to)?;169170 let balance_from = <Balance<T>>::get((collection.id, from))171 .checked_sub(amount)172 .ok_or(<CommonError<T>>::TokenValueTooLow)?;173 let balance_to = if from != to {174 Some(175 <Balance<T>>::get((collection.id, to))176 .checked_add(amount)177 .ok_or(ArithmeticError::Overflow)?,178 )179 } else {180 None181 };182183 collection.consume_sstore()?;184 collection.consume_sstore()?;185 collection.consume_log(2, 32)?;186 collection.consume_sstore()?;187188 // =========189190 if let Some(balance_to) = balance_to {191 // from != to192 if balance_from == 0 {193 <Balance<T>>::remove((collection.id, from));194 } else {195 <Balance<T>>::insert((collection.id, from), balance_from);196 }197 <Balance<T>>::insert((collection.id, to), balance_to);198 }199200 collection.log_infallible(ERC20Events::Transfer {201 from: *from.as_eth(),202 to: *to.as_eth(),203 value: amount.into(),204 });205 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(206 collection.id,207 TokenId::default(),208 from.clone(),209 to.clone(),210 amount,211 ));212 Ok(())213 }214215 pub fn create_multiple_items(216 collection: &FungibleHandle<T>,217 sender: &T::CrossAccountId,218 data: Vec<CreateItemData<T>>,219 ) -> DispatchResult {220 let unrestricted_minting = collection.is_owner_or_admin(sender)?;221 if !unrestricted_minting {222 ensure!(223 collection.mint_mode,224 <CommonError<T>>::PublicMintingNotAllowed225 );226 collection.check_allowlist(sender)?;227228 for (owner, _) in data.iter() {229 collection.check_allowlist(owner)?;230 }231 }232233 let mut balances = BTreeMap::new();234235 let total_supply = data236 .iter()237 .map(|u| u.1)238 .try_fold(0u128, |acc, v| acc.checked_add(v))239 .ok_or(ArithmeticError::Overflow)?;240241 for (user, amount) in data.into_iter() {242 collection.consume_sload()?;243 let balance = balances244 .entry(user.clone())245 .or_insert_with(|| <Balance<T>>::get((collection.id, user)));246 *balance = (*balance)247 .checked_add(amount)248 .ok_or(ArithmeticError::Overflow)?;249 }250251 collection.consume_sstore()?;252 for _ in &balances {253 collection.consume_sstore()?;254 collection.consume_log(2, 32)?;255 collection.consume_sstore()?;256 }257258 // =========259260 <TotalSupply<T>>::insert(collection.id, total_supply);261 for (user, amount) in balances {262 <Balance<T>>::insert((collection.id, &user), amount);263264 collection.log_infallible(ERC20Events::Transfer {265 from: H160::default(),266 to: *user.as_eth(),267 value: amount.into(),268 });269 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(270 collection.id,271 TokenId::default(),272 user.clone(),273 amount,274 ));275 }276277 Ok(())278 }279280 fn set_allowance_unchecked(281 collection: &FungibleHandle<T>,282 owner: &T::CrossAccountId,283 spender: &T::CrossAccountId,284 amount: u128,285 ) {286 <Allowance<T>>::insert((collection.id, owner, spender), amount);287288 collection.log_infallible(ERC20Events::Approval {289 owner: *owner.as_eth(),290 spender: *spender.as_eth(),291 value: amount.into(),292 });293 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(294 collection.id,295 TokenId(0),296 owner.clone(),297 spender.clone(),298 amount,299 ));300 }301302 pub fn set_allowance(303 collection: &FungibleHandle<T>,304 owner: &T::CrossAccountId,305 spender: &T::CrossAccountId,306 amount: u128,307 ) -> DispatchResult {308 if collection.access == AccessMode::WhiteList {309 collection.check_allowlist(&owner)?;310 collection.check_allowlist(&spender)?;311 }312313 if <Balance<T>>::get((collection.id, owner)) < amount {314 ensure!(315 collection.ignores_owned_amount(owner)?,316 <CommonError<T>>::CantApproveMoreThanOwned317 );318 }319320 // =========321322 Self::set_allowance_unchecked(collection, owner, spender, amount);323 Ok(())324 }325326 pub fn transfer_from(327 collection: &FungibleHandle<T>,328 spender: &T::CrossAccountId,329 from: &T::CrossAccountId,330 to: &T::CrossAccountId,331 amount: u128,332 ) -> DispatchResult {333 if spender.conv_eq(from) {334 return Self::transfer(collection, from, to, amount);335 }336 if collection.access == AccessMode::WhiteList {337 // `from`, `to` checked in [`transfer`]338 collection.check_allowlist(spender)?;339 }340341 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);342 if allowance.is_none() {343 ensure!(344 collection.ignores_allowance(spender)?,345 <CommonError<T>>::TokenValueNotEnough346 );347 }348349 // =========350351 Self::transfer(collection, from, to, amount)?;352 if let Some(allowance) = allowance {353 Self::set_allowance_unchecked(collection, from, spender, allowance);354 }355 Ok(())356 }357358 pub fn burn_from(359 collection: &FungibleHandle<T>,360 spender: &T::CrossAccountId,361 from: &T::CrossAccountId,362 amount: u128,363 ) -> DispatchResult {364 if spender.conv_eq(from) {365 return Self::burn(collection, from, amount);366 }367 if collection.access == AccessMode::WhiteList {368 // `from` checked in [`burn`]369 collection.check_allowlist(spender)?;370 }371372 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);373 if allowance.is_none() {374 ensure!(375 collection.ignores_allowance(spender)?,376 <CommonError<T>>::TokenValueNotEnough377 );378 }379380 // =========381382 Self::burn(collection, from, amount)?;383 if let Some(allowance) = allowance {384 Self::set_allowance_unchecked(collection, from, spender, allowance);385 }386 Ok(())387 }388389 /// Delegated to `create_multiple_items`390 pub fn create_item(391 collection: &FungibleHandle<T>,392 sender: &T::CrossAccountId,393 data: CreateItemData<T>,394 ) -> DispatchResult {395 Self::create_multiple_items(collection, sender, vec![data])396 }397}1#![cfg_attr(not(feature = "std"), no_std)]23use core::ops::Deref;4use frame_support::{ensure};5use nft_data_structs::{AccessMode, Collection, CollectionId, TokenId};6use pallet_common::{7 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,8};9use sp_core::H160;10use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};11use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};1213pub use pallet::*;1415use crate::erc::ERC20Events;16#[cfg(feature = "runtime-benchmarks")]17pub mod benchmarking;18pub mod common;19pub mod erc;20pub mod weights;2122pub type CreateItemData<T> = (<T as pallet_common::Config>::CrossAccountId, u128);23pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2425#[frame_support::pallet]26pub mod pallet {27 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};28 use nft_data_structs::CollectionId;29 use super::weights::WeightInfo;3031 #[pallet::error]32 pub enum Error<T> {33 /// Not Fungible item data used to mint in Fungible collection.34 NotFungibleDataUsedToMintFungibleCollectionToken,35 /// Not default id passed as TokenId argument36 FungibleItemsHaveNoId,37 /// Tried to set data for fungible item38 FungibleItemsHaveData,39 }4041 #[pallet::config]42 pub trait Config: frame_system::Config + pallet_common::Config {43 type WeightInfo: WeightInfo;44 }4546 #[pallet::pallet]47 #[pallet::generate_store(pub(super) trait Store)]48 pub struct Pallet<T>(_);4950 #[pallet::storage]51 pub(super) type TotalSupply<T: Config> =52 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;5354 #[pallet::storage]55 pub(super) type Balance<T: Config> = StorageNMap<56 Key = (57 Key<Twox64Concat, CollectionId>,58 Key<Blake2_128Concat, T::CrossAccountId>,59 ),60 Value = u128,61 QueryKind = ValueQuery,62 >;6364 #[pallet::storage]65 pub(super) type Allowance<T: Config> = StorageNMap<66 Key = (67 Key<Twox64Concat, CollectionId>,68 Key<Blake2_128, T::CrossAccountId>,69 Key<Blake2_128Concat, T::CrossAccountId>,70 ),71 Value = u128,72 QueryKind = ValueQuery,73 >;74}7576pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);77impl<T: Config> FungibleHandle<T> {78 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {79 Self(inner)80 }81 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {82 self.083 }84}85impl<T: Config> Deref for FungibleHandle<T> {86 type Target = pallet_common::CollectionHandle<T>;8788 fn deref(&self) -> &Self::Target {89 &self.090 }91}9293impl<T: Config> Pallet<T> {94 pub fn init_collection(data: Collection<T>) -> Result<CollectionId, DispatchError> {95 PalletCommon::init_collection(data)96 }97 pub fn destroy_collection(98 collection: FungibleHandle<T>,99 sender: &T::CrossAccountId,100 ) -> DispatchResult {101 let id = collection.id;102103 // =========104105 PalletCommon::destroy_collection(collection.0, sender)?;106107 <TotalSupply<T>>::remove(id);108 <Balance<T>>::remove_prefix((id,), None);109 <Allowance<T>>::remove_prefix((id,), None);110 Ok(())111 }112113 pub fn burn(114 collection: &FungibleHandle<T>,115 owner: &T::CrossAccountId,116 amount: u128,117 ) -> DispatchResult {118 let total_supply = <TotalSupply<T>>::get(collection.id)119 .checked_sub(amount)120 .ok_or(<CommonError<T>>::TokenValueTooLow)?;121122 let balance = <Balance<T>>::get((collection.id, owner))123 .checked_sub(amount)124 .ok_or(<CommonError<T>>::TokenValueTooLow)?;125126 if collection.access == AccessMode::WhiteList {127 collection.check_allowlist(owner)?;128 }129130 // =========131132 if balance == 0 {133 <Balance<T>>::remove((collection.id, owner));134 } else {135 <Balance<T>>::insert((collection.id, owner), balance);136 }137 <TotalSupply<T>>::insert(collection.id, total_supply);138139 collection.log_infallible(ERC20Events::Transfer {140 from: *owner.as_eth(),141 to: H160::default(),142 value: amount.into(),143 });144 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(145 collection.id,146 TokenId::default(),147 owner.clone(),148 amount,149 ));150 Ok(())151 }152153 pub fn transfer(154 collection: &FungibleHandle<T>,155 from: &T::CrossAccountId,156 to: &T::CrossAccountId,157 amount: u128,158 ) -> DispatchResult {159 ensure!(160 collection.limits.transfers_enabled(),161 <CommonError<T>>::TransferNotAllowed,162 );163164 if collection.access == AccessMode::WhiteList {165 collection.check_allowlist(from)?;166 collection.check_allowlist(to)?;167 }168 <PalletCommon<T>>::ensure_correct_receiver(to)?;169170 let balance_from = <Balance<T>>::get((collection.id, from))171 .checked_sub(amount)172 .ok_or(<CommonError<T>>::TokenValueTooLow)?;173 let balance_to = if from != to {174 Some(175 <Balance<T>>::get((collection.id, to))176 .checked_add(amount)177 .ok_or(ArithmeticError::Overflow)?,178 )179 } else {180 None181 };182183 collection.consume_sstore()?;184 collection.consume_sstore()?;185 collection.consume_log(2, 32)?;186 collection.consume_sstore()?;187188 // =========189190 if let Some(balance_to) = balance_to {191 // from != to192 if balance_from == 0 {193 <Balance<T>>::remove((collection.id, from));194 } else {195 <Balance<T>>::insert((collection.id, from), balance_from);196 }197 <Balance<T>>::insert((collection.id, to), balance_to);198 }199200 collection.log_infallible(ERC20Events::Transfer {201 from: *from.as_eth(),202 to: *to.as_eth(),203 value: amount.into(),204 });205 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(206 collection.id,207 TokenId::default(),208 from.clone(),209 to.clone(),210 amount,211 ));212 Ok(())213 }214215 pub fn create_multiple_items(216 collection: &FungibleHandle<T>,217 sender: &T::CrossAccountId,218 data: Vec<CreateItemData<T>>,219 ) -> DispatchResult {220 let unrestricted_minting = collection.is_owner_or_admin(sender)?;221 if !unrestricted_minting {222 ensure!(223 collection.mint_mode,224 <CommonError<T>>::PublicMintingNotAllowed225 );226 collection.check_allowlist(sender)?;227228 for (owner, _) in data.iter() {229 collection.check_allowlist(owner)?;230 }231 }232233 let mut balances = BTreeMap::new();234235 let total_supply = data236 .iter()237 .map(|u| u.1)238 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {239 acc.checked_add(v)240 })241 .ok_or(ArithmeticError::Overflow)?;242243 for (user, amount) in data.into_iter() {244 collection.consume_sload()?;245 let balance = balances246 .entry(user.clone())247 .or_insert_with(|| <Balance<T>>::get((collection.id, user)));248 *balance = (*balance)249 .checked_add(amount)250 .ok_or(ArithmeticError::Overflow)?;251 }252253 collection.consume_sstore()?;254 for _ in &balances {255 collection.consume_sstore()?;256 collection.consume_log(2, 32)?;257 collection.consume_sstore()?;258 }259260 // =========261262 <TotalSupply<T>>::insert(collection.id, total_supply);263 for (user, amount) in balances {264 <Balance<T>>::insert((collection.id, &user), amount);265266 collection.log_infallible(ERC20Events::Transfer {267 from: H160::default(),268 to: *user.as_eth(),269 value: amount.into(),270 });271 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(272 collection.id,273 TokenId::default(),274 user.clone(),275 amount,276 ));277 }278279 Ok(())280 }281282 fn set_allowance_unchecked(283 collection: &FungibleHandle<T>,284 owner: &T::CrossAccountId,285 spender: &T::CrossAccountId,286 amount: u128,287 ) {288 <Allowance<T>>::insert((collection.id, owner, spender), amount);289290 collection.log_infallible(ERC20Events::Approval {291 owner: *owner.as_eth(),292 spender: *spender.as_eth(),293 value: amount.into(),294 });295 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(296 collection.id,297 TokenId(0),298 owner.clone(),299 spender.clone(),300 amount,301 ));302 }303304 pub fn set_allowance(305 collection: &FungibleHandle<T>,306 owner: &T::CrossAccountId,307 spender: &T::CrossAccountId,308 amount: u128,309 ) -> DispatchResult {310 if collection.access == AccessMode::WhiteList {311 collection.check_allowlist(&owner)?;312 collection.check_allowlist(&spender)?;313 }314315 if <Balance<T>>::get((collection.id, owner)) < amount {316 ensure!(317 collection.ignores_owned_amount(owner)?,318 <CommonError<T>>::CantApproveMoreThanOwned319 );320 }321322 // =========323324 Self::set_allowance_unchecked(collection, owner, spender, amount);325 Ok(())326 }327328 pub fn transfer_from(329 collection: &FungibleHandle<T>,330 spender: &T::CrossAccountId,331 from: &T::CrossAccountId,332 to: &T::CrossAccountId,333 amount: u128,334 ) -> DispatchResult {335 if spender.conv_eq(from) {336 return Self::transfer(collection, from, to, amount);337 }338 if collection.access == AccessMode::WhiteList {339 // `from`, `to` checked in [`transfer`]340 collection.check_allowlist(spender)?;341 }342343 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);344 if allowance.is_none() {345 ensure!(346 collection.ignores_allowance(spender)?,347 <CommonError<T>>::TokenValueNotEnough348 );349 }350351 // =========352353 Self::transfer(collection, from, to, amount)?;354 if let Some(allowance) = allowance {355 Self::set_allowance_unchecked(collection, from, spender, allowance);356 }357 Ok(())358 }359360 pub fn burn_from(361 collection: &FungibleHandle<T>,362 spender: &T::CrossAccountId,363 from: &T::CrossAccountId,364 amount: u128,365 ) -> DispatchResult {366 if spender.conv_eq(from) {367 return Self::burn(collection, from, amount);368 }369 if collection.access == AccessMode::WhiteList {370 // `from` checked in [`burn`]371 collection.check_allowlist(spender)?;372 }373374 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);375 if allowance.is_none() {376 ensure!(377 collection.ignores_allowance(spender)?,378 <CommonError<T>>::TokenValueNotEnough379 );380 }381382 // =========383384 Self::burn(collection, from, amount)?;385 if let Some(allowance) = allowance {386 Self::set_allowance_unchecked(collection, from, spender, allowance);387 }388 Ok(())389 }390391 /// Delegated to `create_multiple_items`392 pub fn create_item(393 collection: &FungibleHandle<T>,394 sender: &T::CrossAccountId,395 data: CreateItemData<T>,396 ) -> DispatchResult {397 Self::create_multiple_items(collection, sender, vec![data])398 }399}