difftreelog
chore add transfer events for transfering from and to partial ownership
in: master
3 files changed
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -34,9 +34,8 @@
CommonEvmHandler, CollectionCall,
static_property::{key, value as property_value},
},
- eth::collection_id_to_address,
};
-use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm, PrecompileHandle};
+use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
use sp_core::H160;
@@ -51,6 +50,8 @@
TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,
};
+pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);
+
/// @title A contract that allows to set and delete token properties and change token property permissions.
#[solidity_interface(name = "TokenProperties")]
impl<T: Config> RefungibleHandle<T> {
@@ -298,13 +299,20 @@
Ok(balance.into())
}
+ /// @notice Find the owner of an RFT
+ /// @dev RFTs assigned to zero address are considered invalid, and queries
+ /// about them do throw.
+ /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for
+ /// the tokens that are partially owned.
+ /// @param tokenId The identifier for an RFT
+ /// @return The address of the owner of the RFT
fn owner_of(&self, token_id: uint256) -> Result<address> {
self.consume_store_reads(2)?;
let token = token_id.try_into()?;
let owner = <Pallet<T>>::token_owner(self.id, token);
Ok(owner
.map(|address| *address.as_eth())
- .unwrap_or_else(|| H160::default()))
+ .unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))
}
/// @dev Not implemented
@@ -366,14 +374,6 @@
<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)
.map_err(dispatch_to_evm::<T>)?;
- <PalletEvm<T>>::deposit_log(
- ERC721Events::Transfer {
- from: *from.as_eth(),
- to: *to.as_eth(),
- token_id: token_id.into(),
- }
- .to_log(collection_id_to_address(self.id)),
- );
Ok(())
}
@@ -652,14 +652,6 @@
<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)
.map_err(dispatch_to_evm::<T>)?;
- <PalletEvm<T>>::deposit_log(
- ERC721Events::Transfer {
- from: *caller.as_eth(),
- to: *to.as_eth(),
- token_id: token_id.into(),
- }
- .to_log(collection_id_to_address(self.id)),
- );
Ok(())
}
pallets/refungible/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//! of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//! Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//! transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//! an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//! with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//! collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//! some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//! Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;91use crate::erc::ERC721Events;9293use codec::{Encode, Decode, MaxEncodedLen};94use core::ops::Deref;95use evm_coder::ToLog;96use frame_support::{BoundedVec, ensure, fail, storage::with_transaction, transactional};97use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};98use pallet_evm_coder_substrate::WithRecorder;99use pallet_common::{100 CommonCollectionOperations, Error as CommonError, Event as CommonEvent,101 eth::collection_id_to_address, Pallet as PalletCommon,102};103use pallet_structure::Pallet as PalletStructure;104use scale_info::TypeInfo;105use sp_core::H160;106use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};107use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};108use up_data_structs::{109 AccessMode, budget::Budget, CollectionId, CreateCollectionData, CreateRefungibleExData,110 CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId, Property,111 PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,112 TrySetProperty,113};114115pub use pallet::*;116#[cfg(feature = "runtime-benchmarks")]117pub mod benchmarking;118pub mod common;119pub mod erc;120pub mod erc_token;121pub mod weights;122123pub type CreateItemData<T> =124 CreateRefungibleExData<<T as pallet_evm::account::Config>::CrossAccountId>;125pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;126127/// Token data, stored independently from other data used to describe it128/// for the convenience of database access. Notably contains the token metadata.129#[struct_versioning::versioned(version = 2, upper)]130#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]131pub struct ItemData {132 pub const_data: BoundedVec<u8, CustomDataLimit>,133134 #[version(..2)]135 pub variable_data: BoundedVec<u8, CustomDataLimit>,136}137138#[frame_support::pallet]139pub mod pallet {140 use super::*;141 use frame_support::{142 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,143 traits::StorageVersion,144 };145 use frame_system::pallet_prelude::*;146 use up_data_structs::{CollectionId, TokenId};147 use super::weights::WeightInfo;148149 #[pallet::error]150 pub enum Error<T> {151 /// Not Refungible item data used to mint in Refungible collection.152 NotRefungibleDataUsedToMintFungibleCollectionToken,153 /// Maximum refungibility exceeded.154 WrongRefungiblePieces,155 /// Refungible token can't be repartitioned by user who isn't owns all pieces.156 RepartitionWhileNotOwningAllPieces,157 /// Refungible token can't nest other tokens.158 RefungibleDisallowsNesting,159 /// Setting item properties is not allowed.160 SettingPropertiesNotAllowed,161 }162163 #[pallet::config]164 pub trait Config:165 frame_system::Config + pallet_common::Config + pallet_structure::Config166 {167 type WeightInfo: WeightInfo;168 }169170 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);171172 #[pallet::pallet]173 #[pallet::storage_version(STORAGE_VERSION)]174 #[pallet::generate_store(pub(super) trait Store)]175 pub struct Pallet<T>(_);176177 /// Total amount of minted tokens in a collection.178 #[pallet::storage]179 pub type TokensMinted<T: Config> =180 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;181182 /// Amount of tokens burnt in a collection.183 #[pallet::storage]184 pub type TokensBurnt<T: Config> =185 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;186187 /// Token data, used to partially describe a token.188 #[pallet::storage]189 pub type TokenData<T: Config> = StorageNMap<190 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),191 Value = ItemData,192 QueryKind = ValueQuery,193 >;194195 /// Amount of pieces a refungible token is split into.196 #[pallet::storage]197 #[pallet::getter(fn token_properties)]198 pub type TokenProperties<T: Config> = StorageNMap<199 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),200 Value = up_data_structs::Properties,201 QueryKind = ValueQuery,202 OnEmpty = up_data_structs::TokenProperties,203 >;204205 /// Total amount of pieces for token206 #[pallet::storage]207 pub type TotalSupply<T: Config> = StorageNMap<208 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),209 Value = u128,210 QueryKind = ValueQuery,211 >;212213 /// Used to enumerate tokens owned by account.214 #[pallet::storage]215 pub type Owned<T: Config> = StorageNMap<216 Key = (217 Key<Twox64Concat, CollectionId>,218 Key<Blake2_128Concat, T::CrossAccountId>,219 Key<Twox64Concat, TokenId>,220 ),221 Value = bool,222 QueryKind = ValueQuery,223 >;224225 /// Amount of tokens (not pieces) partially owned by an account within a collection.226 #[pallet::storage]227 pub type AccountBalance<T: Config> = StorageNMap<228 Key = (229 Key<Twox64Concat, CollectionId>,230 // Owner231 Key<Blake2_128Concat, T::CrossAccountId>,232 ),233 Value = u32,234 QueryKind = ValueQuery,235 >;236237 /// Amount of token pieces owned by account.238 #[pallet::storage]239 pub type Balance<T: Config> = StorageNMap<240 Key = (241 Key<Twox64Concat, CollectionId>,242 Key<Twox64Concat, TokenId>,243 // Owner244 Key<Blake2_128Concat, T::CrossAccountId>,245 ),246 Value = u128,247 QueryKind = ValueQuery,248 >;249250 /// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.251 #[pallet::storage]252 pub type Allowance<T: Config> = StorageNMap<253 Key = (254 Key<Twox64Concat, CollectionId>,255 Key<Twox64Concat, TokenId>,256 // Owner257 Key<Blake2_128, T::CrossAccountId>,258 // Spender259 Key<Blake2_128Concat, T::CrossAccountId>,260 ),261 Value = u128,262 QueryKind = ValueQuery,263 >;264265 #[pallet::hooks]266 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {267 fn on_runtime_upgrade() -> Weight {268 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {269 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {270 Some(<ItemDataVersion2>::from(v))271 })272 }273274 0275 }276 }277}278279pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);280impl<T: Config> RefungibleHandle<T> {281 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {282 Self(inner)283 }284 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {285 self.0286 }287 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {288 &mut self.0289 }290}291292impl<T: Config> Deref for RefungibleHandle<T> {293 type Target = pallet_common::CollectionHandle<T>;294295 fn deref(&self) -> &Self::Target {296 &self.0297 }298}299300impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {301 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {302 self.0.recorder()303 }304 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {305 self.0.into_recorder()306 }307}308309impl<T: Config> Pallet<T> {310 /// Get number of RFT tokens in collection311 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {312 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)313 }314315 /// Check that RFT token exists316 ///317 /// - `token`: Token ID.318 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {319 <TotalSupply<T>>::contains_key((collection.id, token))320 }321322 pub fn set_scoped_token_property(323 collection_id: CollectionId,324 token_id: TokenId,325 scope: PropertyScope,326 property: Property,327 ) -> DispatchResult {328 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {329 properties.try_scoped_set(scope, property.key, property.value)330 })331 .map_err(<CommonError<T>>::from)?;332333 Ok(())334 }335336 pub fn set_scoped_token_properties(337 collection_id: CollectionId,338 token_id: TokenId,339 scope: PropertyScope,340 properties: impl Iterator<Item = Property>,341 ) -> DispatchResult {342 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {343 stored_properties.try_scoped_set_from_iter(scope, properties)344 })345 .map_err(<CommonError<T>>::from)?;346347 Ok(())348 }349}350351// unchecked calls skips any permission checks352impl<T: Config> Pallet<T> {353 /// Create RFT collection354 ///355 /// `init_collection` will take non-refundable deposit for collection creation.356 ///357 /// - `data`: Contains settings for collection limits and permissions.358 pub fn init_collection(359 owner: T::CrossAccountId,360 data: CreateCollectionData<T::AccountId>,361 ) -> Result<CollectionId, DispatchError> {362 <PalletCommon<T>>::init_collection(owner, data, false)363 }364365 /// Destroy RFT collection366 ///367 /// `destroy_collection` will throw error if collection contains any tokens.368 /// Only owner can destroy collection.369 pub fn destroy_collection(370 collection: RefungibleHandle<T>,371 sender: &T::CrossAccountId,372 ) -> DispatchResult {373 let id = collection.id;374375 if Self::collection_has_tokens(id) {376 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());377 }378379 // =========380381 PalletCommon::destroy_collection(collection.0, sender)?;382383 <TokensMinted<T>>::remove(id);384 <TokensBurnt<T>>::remove(id);385 <TokenData<T>>::remove_prefix((id,), None);386 <TotalSupply<T>>::remove_prefix((id,), None);387 <Balance<T>>::remove_prefix((id,), None);388 <Allowance<T>>::remove_prefix((id,), None);389 <Owned<T>>::remove_prefix((id,), None);390 <AccountBalance<T>>::remove_prefix((id,), None);391 Ok(())392 }393394 fn collection_has_tokens(collection_id: CollectionId) -> bool {395 <TokenData<T>>::iter_prefix((collection_id,))396 .next()397 .is_some()398 }399400 pub fn burn_token_unchecked(401 collection: &RefungibleHandle<T>,402 token_id: TokenId,403 ) -> DispatchResult {404 let burnt = <TokensBurnt<T>>::get(collection.id)405 .checked_add(1)406 .ok_or(ArithmeticError::Overflow)?;407408 <TokensBurnt<T>>::insert(collection.id, burnt);409 <TokenData<T>>::remove((collection.id, token_id));410 <TokenProperties<T>>::remove((collection.id, token_id));411 <TotalSupply<T>>::remove((collection.id, token_id));412 <Balance<T>>::remove_prefix((collection.id, token_id), None);413 <Allowance<T>>::remove_prefix((collection.id, token_id), None);414 // TODO: ERC721 transfer event415 Ok(())416 }417418 /// Burn RFT token pieces419 ///420 /// `burn` will decrease total amount of token pieces and amount owned by sender.421 /// `burn` can be called even if there are multiple owners of the RFT token.422 /// If sender wouldn't have any pieces left after `burn` than she will stop being423 /// one of the owners of the token. If there is no account that owns any pieces of424 /// the token than token will be burned too.425 ///426 /// - `amount`: Amount of token pieces to burn.427 /// - `token`: Token who's pieces should be burned428 /// - `collection`: Collection that contains the token429 pub fn burn(430 collection: &RefungibleHandle<T>,431 owner: &T::CrossAccountId,432 token: TokenId,433 amount: u128,434 ) -> DispatchResult {435 let total_supply = <TotalSupply<T>>::get((collection.id, token))436 .checked_sub(amount)437 .ok_or(<CommonError<T>>::TokenValueTooLow)?;438439 // This was probally last owner of this token?440 if total_supply == 0 {441 // Ensure user actually owns this amount442 ensure!(443 <Balance<T>>::get((collection.id, token, owner)) == amount,444 <CommonError<T>>::TokenValueTooLow445 );446 let account_balance = <AccountBalance<T>>::get((collection.id, owner))447 .checked_sub(1)448 // Should not occur449 .ok_or(ArithmeticError::Underflow)?;450451 // =========452453 <Owned<T>>::remove((collection.id, owner, token));454 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);455 <AccountBalance<T>>::insert((collection.id, owner), account_balance);456 Self::burn_token_unchecked(collection, token)?;457 <PalletEvm<T>>::deposit_log(458 ERC721Events::Transfer {459 from: *owner.as_eth(),460 to: H160::default(),461 token_id: token.into(),462 }463 .to_log(collection_id_to_address(collection.id)),464 );465 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(466 collection.id,467 token,468 owner.clone(),469 amount,470 ));471 return Ok(());472 }473474 let balance = <Balance<T>>::get((collection.id, token, owner))475 .checked_sub(amount)476 .ok_or(<CommonError<T>>::TokenValueTooLow)?;477 let account_balance = if balance == 0 {478 <AccountBalance<T>>::get((collection.id, owner))479 .checked_sub(1)480 // Should not occur481 .ok_or(ArithmeticError::Underflow)?482 } else {483 0484 };485486 // =========487488 if balance == 0 {489 <Owned<T>>::remove((collection.id, owner, token));490 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);491 <Balance<T>>::remove((collection.id, token, owner));492 <AccountBalance<T>>::insert((collection.id, owner), account_balance);493 } else {494 <Balance<T>>::insert((collection.id, token, owner), balance);495 }496 <TotalSupply<T>>::insert((collection.id, token), total_supply);497498 <PalletEvm<T>>::deposit_log(499 ERC20Events::Transfer {500 from: *owner.as_eth(),501 to: H160::default(),502 value: amount.into(),503 }504 .to_log(T::EvmTokenAddressMapping::token_to_address(505 collection.id,506 token,507 )),508 );509 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(510 collection.id,511 token,512 owner.clone(),513 amount,514 ));515 Ok(())516 }517518 #[transactional]519 fn modify_token_properties(520 collection: &RefungibleHandle<T>,521 sender: &T::CrossAccountId,522 token_id: TokenId,523 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,524 is_token_create: bool,525 nesting_budget: &dyn Budget,526 ) -> DispatchResult {527 let is_collection_admin = || collection.is_owner_or_admin(sender);528 let is_token_owner = || -> Result<bool, DispatchError> {529 let balance = collection.balance(sender.clone(), token_id);530 let total_pieces: u128 =531 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);532 if balance != total_pieces {533 return Ok(false);534 }535536 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(537 sender.clone(),538 collection.id,539 token_id,540 None,541 nesting_budget,542 )?;543544 Ok(is_bundle_owner)545 };546547 for (key, value) in properties {548 let permission = <PalletCommon<T>>::property_permissions(collection.id)549 .get(&key)550 .cloned()551 .unwrap_or_else(PropertyPermission::none);552553 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))554 .get(&key)555 .is_some();556557 match permission {558 PropertyPermission { mutable: false, .. } if is_property_exists => {559 return Err(<CommonError<T>>::NoPermission.into());560 }561562 PropertyPermission {563 collection_admin,564 token_owner,565 ..566 } => {567 //TODO: investigate threats during public minting.568 let is_token_create =569 is_token_create && (collection_admin || token_owner) && value.is_some();570 if !(is_token_create571 || (collection_admin && is_collection_admin())572 || (token_owner && is_token_owner()?))573 {574 fail!(<CommonError<T>>::NoPermission);575 }576 }577 }578579 match value {580 Some(value) => {581 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {582 properties.try_set(key.clone(), value)583 })584 .map_err(<CommonError<T>>::from)?;585586 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(587 collection.id,588 token_id,589 key,590 ));591 }592 None => {593 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {594 properties.remove(&key)595 })596 .map_err(<CommonError<T>>::from)?;597598 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(599 collection.id,600 token_id,601 key,602 ));603 }604 }605 }606607 Ok(())608 }609610 pub fn set_token_properties(611 collection: &RefungibleHandle<T>,612 sender: &T::CrossAccountId,613 token_id: TokenId,614 properties: impl Iterator<Item = Property>,615 is_token_create: bool,616 nesting_budget: &dyn Budget,617 ) -> DispatchResult {618 Self::modify_token_properties(619 collection,620 sender,621 token_id,622 properties.map(|p| (p.key, Some(p.value))),623 is_token_create,624 nesting_budget,625 )626 }627628 pub fn set_token_property(629 collection: &RefungibleHandle<T>,630 sender: &T::CrossAccountId,631 token_id: TokenId,632 property: Property,633 nesting_budget: &dyn Budget,634 ) -> DispatchResult {635 let is_token_create = false;636637 Self::set_token_properties(638 collection,639 sender,640 token_id,641 [property].into_iter(),642 is_token_create,643 nesting_budget,644 )645 }646647 pub fn delete_token_properties(648 collection: &RefungibleHandle<T>,649 sender: &T::CrossAccountId,650 token_id: TokenId,651 property_keys: impl Iterator<Item = PropertyKey>,652 nesting_budget: &dyn Budget,653 ) -> DispatchResult {654 let is_token_create = false;655656 Self::modify_token_properties(657 collection,658 sender,659 token_id,660 property_keys.into_iter().map(|key| (key, None)),661 is_token_create,662 nesting_budget,663 )664 }665666 pub fn delete_token_property(667 collection: &RefungibleHandle<T>,668 sender: &T::CrossAccountId,669 token_id: TokenId,670 property_key: PropertyKey,671 nesting_budget: &dyn Budget,672 ) -> DispatchResult {673 Self::delete_token_properties(674 collection,675 sender,676 token_id,677 [property_key].into_iter(),678 nesting_budget,679 )680 }681682 /// Transfer RFT token pieces from one account to another.683 ///684 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.685 ///686 /// - `from`: Owner of token pieces to transfer.687 /// - `to`: Recepient of transfered token pieces.688 /// - `amount`: Amount of token pieces to transfer.689 /// - `token`: Token whos pieces should be transfered690 /// - `collection`: Collection that contains the token691 pub fn transfer(692 collection: &RefungibleHandle<T>,693 from: &T::CrossAccountId,694 to: &T::CrossAccountId,695 token: TokenId,696 amount: u128,697 nesting_budget: &dyn Budget,698 ) -> DispatchResult {699 ensure!(700 collection.limits.transfers_enabled(),701 <CommonError<T>>::TransferNotAllowed702 );703704 if collection.permissions.access() == AccessMode::AllowList {705 collection.check_allowlist(from)?;706 collection.check_allowlist(to)?;707 }708 <PalletCommon<T>>::ensure_correct_receiver(to)?;709710 let balance_from = <Balance<T>>::get((collection.id, token, from))711 .checked_sub(amount)712 .ok_or(<CommonError<T>>::TokenValueTooLow)?;713 let mut create_target = false;714 let from_to_differ = from != to;715 let balance_to = if from != to {716 let old_balance = <Balance<T>>::get((collection.id, token, to));717 if old_balance == 0 {718 create_target = true;719 }720 Some(721 old_balance722 .checked_add(amount)723 .ok_or(ArithmeticError::Overflow)?,724 )725 } else {726 None727 };728729 let account_balance_from = if balance_from == 0 {730 Some(731 <AccountBalance<T>>::get((collection.id, from))732 .checked_sub(1)733 // Should not occur734 .ok_or(ArithmeticError::Underflow)?,735 )736 } else {737 None738 };739 // Account data is created in token, AccountBalance should be increased740 // But only if from != to as we shouldn't check overflow in this case741 let account_balance_to = if create_target && from_to_differ {742 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))743 .checked_add(1)744 .ok_or(ArithmeticError::Overflow)?;745 ensure!(746 account_balance_to < collection.limits.account_token_ownership_limit(),747 <CommonError<T>>::AccountTokenLimitExceeded,748 );749750 Some(account_balance_to)751 } else {752 None753 };754755 // =========756757 <PalletStructure<T>>::nest_if_sent_to_token(758 from.clone(),759 to,760 collection.id,761 token,762 nesting_budget,763 )?;764765 if let Some(balance_to) = balance_to {766 // from != to767 if balance_from == 0 {768 <Balance<T>>::remove((collection.id, token, from));769 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);770 } else {771 <Balance<T>>::insert((collection.id, token, from), balance_from);772 }773 <Balance<T>>::insert((collection.id, token, to), balance_to);774 if let Some(account_balance_from) = account_balance_from {775 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);776 <Owned<T>>::remove((collection.id, from, token));777 }778 if let Some(account_balance_to) = account_balance_to {779 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);780 <Owned<T>>::insert((collection.id, to, token), true);781 }782 }783784 <PalletEvm<T>>::deposit_log(785 ERC20Events::Transfer {786 from: *from.as_eth(),787 to: *to.as_eth(),788 value: amount.into(),789 }790 .to_log(T::EvmTokenAddressMapping::token_to_address(791 collection.id,792 token,793 )),794 );795796 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(797 collection.id,798 token,799 from.clone(),800 to.clone(),801 amount,802 ));803 Ok(())804 }805806 /// Batched operation to create multiple RFT tokens.807 ///808 /// Same as `create_item` but creates multiple tokens.809 ///810 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.811 pub fn create_multiple_items(812 collection: &RefungibleHandle<T>,813 sender: &T::CrossAccountId,814 data: Vec<CreateItemData<T>>,815 nesting_budget: &dyn Budget,816 ) -> DispatchResult {817 if !collection.is_owner_or_admin(sender) {818 ensure!(819 collection.permissions.mint_mode(),820 <CommonError<T>>::PublicMintingNotAllowed821 );822 collection.check_allowlist(sender)?;823824 for item in data.iter() {825 for user in item.users.keys() {826 collection.check_allowlist(user)?;827 }828 }829 }830831 for item in data.iter() {832 for (owner, _) in item.users.iter() {833 <PalletCommon<T>>::ensure_correct_receiver(owner)?;834 }835 }836837 // Total pieces per tokens838 let totals = data839 .iter()840 .map(|data| {841 Ok(data842 .users843 .iter()844 .map(|u| u.1)845 .try_fold(0u128, |acc, v| acc.checked_add(*v))846 .ok_or(ArithmeticError::Overflow)?)847 })848 .collect::<Result<Vec<_>, DispatchError>>()?;849 for total in &totals {850 ensure!(851 *total <= MAX_REFUNGIBLE_PIECES,852 <Error<T>>::WrongRefungiblePieces853 );854 }855856 let first_token_id = <TokensMinted<T>>::get(collection.id);857 let tokens_minted = first_token_id858 .checked_add(data.len() as u32)859 .ok_or(ArithmeticError::Overflow)?;860 ensure!(861 tokens_minted < collection.limits.token_limit(),862 <CommonError<T>>::CollectionTokenLimitExceeded863 );864865 let mut balances = BTreeMap::new();866 for data in &data {867 for owner in data.users.keys() {868 let balance = balances869 .entry(owner)870 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));871 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;872873 ensure!(874 *balance <= collection.limits.account_token_ownership_limit(),875 <CommonError<T>>::AccountTokenLimitExceeded,876 );877 }878 }879880 for (i, token) in data.iter().enumerate() {881 let token_id = TokenId(first_token_id + i as u32 + 1);882 for (to, _) in token.users.iter() {883 <PalletStructure<T>>::check_nesting(884 sender.clone(),885 to,886 collection.id,887 token_id,888 nesting_budget,889 )?;890 }891 }892893 // =========894895 with_transaction(|| {896 for (i, data) in data.iter().enumerate() {897 let token_id = first_token_id + i as u32 + 1;898 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);899900 <TokenData<T>>::insert(901 (collection.id, token_id),902 ItemData {903 const_data: data.const_data.clone(),904 },905 );906907 for (user, amount) in data.users.iter() {908 if *amount == 0 {909 continue;910 }911 <Balance<T>>::insert((collection.id, token_id, &user), amount);912 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);913 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(914 user,915 collection.id,916 TokenId(token_id),917 );918 }919920 if let Err(e) = Self::set_token_properties(921 collection,922 sender,923 TokenId(token_id),924 data.properties.clone().into_iter(),925 true,926 nesting_budget,927 ) {928 return TransactionOutcome::Rollback(Err(e));929 }930 }931 TransactionOutcome::Commit(Ok(()))932 })?;933934 <TokensMinted<T>>::insert(collection.id, tokens_minted);935936 for (account, balance) in balances {937 <AccountBalance<T>>::insert((collection.id, account), balance);938 }939940 for (i, token) in data.into_iter().enumerate() {941 let token_id = first_token_id + i as u32 + 1;942943 for (user, amount) in token.users.into_iter() {944 if amount == 0 {945 continue;946 }947948 <PalletEvm<T>>::deposit_log(949 ERC20Events::Transfer {950 from: H160::default(),951 to: *user.as_eth(),952 value: amount.into(),953 }954 .to_log(T::EvmTokenAddressMapping::token_to_address(955 collection.id,956 TokenId(token_id),957 )),958 );959 <PalletEvm<T>>::deposit_log(960 ERC721Events::Transfer {961 from: H160::default(),962 to: *user.as_eth(),963 token_id: token_id.into(),964 }965 .to_log(collection_id_to_address(collection.id)),966 );967 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(968 collection.id,969 TokenId(token_id),970 user,971 amount,972 ));973 }974 }975 Ok(())976 }977978 pub fn set_allowance_unchecked(979 collection: &RefungibleHandle<T>,980 sender: &T::CrossAccountId,981 spender: &T::CrossAccountId,982 token: TokenId,983 amount: u128,984 ) {985 if amount == 0 {986 <Allowance<T>>::remove((collection.id, token, sender, spender));987 } else {988 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);989 }990991 <PalletEvm<T>>::deposit_log(992 ERC20Events::Approval {993 owner: *sender.as_eth(),994 spender: *spender.as_eth(),995 value: amount.into(),996 }997 .to_log(T::EvmTokenAddressMapping::token_to_address(998 collection.id,999 token,1000 )),1001 );1002 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1003 collection.id,1004 token,1005 sender.clone(),1006 spender.clone(),1007 amount,1008 ))1009 }10101011 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1012 ///1013 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1014 pub fn set_allowance(1015 collection: &RefungibleHandle<T>,1016 sender: &T::CrossAccountId,1017 spender: &T::CrossAccountId,1018 token: TokenId,1019 amount: u128,1020 ) -> DispatchResult {1021 if collection.permissions.access() == AccessMode::AllowList {1022 collection.check_allowlist(sender)?;1023 collection.check_allowlist(spender)?;1024 }10251026 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10271028 if <Balance<T>>::get((collection.id, token, sender)) < amount {1029 ensure!(1030 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1031 <CommonError<T>>::CantApproveMoreThanOwned1032 );1033 }10341035 // =========10361037 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1038 Ok(())1039 }10401041 /// Returns allowance, which should be set after transaction1042 fn check_allowed(1043 collection: &RefungibleHandle<T>,1044 spender: &T::CrossAccountId,1045 from: &T::CrossAccountId,1046 token: TokenId,1047 amount: u128,1048 nesting_budget: &dyn Budget,1049 ) -> Result<Option<u128>, DispatchError> {1050 if spender.conv_eq(from) {1051 return Ok(None);1052 }1053 if collection.permissions.access() == AccessMode::AllowList {1054 // `from`, `to` checked in [`transfer`]1055 collection.check_allowlist(spender)?;1056 }1057 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1058 // TODO: should collection owner be allowed to perform this transfer?1059 ensure!(1060 <PalletStructure<T>>::check_indirectly_owned(1061 spender.clone(),1062 source.0,1063 source.1,1064 None,1065 nesting_budget1066 )?,1067 <CommonError<T>>::ApprovedValueTooLow,1068 );1069 return Ok(None);1070 }1071 let allowance =1072 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1073 if allowance.is_none() {1074 ensure!(1075 collection.ignores_allowance(spender),1076 <CommonError<T>>::ApprovedValueTooLow1077 );1078 }1079 Ok(allowance)1080 }10811082 /// Transfer RFT token pieces from one account to another.1083 ///1084 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1085 /// The owner should set allowance for the spender to transfer pieces.1086 ///1087 /// [`transfer`]: struct.Pallet.html#method.transfer1088 pub fn transfer_from(1089 collection: &RefungibleHandle<T>,1090 spender: &T::CrossAccountId,1091 from: &T::CrossAccountId,1092 to: &T::CrossAccountId,1093 token: TokenId,1094 amount: u128,1095 nesting_budget: &dyn Budget,1096 ) -> DispatchResult {1097 let allowance =1098 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10991100 // =========11011102 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1103 if let Some(allowance) = allowance {1104 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1105 }1106 Ok(())1107 }11081109 /// Burn RFT token pieces from the account.1110 ///1111 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1112 /// set allowance for the spender to burn pieces1113 ///1114 /// [`burn`]: struct.Pallet.html#method.burn1115 pub fn burn_from(1116 collection: &RefungibleHandle<T>,1117 spender: &T::CrossAccountId,1118 from: &T::CrossAccountId,1119 token: TokenId,1120 amount: u128,1121 nesting_budget: &dyn Budget,1122 ) -> DispatchResult {1123 let allowance =1124 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11251126 // =========11271128 Self::burn(collection, from, token, amount)?;1129 if let Some(allowance) = allowance {1130 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1131 }1132 Ok(())1133 }11341135 /// Create RFT token.1136 ///1137 /// The sender should be the owner/admin of the collection or collection should be configured1138 /// to allow public minting.1139 ///1140 /// - `data`: Contains list of users who will become the owners of the token pieces and amount1141 /// of token pieces they will receive.1142 pub fn create_item(1143 collection: &RefungibleHandle<T>,1144 sender: &T::CrossAccountId,1145 data: CreateItemData<T>,1146 nesting_budget: &dyn Budget,1147 ) -> DispatchResult {1148 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1149 }11501151 /// Repartition RFT token.1152 ///1153 /// `repartition` will set token balance of the sender and total amount of token pieces.1154 /// Sender should own all of the token pieces. `repartition' could be done even if some1155 /// token pieces were burned before.1156 ///1157 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.1158 pub fn repartition(1159 collection: &RefungibleHandle<T>,1160 owner: &T::CrossAccountId,1161 token: TokenId,1162 amount: u128,1163 ) -> DispatchResult {1164 ensure!(1165 amount <= MAX_REFUNGIBLE_PIECES,1166 <Error<T>>::WrongRefungiblePieces1167 );1168 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1169 // Ensure user owns all pieces1170 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1171 let balance = <Balance<T>>::get((collection.id, token, owner));1172 ensure!(1173 total_pieces == balance,1174 <Error<T>>::RepartitionWhileNotOwningAllPieces1175 );11761177 <Balance<T>>::insert((collection.id, token, owner), amount);1178 <TotalSupply<T>>::insert((collection.id, token), amount);11791180 if amount > total_pieces {1181 let mint_amount = amount - total_pieces;1182 <PalletEvm<T>>::deposit_log(1183 ERC20Events::Transfer {1184 from: H160::default(),1185 to: *owner.as_eth(),1186 value: mint_amount.into(),1187 }1188 .to_log(T::EvmTokenAddressMapping::token_to_address(1189 collection.id,1190 token,1191 )),1192 );1193 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1194 collection.id,1195 token,1196 owner.clone(),1197 mint_amount,1198 ));1199 } else if total_pieces > amount {1200 let burn_amount = total_pieces - amount;1201 <PalletEvm<T>>::deposit_log(1202 ERC20Events::Transfer {1203 from: *owner.as_eth(),1204 to: H160::default(),1205 value: burn_amount.into(),1206 }1207 .to_log(T::EvmTokenAddressMapping::token_to_address(1208 collection.id,1209 token,1210 )),1211 );1212 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1213 collection.id,1214 token,1215 owner.clone(),1216 burn_amount,1217 ));1218 }12191220 Ok(())1221 }12221223 fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1224 let mut owner = None;1225 let mut count = 0;1226 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1227 count += 1;1228 if count > 1 {1229 return None;1230 }1231 owner = Some(key);1232 }1233 owner1234 }12351236 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1237 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1238 }12391240 pub fn set_collection_properties(1241 collection: &RefungibleHandle<T>,1242 sender: &T::CrossAccountId,1243 properties: Vec<Property>,1244 ) -> DispatchResult {1245 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)1246 }12471248 pub fn delete_collection_properties(1249 collection: &RefungibleHandle<T>,1250 sender: &T::CrossAccountId,1251 property_keys: Vec<PropertyKey>,1252 ) -> DispatchResult {1253 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1254 }12551256 pub fn set_token_property_permissions(1257 collection: &RefungibleHandle<T>,1258 sender: &T::CrossAccountId,1259 property_permissions: Vec<PropertyKeyPermission>,1260 ) -> DispatchResult {1261 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1262 }12631264 /// Returns 10 token in no particular order.1265 ///1266 /// There is no direct way to get token holders in ascending order,1267 /// since `iter_prefix` returns values in no particular order.1268 /// Therefore, getting the 10 largest holders with a large value of holders1269 /// can lead to impact memory allocation + sorting with `n * log (n)`.1270 pub fn token_owners(1271 collection_id: CollectionId,1272 token: TokenId,1273 ) -> Option<Vec<T::CrossAccountId>> {1274 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1275 .map(|(owner, _amount)| owner)1276 .take(10)1277 .collect();12781279 if res.is_empty() {1280 None1281 } else {1282 Some(res)1283 }1284 }1285}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//! of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//! Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//! transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//! an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//! with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//! collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//! some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//! Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;91use crate::erc::ERC721Events;9293use codec::{Encode, Decode, MaxEncodedLen};94use core::ops::Deref;95use evm_coder::ToLog;96use frame_support::{BoundedVec, ensure, fail, storage::with_transaction, transactional};97use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};98use pallet_evm_coder_substrate::WithRecorder;99use pallet_common::{100 CommonCollectionOperations, Error as CommonError, Event as CommonEvent,101 eth::collection_id_to_address, Pallet as PalletCommon,102};103use pallet_structure::Pallet as PalletStructure;104use scale_info::TypeInfo;105use sp_core::H160;106use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};107use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};108use up_data_structs::{109 AccessMode, budget::Budget, CollectionId, CreateCollectionData, CreateRefungibleExData,110 CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId, Property,111 PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,112 TrySetProperty,113};114115pub use pallet::*;116#[cfg(feature = "runtime-benchmarks")]117pub mod benchmarking;118pub mod common;119pub mod erc;120pub mod erc_token;121pub mod weights;122123pub type CreateItemData<T> =124 CreateRefungibleExData<<T as pallet_evm::account::Config>::CrossAccountId>;125pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;126127/// Token data, stored independently from other data used to describe it128/// for the convenience of database access. Notably contains the token metadata.129#[struct_versioning::versioned(version = 2, upper)]130#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]131pub struct ItemData {132 pub const_data: BoundedVec<u8, CustomDataLimit>,133134 #[version(..2)]135 pub variable_data: BoundedVec<u8, CustomDataLimit>,136}137138#[frame_support::pallet]139pub mod pallet {140 use super::*;141 use frame_support::{142 Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,143 traits::StorageVersion,144 };145 use frame_system::pallet_prelude::*;146 use up_data_structs::{CollectionId, TokenId};147 use super::weights::WeightInfo;148149 #[pallet::error]150 pub enum Error<T> {151 /// Not Refungible item data used to mint in Refungible collection.152 NotRefungibleDataUsedToMintFungibleCollectionToken,153 /// Maximum refungibility exceeded.154 WrongRefungiblePieces,155 /// Refungible token can't be repartitioned by user who isn't owns all pieces.156 RepartitionWhileNotOwningAllPieces,157 /// Refungible token can't nest other tokens.158 RefungibleDisallowsNesting,159 /// Setting item properties is not allowed.160 SettingPropertiesNotAllowed,161 }162163 #[pallet::config]164 pub trait Config:165 frame_system::Config + pallet_common::Config + pallet_structure::Config166 {167 type WeightInfo: WeightInfo;168 }169170 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);171172 #[pallet::pallet]173 #[pallet::storage_version(STORAGE_VERSION)]174 #[pallet::generate_store(pub(super) trait Store)]175 pub struct Pallet<T>(_);176177 /// Total amount of minted tokens in a collection.178 #[pallet::storage]179 pub type TokensMinted<T: Config> =180 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;181182 /// Amount of tokens burnt in a collection.183 #[pallet::storage]184 pub type TokensBurnt<T: Config> =185 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;186187 /// Token data, used to partially describe a token.188 #[pallet::storage]189 pub type TokenData<T: Config> = StorageNMap<190 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),191 Value = ItemData,192 QueryKind = ValueQuery,193 >;194195 /// Amount of pieces a refungible token is split into.196 #[pallet::storage]197 #[pallet::getter(fn token_properties)]198 pub type TokenProperties<T: Config> = StorageNMap<199 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),200 Value = up_data_structs::Properties,201 QueryKind = ValueQuery,202 OnEmpty = up_data_structs::TokenProperties,203 >;204205 /// Total amount of pieces for token206 #[pallet::storage]207 pub type TotalSupply<T: Config> = StorageNMap<208 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),209 Value = u128,210 QueryKind = ValueQuery,211 >;212213 /// Used to enumerate tokens owned by account.214 #[pallet::storage]215 pub type Owned<T: Config> = StorageNMap<216 Key = (217 Key<Twox64Concat, CollectionId>,218 Key<Blake2_128Concat, T::CrossAccountId>,219 Key<Twox64Concat, TokenId>,220 ),221 Value = bool,222 QueryKind = ValueQuery,223 >;224225 /// Amount of tokens (not pieces) partially owned by an account within a collection.226 #[pallet::storage]227 pub type AccountBalance<T: Config> = StorageNMap<228 Key = (229 Key<Twox64Concat, CollectionId>,230 // Owner231 Key<Blake2_128Concat, T::CrossAccountId>,232 ),233 Value = u32,234 QueryKind = ValueQuery,235 >;236237 /// Amount of token pieces owned by account.238 #[pallet::storage]239 pub type Balance<T: Config> = StorageNMap<240 Key = (241 Key<Twox64Concat, CollectionId>,242 Key<Twox64Concat, TokenId>,243 // Owner244 Key<Blake2_128Concat, T::CrossAccountId>,245 ),246 Value = u128,247 QueryKind = ValueQuery,248 >;249250 /// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.251 #[pallet::storage]252 pub type Allowance<T: Config> = StorageNMap<253 Key = (254 Key<Twox64Concat, CollectionId>,255 Key<Twox64Concat, TokenId>,256 // Owner257 Key<Blake2_128, T::CrossAccountId>,258 // Spender259 Key<Blake2_128Concat, T::CrossAccountId>,260 ),261 Value = u128,262 QueryKind = ValueQuery,263 >;264265 #[pallet::hooks]266 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {267 fn on_runtime_upgrade() -> Weight {268 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {269 <TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {270 Some(<ItemDataVersion2>::from(v))271 })272 }273274 0275 }276 }277}278279pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);280impl<T: Config> RefungibleHandle<T> {281 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {282 Self(inner)283 }284 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {285 self.0286 }287 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {288 &mut self.0289 }290}291292impl<T: Config> Deref for RefungibleHandle<T> {293 type Target = pallet_common::CollectionHandle<T>;294295 fn deref(&self) -> &Self::Target {296 &self.0297 }298}299300impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {301 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {302 self.0.recorder()303 }304 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {305 self.0.into_recorder()306 }307}308309impl<T: Config> Pallet<T> {310 /// Get number of RFT tokens in collection311 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {312 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)313 }314315 /// Check that RFT token exists316 ///317 /// - `token`: Token ID.318 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {319 <TotalSupply<T>>::contains_key((collection.id, token))320 }321322 pub fn set_scoped_token_property(323 collection_id: CollectionId,324 token_id: TokenId,325 scope: PropertyScope,326 property: Property,327 ) -> DispatchResult {328 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {329 properties.try_scoped_set(scope, property.key, property.value)330 })331 .map_err(<CommonError<T>>::from)?;332333 Ok(())334 }335336 pub fn set_scoped_token_properties(337 collection_id: CollectionId,338 token_id: TokenId,339 scope: PropertyScope,340 properties: impl Iterator<Item = Property>,341 ) -> DispatchResult {342 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {343 stored_properties.try_scoped_set_from_iter(scope, properties)344 })345 .map_err(<CommonError<T>>::from)?;346347 Ok(())348 }349}350351// unchecked calls skips any permission checks352impl<T: Config> Pallet<T> {353 /// Create RFT collection354 ///355 /// `init_collection` will take non-refundable deposit for collection creation.356 ///357 /// - `data`: Contains settings for collection limits and permissions.358 pub fn init_collection(359 owner: T::CrossAccountId,360 data: CreateCollectionData<T::AccountId>,361 ) -> Result<CollectionId, DispatchError> {362 <PalletCommon<T>>::init_collection(owner, data, false)363 }364365 /// Destroy RFT collection366 ///367 /// `destroy_collection` will throw error if collection contains any tokens.368 /// Only owner can destroy collection.369 pub fn destroy_collection(370 collection: RefungibleHandle<T>,371 sender: &T::CrossAccountId,372 ) -> DispatchResult {373 let id = collection.id;374375 if Self::collection_has_tokens(id) {376 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());377 }378379 // =========380381 PalletCommon::destroy_collection(collection.0, sender)?;382383 <TokensMinted<T>>::remove(id);384 <TokensBurnt<T>>::remove(id);385 <TokenData<T>>::remove_prefix((id,), None);386 <TotalSupply<T>>::remove_prefix((id,), None);387 <Balance<T>>::remove_prefix((id,), None);388 <Allowance<T>>::remove_prefix((id,), None);389 <Owned<T>>::remove_prefix((id,), None);390 <AccountBalance<T>>::remove_prefix((id,), None);391 Ok(())392 }393394 fn collection_has_tokens(collection_id: CollectionId) -> bool {395 <TokenData<T>>::iter_prefix((collection_id,))396 .next()397 .is_some()398 }399400 pub fn burn_token_unchecked(401 collection: &RefungibleHandle<T>,402 token_id: TokenId,403 ) -> DispatchResult {404 let burnt = <TokensBurnt<T>>::get(collection.id)405 .checked_add(1)406 .ok_or(ArithmeticError::Overflow)?;407408 <TokensBurnt<T>>::insert(collection.id, burnt);409 <TokenData<T>>::remove((collection.id, token_id));410 <TokenProperties<T>>::remove((collection.id, token_id));411 <TotalSupply<T>>::remove((collection.id, token_id));412 <Balance<T>>::remove_prefix((collection.id, token_id), None);413 <Allowance<T>>::remove_prefix((collection.id, token_id), None);414 // TODO: ERC721 transfer event415 Ok(())416 }417418 /// Burn RFT token pieces419 ///420 /// `burn` will decrease total amount of token pieces and amount owned by sender.421 /// `burn` can be called even if there are multiple owners of the RFT token.422 /// If sender wouldn't have any pieces left after `burn` than she will stop being423 /// one of the owners of the token. If there is no account that owns any pieces of424 /// the token than token will be burned too.425 ///426 /// - `amount`: Amount of token pieces to burn.427 /// - `token`: Token who's pieces should be burned428 /// - `collection`: Collection that contains the token429 pub fn burn(430 collection: &RefungibleHandle<T>,431 owner: &T::CrossAccountId,432 token: TokenId,433 amount: u128,434 ) -> DispatchResult {435 let total_supply = <TotalSupply<T>>::get((collection.id, token))436 .checked_sub(amount)437 .ok_or(<CommonError<T>>::TokenValueTooLow)?;438439 // This was probally last owner of this token?440 if total_supply == 0 {441 // Ensure user actually owns this amount442 ensure!(443 <Balance<T>>::get((collection.id, token, owner)) == amount,444 <CommonError<T>>::TokenValueTooLow445 );446 let account_balance = <AccountBalance<T>>::get((collection.id, owner))447 .checked_sub(1)448 // Should not occur449 .ok_or(ArithmeticError::Underflow)?;450451 // =========452453 <Owned<T>>::remove((collection.id, owner, token));454 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);455 <AccountBalance<T>>::insert((collection.id, owner), account_balance);456 Self::burn_token_unchecked(collection, token)?;457 <PalletEvm<T>>::deposit_log(458 ERC721Events::Transfer {459 from: *owner.as_eth(),460 to: H160::default(),461 token_id: token.into(),462 }463 .to_log(collection_id_to_address(collection.id)),464 );465 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(466 collection.id,467 token,468 owner.clone(),469 amount,470 ));471 return Ok(());472 }473474 let balance = <Balance<T>>::get((collection.id, token, owner))475 .checked_sub(amount)476 .ok_or(<CommonError<T>>::TokenValueTooLow)?;477 let account_balance = if balance == 0 {478 <AccountBalance<T>>::get((collection.id, owner))479 .checked_sub(1)480 // Should not occur481 .ok_or(ArithmeticError::Underflow)?482 } else {483 0484 };485486 // =========487488 if balance == 0 {489 <Owned<T>>::remove((collection.id, owner, token));490 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);491 <Balance<T>>::remove((collection.id, token, owner));492 <AccountBalance<T>>::insert((collection.id, owner), account_balance);493 } else {494 <Balance<T>>::insert((collection.id, token, owner), balance);495 }496 <TotalSupply<T>>::insert((collection.id, token), total_supply);497498 <PalletEvm<T>>::deposit_log(499 ERC20Events::Transfer {500 from: *owner.as_eth(),501 to: H160::default(),502 value: amount.into(),503 }504 .to_log(T::EvmTokenAddressMapping::token_to_address(505 collection.id,506 token,507 )),508 );509 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(510 collection.id,511 token,512 owner.clone(),513 amount,514 ));515 Ok(())516 }517518 #[transactional]519 fn modify_token_properties(520 collection: &RefungibleHandle<T>,521 sender: &T::CrossAccountId,522 token_id: TokenId,523 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,524 is_token_create: bool,525 nesting_budget: &dyn Budget,526 ) -> DispatchResult {527 let is_collection_admin = || collection.is_owner_or_admin(sender);528 let is_token_owner = || -> Result<bool, DispatchError> {529 let balance = collection.balance(sender.clone(), token_id);530 let total_pieces: u128 =531 Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);532 if balance != total_pieces {533 return Ok(false);534 }535536 let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(537 sender.clone(),538 collection.id,539 token_id,540 None,541 nesting_budget,542 )?;543544 Ok(is_bundle_owner)545 };546547 for (key, value) in properties {548 let permission = <PalletCommon<T>>::property_permissions(collection.id)549 .get(&key)550 .cloned()551 .unwrap_or_else(PropertyPermission::none);552553 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))554 .get(&key)555 .is_some();556557 match permission {558 PropertyPermission { mutable: false, .. } if is_property_exists => {559 return Err(<CommonError<T>>::NoPermission.into());560 }561562 PropertyPermission {563 collection_admin,564 token_owner,565 ..566 } => {567 //TODO: investigate threats during public minting.568 let is_token_create =569 is_token_create && (collection_admin || token_owner) && value.is_some();570 if !(is_token_create571 || (collection_admin && is_collection_admin())572 || (token_owner && is_token_owner()?))573 {574 fail!(<CommonError<T>>::NoPermission);575 }576 }577 }578579 match value {580 Some(value) => {581 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {582 properties.try_set(key.clone(), value)583 })584 .map_err(<CommonError<T>>::from)?;585586 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(587 collection.id,588 token_id,589 key,590 ));591 }592 None => {593 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {594 properties.remove(&key)595 })596 .map_err(<CommonError<T>>::from)?;597598 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(599 collection.id,600 token_id,601 key,602 ));603 }604 }605 }606607 Ok(())608 }609610 pub fn set_token_properties(611 collection: &RefungibleHandle<T>,612 sender: &T::CrossAccountId,613 token_id: TokenId,614 properties: impl Iterator<Item = Property>,615 is_token_create: bool,616 nesting_budget: &dyn Budget,617 ) -> DispatchResult {618 Self::modify_token_properties(619 collection,620 sender,621 token_id,622 properties.map(|p| (p.key, Some(p.value))),623 is_token_create,624 nesting_budget,625 )626 }627628 pub fn set_token_property(629 collection: &RefungibleHandle<T>,630 sender: &T::CrossAccountId,631 token_id: TokenId,632 property: Property,633 nesting_budget: &dyn Budget,634 ) -> DispatchResult {635 let is_token_create = false;636637 Self::set_token_properties(638 collection,639 sender,640 token_id,641 [property].into_iter(),642 is_token_create,643 nesting_budget,644 )645 }646647 pub fn delete_token_properties(648 collection: &RefungibleHandle<T>,649 sender: &T::CrossAccountId,650 token_id: TokenId,651 property_keys: impl Iterator<Item = PropertyKey>,652 nesting_budget: &dyn Budget,653 ) -> DispatchResult {654 let is_token_create = false;655656 Self::modify_token_properties(657 collection,658 sender,659 token_id,660 property_keys.into_iter().map(|key| (key, None)),661 is_token_create,662 nesting_budget,663 )664 }665666 pub fn delete_token_property(667 collection: &RefungibleHandle<T>,668 sender: &T::CrossAccountId,669 token_id: TokenId,670 property_key: PropertyKey,671 nesting_budget: &dyn Budget,672 ) -> DispatchResult {673 Self::delete_token_properties(674 collection,675 sender,676 token_id,677 [property_key].into_iter(),678 nesting_budget,679 )680 }681682 /// Transfer RFT token pieces from one account to another.683 ///684 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.685 ///686 /// - `from`: Owner of token pieces to transfer.687 /// - `to`: Recepient of transfered token pieces.688 /// - `amount`: Amount of token pieces to transfer.689 /// - `token`: Token whos pieces should be transfered690 /// - `collection`: Collection that contains the token691 pub fn transfer(692 collection: &RefungibleHandle<T>,693 from: &T::CrossAccountId,694 to: &T::CrossAccountId,695 token: TokenId,696 amount: u128,697 nesting_budget: &dyn Budget,698 ) -> DispatchResult {699 ensure!(700 collection.limits.transfers_enabled(),701 <CommonError<T>>::TransferNotAllowed702 );703704 if collection.permissions.access() == AccessMode::AllowList {705 collection.check_allowlist(from)?;706 collection.check_allowlist(to)?;707 }708 <PalletCommon<T>>::ensure_correct_receiver(to)?;709710 let initial_balance_from = <Balance<T>>::get((collection.id, token, from));711 let updated_balance_from = initial_balance_from712 .checked_sub(amount)713 .ok_or(<CommonError<T>>::TokenValueTooLow)?;714 let mut create_target = false;715 let from_to_differ = from != to;716 let updated_balance_to = if from != to {717 let old_balance = <Balance<T>>::get((collection.id, token, to));718 if old_balance == 0 {719 create_target = true;720 }721 Some(722 old_balance723 .checked_add(amount)724 .ok_or(ArithmeticError::Overflow)?,725 )726 } else {727 None728 };729730 let account_balance_from = if updated_balance_from == 0 {731 Some(732 <AccountBalance<T>>::get((collection.id, from))733 .checked_sub(1)734 // Should not occur735 .ok_or(ArithmeticError::Underflow)?,736 )737 } else {738 None739 };740 // Account data is created in token, AccountBalance should be increased741 // But only if from != to as we shouldn't check overflow in this case742 let account_balance_to = if create_target && from_to_differ {743 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))744 .checked_add(1)745 .ok_or(ArithmeticError::Overflow)?;746 ensure!(747 account_balance_to < collection.limits.account_token_ownership_limit(),748 <CommonError<T>>::AccountTokenLimitExceeded,749 );750751 Some(account_balance_to)752 } else {753 None754 };755756 // =========757758 <PalletStructure<T>>::nest_if_sent_to_token(759 from.clone(),760 to,761 collection.id,762 token,763 nesting_budget,764 )?;765766 if let Some(updated_balance_to) = updated_balance_to {767 // from != to768 if updated_balance_from == 0 {769 <Balance<T>>::remove((collection.id, token, from));770 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);771 } else {772 <Balance<T>>::insert((collection.id, token, from), updated_balance_from);773 }774 <Balance<T>>::insert((collection.id, token, to), updated_balance_to);775 if let Some(account_balance_from) = account_balance_from {776 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);777 <Owned<T>>::remove((collection.id, from, token));778 }779 if let Some(account_balance_to) = account_balance_to {780 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);781 <Owned<T>>::insert((collection.id, to, token), true);782 }783 }784785 <PalletEvm<T>>::deposit_log(786 ERC20Events::Transfer {787 from: *from.as_eth(),788 to: *to.as_eth(),789 value: amount.into(),790 }791 .to_log(T::EvmTokenAddressMapping::token_to_address(792 collection.id,793 token,794 )),795 );796797 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(798 collection.id,799 token,800 from.clone(),801 to.clone(),802 amount,803 ));804805 let total_supply = <TotalSupply<T>>::get((collection.id, token));806807 if amount == total_supply {808 // if token was fully owned by `from` and will be fully owned by `to` after transfer809 <PalletEvm<T>>::deposit_log(810 ERC721Events::Transfer {811 from: *from.as_eth(),812 to: *to.as_eth(),813 token_id: token.into(),814 }815 .to_log(collection_id_to_address(collection.id)),816 );817 } else if let Some(updated_balance_to) = updated_balance_to {818 // if `from` not equals `to`. This condition is needed to avoid sending event819 // when `from` fully owns token and sends part of token pieces to itself.820 if initial_balance_from == total_supply {821 // if token was fully owned by `from` and will be only partially owned by `to`822 // and `from` after transfer823 <PalletEvm<T>>::deposit_log(824 ERC721Events::Transfer {825 from: *from.as_eth(),826 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,827 token_id: token.into(),828 }829 .to_log(collection_id_to_address(collection.id)),830 );831 } else if updated_balance_to == total_supply {832 // if token was partially owned by `from` and will be fully owned by `to` after transfer833 <PalletEvm<T>>::deposit_log(834 ERC721Events::Transfer {835 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,836 to: *to.as_eth(),837 token_id: token.into(),838 }839 .to_log(collection_id_to_address(collection.id)),840 );841 }842 }843844 Ok(())845 }846847 /// Batched operation to create multiple RFT tokens.848 ///849 /// Same as `create_item` but creates multiple tokens.850 ///851 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.852 pub fn create_multiple_items(853 collection: &RefungibleHandle<T>,854 sender: &T::CrossAccountId,855 data: Vec<CreateItemData<T>>,856 nesting_budget: &dyn Budget,857 ) -> DispatchResult {858 if !collection.is_owner_or_admin(sender) {859 ensure!(860 collection.permissions.mint_mode(),861 <CommonError<T>>::PublicMintingNotAllowed862 );863 collection.check_allowlist(sender)?;864865 for item in data.iter() {866 for user in item.users.keys() {867 collection.check_allowlist(user)?;868 }869 }870 }871872 for item in data.iter() {873 for (owner, _) in item.users.iter() {874 <PalletCommon<T>>::ensure_correct_receiver(owner)?;875 }876 }877878 // Total pieces per tokens879 let totals = data880 .iter()881 .map(|data| {882 Ok(data883 .users884 .iter()885 .map(|u| u.1)886 .try_fold(0u128, |acc, v| acc.checked_add(*v))887 .ok_or(ArithmeticError::Overflow)?)888 })889 .collect::<Result<Vec<_>, DispatchError>>()?;890 for total in &totals {891 ensure!(892 *total <= MAX_REFUNGIBLE_PIECES,893 <Error<T>>::WrongRefungiblePieces894 );895 }896897 let first_token_id = <TokensMinted<T>>::get(collection.id);898 let tokens_minted = first_token_id899 .checked_add(data.len() as u32)900 .ok_or(ArithmeticError::Overflow)?;901 ensure!(902 tokens_minted < collection.limits.token_limit(),903 <CommonError<T>>::CollectionTokenLimitExceeded904 );905906 let mut balances = BTreeMap::new();907 for data in &data {908 for owner in data.users.keys() {909 let balance = balances910 .entry(owner)911 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));912 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;913914 ensure!(915 *balance <= collection.limits.account_token_ownership_limit(),916 <CommonError<T>>::AccountTokenLimitExceeded,917 );918 }919 }920921 for (i, token) in data.iter().enumerate() {922 let token_id = TokenId(first_token_id + i as u32 + 1);923 for (to, _) in token.users.iter() {924 <PalletStructure<T>>::check_nesting(925 sender.clone(),926 to,927 collection.id,928 token_id,929 nesting_budget,930 )?;931 }932 }933934 // =========935936 with_transaction(|| {937 for (i, data) in data.iter().enumerate() {938 let token_id = first_token_id + i as u32 + 1;939 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);940941 <TokenData<T>>::insert(942 (collection.id, token_id),943 ItemData {944 const_data: data.const_data.clone(),945 },946 );947948 for (user, amount) in data.users.iter() {949 if *amount == 0 {950 continue;951 }952 <Balance<T>>::insert((collection.id, token_id, &user), amount);953 <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);954 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(955 user,956 collection.id,957 TokenId(token_id),958 );959 }960961 if let Err(e) = Self::set_token_properties(962 collection,963 sender,964 TokenId(token_id),965 data.properties.clone().into_iter(),966 true,967 nesting_budget,968 ) {969 return TransactionOutcome::Rollback(Err(e));970 }971 }972 TransactionOutcome::Commit(Ok(()))973 })?;974975 <TokensMinted<T>>::insert(collection.id, tokens_minted);976977 for (account, balance) in balances {978 <AccountBalance<T>>::insert((collection.id, account), balance);979 }980981 for (i, token) in data.into_iter().enumerate() {982 let token_id = first_token_id + i as u32 + 1;983984 for (user, amount) in token.users.into_iter() {985 if amount == 0 {986 continue;987 }988989 <PalletEvm<T>>::deposit_log(990 ERC20Events::Transfer {991 from: H160::default(),992 to: *user.as_eth(),993 value: amount.into(),994 }995 .to_log(T::EvmTokenAddressMapping::token_to_address(996 collection.id,997 TokenId(token_id),998 )),999 );1000 <PalletEvm<T>>::deposit_log(1001 ERC721Events::Transfer {1002 from: H160::default(),1003 to: *user.as_eth(),1004 token_id: token_id.into(),1005 }1006 .to_log(collection_id_to_address(collection.id)),1007 );1008 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1009 collection.id,1010 TokenId(token_id),1011 user,1012 amount,1013 ));1014 }1015 }1016 Ok(())1017 }10181019 pub fn set_allowance_unchecked(1020 collection: &RefungibleHandle<T>,1021 sender: &T::CrossAccountId,1022 spender: &T::CrossAccountId,1023 token: TokenId,1024 amount: u128,1025 ) {1026 if amount == 0 {1027 <Allowance<T>>::remove((collection.id, token, sender, spender));1028 } else {1029 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);1030 }10311032 <PalletEvm<T>>::deposit_log(1033 ERC20Events::Approval {1034 owner: *sender.as_eth(),1035 spender: *spender.as_eth(),1036 value: amount.into(),1037 }1038 .to_log(T::EvmTokenAddressMapping::token_to_address(1039 collection.id,1040 token,1041 )),1042 );1043 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1044 collection.id,1045 token,1046 sender.clone(),1047 spender.clone(),1048 amount,1049 ))1050 }10511052 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1053 ///1054 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1055 pub fn set_allowance(1056 collection: &RefungibleHandle<T>,1057 sender: &T::CrossAccountId,1058 spender: &T::CrossAccountId,1059 token: TokenId,1060 amount: u128,1061 ) -> DispatchResult {1062 if collection.permissions.access() == AccessMode::AllowList {1063 collection.check_allowlist(sender)?;1064 collection.check_allowlist(spender)?;1065 }10661067 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10681069 if <Balance<T>>::get((collection.id, token, sender)) < amount {1070 ensure!(1071 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1072 <CommonError<T>>::CantApproveMoreThanOwned1073 );1074 }10751076 // =========10771078 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1079 Ok(())1080 }10811082 /// Returns allowance, which should be set after transaction1083 fn check_allowed(1084 collection: &RefungibleHandle<T>,1085 spender: &T::CrossAccountId,1086 from: &T::CrossAccountId,1087 token: TokenId,1088 amount: u128,1089 nesting_budget: &dyn Budget,1090 ) -> Result<Option<u128>, DispatchError> {1091 if spender.conv_eq(from) {1092 return Ok(None);1093 }1094 if collection.permissions.access() == AccessMode::AllowList {1095 // `from`, `to` checked in [`transfer`]1096 collection.check_allowlist(spender)?;1097 }1098 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1099 // TODO: should collection owner be allowed to perform this transfer?1100 ensure!(1101 <PalletStructure<T>>::check_indirectly_owned(1102 spender.clone(),1103 source.0,1104 source.1,1105 None,1106 nesting_budget1107 )?,1108 <CommonError<T>>::ApprovedValueTooLow,1109 );1110 return Ok(None);1111 }1112 let allowance =1113 <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1114 if allowance.is_none() {1115 ensure!(1116 collection.ignores_allowance(spender),1117 <CommonError<T>>::ApprovedValueTooLow1118 );1119 }1120 Ok(allowance)1121 }11221123 /// Transfer RFT token pieces from one account to another.1124 ///1125 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1126 /// The owner should set allowance for the spender to transfer pieces.1127 ///1128 /// [`transfer`]: struct.Pallet.html#method.transfer1129 pub fn transfer_from(1130 collection: &RefungibleHandle<T>,1131 spender: &T::CrossAccountId,1132 from: &T::CrossAccountId,1133 to: &T::CrossAccountId,1134 token: TokenId,1135 amount: u128,1136 nesting_budget: &dyn Budget,1137 ) -> DispatchResult {1138 let allowance =1139 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11401141 // =========11421143 Self::transfer(collection, from, to, token, amount, nesting_budget)?;1144 if let Some(allowance) = allowance {1145 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1146 }1147 Ok(())1148 }11491150 /// Burn RFT token pieces from the account.1151 ///1152 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1153 /// set allowance for the spender to burn pieces1154 ///1155 /// [`burn`]: struct.Pallet.html#method.burn1156 pub fn burn_from(1157 collection: &RefungibleHandle<T>,1158 spender: &T::CrossAccountId,1159 from: &T::CrossAccountId,1160 token: TokenId,1161 amount: u128,1162 nesting_budget: &dyn Budget,1163 ) -> DispatchResult {1164 let allowance =1165 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11661167 // =========11681169 Self::burn(collection, from, token, amount)?;1170 if let Some(allowance) = allowance {1171 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1172 }1173 Ok(())1174 }11751176 /// Create RFT token.1177 ///1178 /// The sender should be the owner/admin of the collection or collection should be configured1179 /// to allow public minting.1180 ///1181 /// - `data`: Contains list of users who will become the owners of the token pieces and amount1182 /// of token pieces they will receive.1183 pub fn create_item(1184 collection: &RefungibleHandle<T>,1185 sender: &T::CrossAccountId,1186 data: CreateItemData<T>,1187 nesting_budget: &dyn Budget,1188 ) -> DispatchResult {1189 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1190 }11911192 /// Repartition RFT token.1193 ///1194 /// `repartition` will set token balance of the sender and total amount of token pieces.1195 /// Sender should own all of the token pieces. `repartition' could be done even if some1196 /// token pieces were burned before.1197 ///1198 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.1199 pub fn repartition(1200 collection: &RefungibleHandle<T>,1201 owner: &T::CrossAccountId,1202 token: TokenId,1203 amount: u128,1204 ) -> DispatchResult {1205 ensure!(1206 amount <= MAX_REFUNGIBLE_PIECES,1207 <Error<T>>::WrongRefungiblePieces1208 );1209 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1210 // Ensure user owns all pieces1211 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1212 let balance = <Balance<T>>::get((collection.id, token, owner));1213 ensure!(1214 total_pieces == balance,1215 <Error<T>>::RepartitionWhileNotOwningAllPieces1216 );12171218 <Balance<T>>::insert((collection.id, token, owner), amount);1219 <TotalSupply<T>>::insert((collection.id, token), amount);12201221 if amount > total_pieces {1222 let mint_amount = amount - total_pieces;1223 <PalletEvm<T>>::deposit_log(1224 ERC20Events::Transfer {1225 from: H160::default(),1226 to: *owner.as_eth(),1227 value: mint_amount.into(),1228 }1229 .to_log(T::EvmTokenAddressMapping::token_to_address(1230 collection.id,1231 token,1232 )),1233 );1234 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1235 collection.id,1236 token,1237 owner.clone(),1238 mint_amount,1239 ));1240 } else if total_pieces > amount {1241 let burn_amount = total_pieces - amount;1242 <PalletEvm<T>>::deposit_log(1243 ERC20Events::Transfer {1244 from: *owner.as_eth(),1245 to: H160::default(),1246 value: burn_amount.into(),1247 }1248 .to_log(T::EvmTokenAddressMapping::token_to_address(1249 collection.id,1250 token,1251 )),1252 );1253 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1254 collection.id,1255 token,1256 owner.clone(),1257 burn_amount,1258 ));1259 }12601261 Ok(())1262 }12631264 fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1265 let mut owner = None;1266 let mut count = 0;1267 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1268 count += 1;1269 if count > 1 {1270 return None;1271 }1272 owner = Some(key);1273 }1274 owner1275 }12761277 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1278 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1279 }12801281 pub fn set_collection_properties(1282 collection: &RefungibleHandle<T>,1283 sender: &T::CrossAccountId,1284 properties: Vec<Property>,1285 ) -> DispatchResult {1286 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)1287 }12881289 pub fn delete_collection_properties(1290 collection: &RefungibleHandle<T>,1291 sender: &T::CrossAccountId,1292 property_keys: Vec<PropertyKey>,1293 ) -> DispatchResult {1294 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1295 }12961297 pub fn set_token_property_permissions(1298 collection: &RefungibleHandle<T>,1299 sender: &T::CrossAccountId,1300 property_permissions: Vec<PropertyKeyPermission>,1301 ) -> DispatchResult {1302 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1303 }13041305 /// Returns 10 token in no particular order.1306 ///1307 /// There is no direct way to get token holders in ascending order,1308 /// since `iter_prefix` returns values in no particular order.1309 /// Therefore, getting the 10 largest holders with a large value of holders1310 /// can lead to impact memory allocation + sorting with `n * log (n)`.1311 pub fn token_owners(1312 collection_id: CollectionId,1313 token: TokenId,1314 ) -> Option<Vec<T::CrossAccountId>> {1315 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1316 .map(|(owner, _amount)| owner)1317 .take(10)1318 .collect();13191320 if res.is_empty() {1321 None1322 } else {1323 Some(res)1324 }1325 }1326}tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import {createCollectionExpectSuccess, UNIQUE} from '../util/helpers';
+import {createCollectionExpectSuccess, transfer, UNIQUE} from '../util/helpers';
import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, tokenIdToAddress} from './util/helpers';
import reFungibleAbi from './reFungibleAbi.json';
import reFungibleTokenAbi from './reFungibleTokenAbi.json';
@@ -96,6 +96,28 @@
expect(owner).to.equal(receiver);
});
+
+ itWeb3('ownerOf for partial ownership', async ({api, web3, privateKeyWrapper}) => {
+ const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ const receiver = createEthAccount(web3);
+ const helper = evmCollectionHelpers(web3, caller);
+ const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();
+ const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+ const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+
+ const tokenId = await contract.methods.nextTokenId().call();
+ await contract.methods.mint(caller, tokenId).send();
+
+ const tokenAddress = tokenIdToAddress(collectionId, tokenId);
+ const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+
+ await tokenContract.methods.repartition(2).send();
+ await tokenContract.methods.transfer(receiver, 1).send();
+
+ const owner = await contract.methods.ownerOf(tokenId).call();
+
+ expect(owner).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');
+ });
});
describe('Refungible: Plain calls', () => {
@@ -293,6 +315,74 @@
expect(+balance).to.equal(1);
}
});
+
+ itWeb3('transfer event on transfer from partial ownership to full ownership', async ({api, web3, privateKeyWrapper}) => {
+ const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ const receiver = createEthAccount(web3);
+ const helper = evmCollectionHelpers(web3, caller);
+ const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();
+ const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+ const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+
+ const tokenId = await contract.methods.nextTokenId().call();
+ await contract.methods.mint(caller, tokenId).send();
+
+ const tokenAddress = tokenIdToAddress(collectionId, tokenId);
+ const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+
+ await tokenContract.methods.repartition(2).send();
+ await tokenContract.methods.transfer(receiver, 1).send();
+
+ let transfer;
+ contract.events.Transfer({}, function(_error: any, event: any){ transfer = event;});
+ await tokenContract.methods.transfer(receiver, 1).send();
+ const events = normalizeEvents([transfer]);
+ expect(events).to.deep.equal([
+ {
+ address: collectionIdAddress,
+ event: 'Transfer',
+ args: {
+ from: '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF',
+ to: receiver,
+ tokenId: tokenId.toString(),
+ },
+ },
+ ]);
+ });
+
+ itWeb3('transfer event on transfer from full ownership to partial ownership', async ({api, web3, privateKeyWrapper}) => {
+ const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+ const receiver = createEthAccount(web3);
+ const helper = evmCollectionHelpers(web3, caller);
+ const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();
+ const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+ const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+
+ const tokenId = await contract.methods.nextTokenId().call();
+ await contract.methods.mint(caller, tokenId).send();
+
+ const tokenAddress = tokenIdToAddress(collectionId, tokenId);
+ const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+
+ await tokenContract.methods.repartition(2).send();
+
+ let transfer;
+ contract.events.Transfer({}, function(_error: any, event: any){ transfer = event;});
+ await tokenContract.methods.transfer(receiver, 1).send();
+
+ const events = normalizeEvents([transfer]);
+ expect(events).to.deep.equal([
+ {
+ address: collectionIdAddress,
+ event: 'Transfer',
+ args: {
+ from: caller,
+ to: '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF',
+ tokenId: tokenId.toString(),
+ },
+ },
+ ]);
+ });
});
describe('RFT: Fees', () => {