difftreelog
fix restore foreign flag, minor fixes
in: master
11 files changed
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -121,7 +121,7 @@
owner,
CollectionMode::NFT,
|owner: T::CrossAccountId, data| {
- <Pallet<T>>::init_collection(owner.clone(), Some(owner), data)
+ <Pallet<T>>::init_collection(owner.clone(), Some(owner), false, data)
},
|h| h,
)
pallets/common/src/dispatch.rsdiffbeforeafterboth--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -78,6 +78,21 @@
sender: T::CrossAccountId,
payer: Option<T::CrossAccountId>,
data: CreateCollectionData<T::CrossAccountId>,
+ ) -> Result<CollectionId, DispatchError> {
+ Self::create_internal(sender, payer, false, data)
+ }
+
+ /// Create a collection. The collection will be created according to the value of [`data.mode`](CreateCollectionData::mode).
+ ///
+ /// * `sender` - The user who will become the owner of the collection.
+ /// * `payer` - If set, the user who pays the collection creation deposit.
+ /// * `data` - Description of the created collection.
+ /// * `is_special_collection` -- Whether this collection is a system one, i.e. can have special flags set.
+ fn create_internal(
+ sender: T::CrossAccountId,
+ payer: Option<T::CrossAccountId>,
+ is_special_collection: bool,
+ data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError>;
/// Delete the collection.
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1088,6 +1088,7 @@
read_only: flags.external,
flags: RpcCollectionFlags {
+ foreign: flags.foreign,
erc721metadata: flags.erc721metadata,
},
})
@@ -1129,12 +1130,16 @@
/// * `owner` - The owner of the collection.
/// * `payer` - If set, the user that will pay a deposit for the collection creation.
/// * `data` - Description of the created collection.
+ /// * `is_special_collection` -- Whether this collection is a special one, i.e. can have special flags set.
pub fn init_collection(
owner: T::CrossAccountId,
payer: Option<T::CrossAccountId>,
+ is_special_collection: bool,
data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError> {
- ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);
+ if !is_special_collection {
+ ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);
+ }
// Take a (non-refundable) deposit of collection creation
if let Some(payer) = payer {
pallets/foreign-assets/src/lib.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -153,9 +153,11 @@
.expect("description length < max description length; qed");
let payer = None;
- let collection_id = T::CollectionDispatch::create(
+ let is_special_collection = true;
+ let collection_id = T::CollectionDispatch::create_internal(
foreign_collection_owner,
payer,
+ is_special_collection,
CreateCollectionData {
name,
description,
pallets/fungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -31,7 +31,7 @@
owner,
CollectionMode::Fungible(0),
|owner: T::CrossAccountId, data| {
- <PalletCommon<T>>::init_collection(owner.clone(), Some(owner), data)
+ <PalletCommon<T>>::init_collection(owner.clone(), Some(owner), false, data)
},
FungibleHandle::cast,
)
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -58,7 +58,7 @@
owner,
CollectionMode::NFT,
|owner: T::CrossAccountId, data| {
- <PalletCommon<T>>::init_collection(owner.clone(), Some(owner), data)
+ <PalletCommon<T>>::init_collection(owner.clone(), Some(owner), false, data)
},
NonfungibleHandle::cast,
)
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -20,6 +20,7 @@
use pallet_common::{
bench_init,
benchmarking::{create_collection_raw, property_key, property_value},
+ Pallet as PalletCommon,
};
use sp_std::prelude::*;
use up_data_structs::{
@@ -61,7 +62,9 @@
create_collection_raw(
owner,
CollectionMode::ReFungible,
- |owner: T::CrossAccountId, data| <Pallet<T>>::init_collection(owner.clone(), owner, data),
+ |owner: T::CrossAccountId, data| {
+ <PalletCommon<T>>::init_collection(owner.clone(), Some(owner), false, data)
+ },
RefungibleHandle::cast,
)
}
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 core::{cmp::Ordering, ops::Deref};9192use evm_coder::ToLog;93use frame_support::{ensure, storage::with_transaction, transactional};94pub use pallet::*;95use pallet_common::{96 eth::collection_id_to_address, Error as CommonError, Event as CommonEvent,97 Pallet as PalletCommon,98};99use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};100use pallet_evm_coder_substrate::WithRecorder;101use pallet_structure::Pallet as PalletStructure;102use sp_core::{Get, H160};103use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};104use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};105use up_data_structs::{106 budget::Budget, mapping::TokenAddressMapping, AccessMode, CollectionId, CreateCollectionData,107 CreateRefungibleExMultipleOwners, PropertiesPermissionMap, Property, PropertyKey,108 PropertyKeyPermission, PropertyScope, PropertyValue, TokenId, TokenOwnerError,109 TokenProperties as TokenPropertiesT, MAX_REFUNGIBLE_PIECES,110};111112use crate::{erc::ERC721Events, erc_token::ERC20Events};113#[cfg(feature = "runtime-benchmarks")]114pub mod benchmarking;115pub mod common;116pub mod erc;117pub mod erc_token;118pub mod weights;119120pub type CreateItemData<T> =121 CreateRefungibleExMultipleOwners<<T as pallet_evm::Config>::CrossAccountId>;122pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;123124#[frame_support::pallet]125pub mod pallet {126 use frame_support::{127 pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128, Blake2_128Concat,128 Twox64Concat,129 };130 use up_data_structs::{CollectionId, TokenId};131132 use super::{weights::WeightInfo, *};133134 #[pallet::error]135 pub enum Error<T> {136 /// Not Refungible item data used to mint in Refungible collection.137 NotRefungibleDataUsedToMintFungibleCollectionToken,138 /// Maximum refungibility exceeded.139 WrongRefungiblePieces,140 /// Refungible token can't be repartitioned by user who isn't owns all pieces.141 RepartitionWhileNotOwningAllPieces,142 /// Refungible token can't nest other tokens.143 RefungibleDisallowsNesting,144 /// Setting item properties is not allowed.145 SettingPropertiesNotAllowed,146 }147148 #[pallet::config]149 pub trait Config:150 frame_system::Config + pallet_common::Config + pallet_structure::Config151 {152 type WeightInfo: WeightInfo;153 }154155 const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);156157 #[pallet::pallet]158 #[pallet::storage_version(STORAGE_VERSION)]159 pub struct Pallet<T>(_);160161 /// Total amount of minted tokens in a collection.162 #[pallet::storage]163 pub type TokensMinted<T: Config> =164 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;165166 /// Amount of tokens burnt in a collection.167 #[pallet::storage]168 pub type TokensBurnt<T: Config> =169 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;170171 /// Amount of pieces a refungible token is split into.172 #[pallet::storage]173 #[pallet::getter(fn token_properties)]174 pub type TokenProperties<T: Config> = StorageNMap<175 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),176 Value = TokenPropertiesT,177 QueryKind = OptionQuery,178 >;179180 /// Total amount of pieces for token181 #[pallet::storage]182 pub type TotalSupply<T: Config> = StorageNMap<183 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),184 Value = u128,185 QueryKind = ValueQuery,186 >;187188 /// Used to enumerate tokens owned by account.189 #[pallet::storage]190 pub type Owned<T: Config> = StorageNMap<191 Key = (192 Key<Twox64Concat, CollectionId>,193 Key<Blake2_128Concat, T::CrossAccountId>,194 Key<Twox64Concat, TokenId>,195 ),196 Value = bool,197 QueryKind = ValueQuery,198 >;199200 /// Amount of tokens (not pieces) partially owned by an account within a collection.201 #[pallet::storage]202 pub type AccountBalance<T: Config> = StorageNMap<203 Key = (204 Key<Twox64Concat, CollectionId>,205 // Owner206 Key<Blake2_128Concat, T::CrossAccountId>,207 ),208 Value = u32,209 QueryKind = ValueQuery,210 >;211212 /// Amount of token pieces owned by account.213 #[pallet::storage]214 pub type Balance<T: Config> = StorageNMap<215 Key = (216 Key<Twox64Concat, CollectionId>,217 Key<Twox64Concat, TokenId>,218 // Owner219 Key<Blake2_128Concat, T::CrossAccountId>,220 ),221 Value = u128,222 QueryKind = ValueQuery,223 >;224225 /// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.226 #[pallet::storage]227 pub type Allowance<T: Config> = StorageNMap<228 Key = (229 Key<Twox64Concat, CollectionId>,230 Key<Twox64Concat, TokenId>,231 // Owner232 Key<Blake2_128, T::CrossAccountId>,233 // Spender234 Key<Blake2_128Concat, T::CrossAccountId>,235 ),236 Value = u128,237 QueryKind = ValueQuery,238 >;239240 /// Spender set by a wallet owner that could perform certain transactions on all tokens in the wallet.241 #[pallet::storage]242 pub type CollectionAllowance<T: Config> = StorageNMap<243 Key = (244 Key<Twox64Concat, CollectionId>,245 Key<Blake2_128Concat, T::CrossAccountId>, // Owner246 Key<Blake2_128Concat, T::CrossAccountId>, // Spender247 ),248 Value = bool,249 QueryKind = ValueQuery,250 >;251}252253pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);254impl<T: Config> RefungibleHandle<T> {255 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {256 Self(inner)257 }258 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {259 self.0260 }261 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {262 &mut self.0263 }264}265266impl<T: Config> Deref for RefungibleHandle<T> {267 type Target = pallet_common::CollectionHandle<T>;268269 fn deref(&self) -> &Self::Target {270 &self.0271 }272}273274impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {275 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {276 self.0.recorder()277 }278 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {279 self.0.into_recorder()280 }281}282283impl<T: Config> Pallet<T> {284 /// Get number of RFT tokens in collection285 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {286 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)287 }288289 /// Check that RFT token exists290 ///291 /// - `token`: Token ID.292 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {293 <TotalSupply<T>>::contains_key((collection.id, token))294 }295}296297// unchecked calls skips any permission checks298impl<T: Config> Pallet<T> {299 /// Create RFT collection300 ///301 /// `init_collection` will take non-refundable deposit for collection creation.302 ///303 /// - `data`: Contains settings for collection limits and permissions.304 pub fn init_collection(305 owner: T::CrossAccountId,306 payer: T::CrossAccountId,307 data: CreateCollectionData<T::CrossAccountId>,308 ) -> Result<CollectionId, DispatchError> {309 <PalletCommon<T>>::init_collection(owner, Some(payer), data)310 }311312 /// Destroy RFT collection313 ///314 /// `destroy_collection` will throw error if collection contains any tokens.315 /// Only owner can destroy collection.316 pub fn destroy_collection(317 collection: RefungibleHandle<T>,318 sender: &T::CrossAccountId,319 ) -> DispatchResult {320 let id = collection.id;321322 if Self::collection_has_tokens(id) {323 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());324 }325326 // =========327328 PalletCommon::destroy_collection(collection.0, sender)?;329330 <TokensMinted<T>>::remove(id);331 <TokensBurnt<T>>::remove(id);332 let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);333 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);334 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);335 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);336 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);337 Ok(())338 }339340 fn collection_has_tokens(collection_id: CollectionId) -> bool {341 <TotalSupply<T>>::iter_prefix((collection_id,))342 .next()343 .is_some()344 }345346 pub fn burn_token_unchecked(347 collection: &RefungibleHandle<T>,348 owner: &T::CrossAccountId,349 token_id: TokenId,350 ) -> DispatchResult {351 let burnt = <TokensBurnt<T>>::get(collection.id)352 .checked_add(1)353 .ok_or(ArithmeticError::Overflow)?;354355 <TokensBurnt<T>>::insert(collection.id, burnt);356 <TokenProperties<T>>::remove((collection.id, token_id));357 <TotalSupply<T>>::remove((collection.id, token_id));358 let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);359 let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);360 <PalletEvm<T>>::deposit_log(361 ERC721Events::Transfer {362 from: *owner.as_eth(),363 to: H160::default(),364 token_id: token_id.into(),365 }366 .to_log(collection_id_to_address(collection.id)),367 );368 Ok(())369 }370371 /// Burn RFT token pieces372 ///373 /// `burn` will decrease total amount of token pieces and amount owned by sender.374 /// `burn` can be called even if there are multiple owners of the RFT token.375 /// If sender wouldn't have any pieces left after `burn` than she will stop being376 /// one of the owners of the token. If there is no account that owns any pieces of377 /// the token than token will be burned too.378 ///379 /// - `amount`: Amount of token pieces to burn.380 /// - `token`: Token who's pieces should be burned381 /// - `collection`: Collection that contains the token382 pub fn burn(383 collection: &RefungibleHandle<T>,384 owner: &T::CrossAccountId,385 token: TokenId,386 amount: u128,387 ) -> DispatchResult {388 if <Balance<T>>::get((collection.id, token, owner)) == 0 {389 return Err(<CommonError<T>>::TokenValueTooLow.into());390 }391392 let total_supply = <TotalSupply<T>>::get((collection.id, token))393 .checked_sub(amount)394 .ok_or(<CommonError<T>>::TokenValueTooLow)?;395396 // This was probally last owner of this token?397 if total_supply == 0 {398 // Ensure user actually owns this amount399 ensure!(400 <Balance<T>>::get((collection.id, token, owner)) == amount,401 <CommonError<T>>::TokenValueTooLow402 );403 let account_balance = <AccountBalance<T>>::get((collection.id, owner))404 .checked_sub(1)405 // Should not occur406 .ok_or(ArithmeticError::Underflow)?;407408 // =========409410 <Owned<T>>::remove((collection.id, owner, token));411 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);412 <AccountBalance<T>>::insert((collection.id, owner), account_balance);413 Self::burn_token_unchecked(collection, owner, token)?;414 <PalletEvm<T>>::deposit_log(415 ERC20Events::Transfer {416 from: *owner.as_eth(),417 to: H160::default(),418 value: amount.into(),419 }420 .to_log(collection_id_to_address(collection.id)),421 );422 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(423 collection.id,424 token,425 owner.clone(),426 amount,427 ));428 return Ok(());429 }430431 let balance = <Balance<T>>::get((collection.id, token, owner))432 .checked_sub(amount)433 .ok_or(<CommonError<T>>::TokenValueTooLow)?;434 let account_balance = if balance == 0 {435 <AccountBalance<T>>::get((collection.id, owner))436 .checked_sub(1)437 // Should not occur438 .ok_or(ArithmeticError::Underflow)?439 } else {440 0441 };442443 // =========444445 if balance == 0 {446 <Owned<T>>::remove((collection.id, owner, token));447 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);448 <Balance<T>>::remove((collection.id, token, owner));449 <AccountBalance<T>>::insert((collection.id, owner), account_balance);450451 if let Ok(user) = Self::token_owner(collection.id, token) {452 <PalletEvm<T>>::deposit_log(453 ERC721Events::Transfer {454 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,455 to: *user.as_eth(),456 token_id: token.into(),457 }458 .to_log(collection_id_to_address(collection.id)),459 );460 }461 } else {462 <Balance<T>>::insert((collection.id, token, owner), balance);463 }464 <TotalSupply<T>>::insert((collection.id, token), total_supply);465466 <PalletEvm<T>>::deposit_log(467 ERC20Events::Transfer {468 from: *owner.as_eth(),469 to: H160::default(),470 value: amount.into(),471 }472 .to_log(T::EvmTokenAddressMapping::token_to_address(473 collection.id,474 token,475 )),476 );477 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(478 collection.id,479 token,480 owner.clone(),481 amount,482 ));483 Ok(())484 }485486 /// A batch operation to add, edit or remove properties for a token.487 /// It sets or removes a token's properties according to488 /// `properties_updates` contents:489 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`490 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.491 ///492 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.493 ///494 /// All affected properties should have `mutable` permission495 /// to be **deleted** or to be **set more than once**,496 /// and the sender should have permission to edit those properties.497 ///498 /// This function fires an event for each property change.499 /// In case of an error, all the changes (including the events) will be reverted500 /// since the function is transactional.501 #[transactional]502 fn modify_token_properties(503 collection: &RefungibleHandle<T>,504 sender: &T::CrossAccountId,505 token_id: TokenId,506 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,507 nesting_budget: &dyn Budget,508 ) -> DispatchResult {509 let mut property_writer =510 pallet_common::ExistingTokenPropertyWriter::new(collection, sender);511512 property_writer.write_token_properties(513 sender,514 token_id,515 properties_updates,516 nesting_budget,517 erc::ERC721TokenEvent::TokenChanged {518 token_id: token_id.into(),519 }520 .to_log(T::ContractAddress::get()),521 )522 }523524 pub fn next_token_id(collection: &RefungibleHandle<T>) -> Result<TokenId, DispatchError> {525 let next_token_id = <TokensMinted<T>>::get(collection.id)526 .checked_add(1)527 .ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;528529 ensure!(530 collection.limits.token_limit() >= next_token_id,531 <CommonError<T>>::CollectionTokenLimitExceeded532 );533534 Ok(TokenId(next_token_id))535 }536537 pub fn set_token_properties(538 collection: &RefungibleHandle<T>,539 sender: &T::CrossAccountId,540 token_id: TokenId,541 properties: impl Iterator<Item = Property>,542 nesting_budget: &dyn Budget,543 ) -> DispatchResult {544 Self::modify_token_properties(545 collection,546 sender,547 token_id,548 properties.map(|p| (p.key, Some(p.value))),549 nesting_budget,550 )551 }552553 pub fn set_token_property(554 collection: &RefungibleHandle<T>,555 sender: &T::CrossAccountId,556 token_id: TokenId,557 property: Property,558 nesting_budget: &dyn Budget,559 ) -> DispatchResult {560 Self::set_token_properties(561 collection,562 sender,563 token_id,564 [property].into_iter(),565 nesting_budget,566 )567 }568569 pub fn delete_token_properties(570 collection: &RefungibleHandle<T>,571 sender: &T::CrossAccountId,572 token_id: TokenId,573 property_keys: impl Iterator<Item = PropertyKey>,574 nesting_budget: &dyn Budget,575 ) -> DispatchResult {576 Self::modify_token_properties(577 collection,578 sender,579 token_id,580 property_keys.into_iter().map(|key| (key, None)),581 nesting_budget,582 )583 }584585 pub fn delete_token_property(586 collection: &RefungibleHandle<T>,587 sender: &T::CrossAccountId,588 token_id: TokenId,589 property_key: PropertyKey,590 nesting_budget: &dyn Budget,591 ) -> DispatchResult {592 Self::delete_token_properties(593 collection,594 sender,595 token_id,596 [property_key].into_iter(),597 nesting_budget,598 )599 }600601 /// Transfer RFT token pieces from one account to another.602 ///603 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.604 ///605 /// - `from`: Owner of token pieces to transfer.606 /// - `to`: Recepient of transfered token pieces.607 /// - `amount`: Amount of token pieces to transfer.608 /// - `token`: Token whos pieces should be transfered609 /// - `collection`: Collection that contains the token610 pub fn transfer(611 collection: &RefungibleHandle<T>,612 from: &T::CrossAccountId,613 to: &T::CrossAccountId,614 token: TokenId,615 amount: u128,616 nesting_budget: &dyn Budget,617 ) -> DispatchResult {618 let depositor = from;619 Self::transfer_internal(620 collection,621 depositor,622 from,623 to,624 token,625 amount,626 nesting_budget,627 )628 }629630 /// Transfers RFT tokens from the `from` account to the `to` account.631 /// The `depositor` is the account who deposits the tokens.632 /// For instance, the nesting rules will be checked against the `depositor`'s permissions.633 pub fn transfer_internal(634 collection: &RefungibleHandle<T>,635 depositor: &T::CrossAccountId,636 from: &T::CrossAccountId,637 to: &T::CrossAccountId,638 token: TokenId,639 amount: u128,640 nesting_budget: &dyn Budget,641 ) -> DispatchResult {642 ensure!(643 collection.limits.transfers_enabled(),644 <CommonError<T>>::TransferNotAllowed645 );646647 if collection.permissions.access() == AccessMode::AllowList {648 collection.check_allowlist(from)?;649 collection.check_allowlist(to)?;650 }651 <PalletCommon<T>>::ensure_correct_receiver(to)?;652653 let initial_balance_from = <Balance<T>>::get((collection.id, token, from));654655 if initial_balance_from == 0 {656 return Err(<CommonError<T>>::TokenValueTooLow.into());657 }658659 let updated_balance_from = initial_balance_from660 .checked_sub(amount)661 .ok_or(<CommonError<T>>::TokenValueTooLow)?;662 let mut create_target = false;663 let from_to_differ = from != to;664 let updated_balance_to = if from != to && amount != 0 {665 let old_balance = <Balance<T>>::get((collection.id, token, to));666 if old_balance == 0 {667 create_target = true;668 }669 Some(670 old_balance671 .checked_add(amount)672 .ok_or(ArithmeticError::Overflow)?,673 )674 } else {675 None676 };677678 let account_balance_from = if updated_balance_from == 0 {679 Some(680 <AccountBalance<T>>::get((collection.id, from))681 .checked_sub(1)682 // Should not occur683 .ok_or(ArithmeticError::Underflow)?,684 )685 } else {686 None687 };688 // Account data is created in token, AccountBalance should be increased689 // But only if from != to as we shouldn't check overflow in this case690 let account_balance_to = if create_target && from_to_differ {691 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))692 .checked_add(1)693 .ok_or(ArithmeticError::Overflow)?;694 ensure!(695 account_balance_to < collection.limits.account_token_ownership_limit(),696 <CommonError<T>>::AccountTokenLimitExceeded,697 );698699 Some(account_balance_to)700 } else {701 None702 };703704 // =========705706 if let Some(updated_balance_to) = updated_balance_to {707 // from != to && amount != 0708709 <PalletStructure<T>>::nest_if_sent_to_token(710 depositor,711 to,712 collection.id,713 token,714 nesting_budget,715 )?;716717 if updated_balance_from == 0 {718 <Balance<T>>::remove((collection.id, token, from));719 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);720 } else {721 <Balance<T>>::insert((collection.id, token, from), updated_balance_from);722 }723 <Balance<T>>::insert((collection.id, token, to), updated_balance_to);724 if let Some(account_balance_from) = account_balance_from {725 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);726 <Owned<T>>::remove((collection.id, from, token));727 }728 if let Some(account_balance_to) = account_balance_to {729 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);730 <Owned<T>>::insert((collection.id, to, token), true);731 }732 }733734 <PalletEvm<T>>::deposit_log(735 ERC20Events::Transfer {736 from: *from.as_eth(),737 to: *to.as_eth(),738 value: amount.into(),739 }740 .to_log(T::EvmTokenAddressMapping::token_to_address(741 collection.id,742 token,743 )),744 );745746 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(747 collection.id,748 token,749 from.clone(),750 to.clone(),751 amount,752 ));753754 let total_supply = <TotalSupply<T>>::get((collection.id, token));755756 if amount == total_supply {757 // if token was fully owned by `from` and will be fully owned by `to` after transfer758 <PalletEvm<T>>::deposit_log(759 ERC721Events::Transfer {760 from: *from.as_eth(),761 to: *to.as_eth(),762 token_id: token.into(),763 }764 .to_log(collection_id_to_address(collection.id)),765 );766 } else if let Some(updated_balance_to) = updated_balance_to {767 // if `from` not equals `to`. This condition is needed to avoid sending event768 // when `from` fully owns token and sends part of token pieces to itself.769 if initial_balance_from == total_supply {770 // if token was fully owned by `from` and will be only partially owned by `to`771 // and `from` after transfer772 <PalletEvm<T>>::deposit_log(773 ERC721Events::Transfer {774 from: *from.as_eth(),775 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,776 token_id: token.into(),777 }778 .to_log(collection_id_to_address(collection.id)),779 );780 } else if updated_balance_to == total_supply {781 // if token was partially owned by `from` and will be fully owned by `to` after transfer782 <PalletEvm<T>>::deposit_log(783 ERC721Events::Transfer {784 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,785 to: *to.as_eth(),786 token_id: token.into(),787 }788 .to_log(collection_id_to_address(collection.id)),789 );790 }791 }792793 Ok(())794 }795796 /// Batched operation to create multiple RFT tokens.797 ///798 /// Same as `create_item` but creates multiple tokens.799 ///800 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.801 pub fn create_multiple_items(802 collection: &RefungibleHandle<T>,803 sender: &T::CrossAccountId,804 data: Vec<CreateItemData<T>>,805 nesting_budget: &dyn Budget,806 ) -> DispatchResult {807 if !collection.is_owner_or_admin(sender) {808 ensure!(809 collection.permissions.mint_mode(),810 <CommonError<T>>::PublicMintingNotAllowed811 );812 collection.check_allowlist(sender)?;813814 for item in data.iter() {815 for user in item.users.keys() {816 collection.check_allowlist(user)?;817 }818 }819 }820821 for item in data.iter() {822 for (owner, _) in item.users.iter() {823 <PalletCommon<T>>::ensure_correct_receiver(owner)?;824 }825 }826827 // Total pieces per tokens828 let totals = data829 .iter()830 .map(|data| {831 Ok(data832 .users833 .iter()834 .map(|u| u.1)835 .try_fold(0u128, |acc, v| acc.checked_add(*v))836 .ok_or(ArithmeticError::Overflow)?)837 })838 .collect::<Result<Vec<_>, DispatchError>>()?;839 for total in &totals {840 ensure!(841 *total <= MAX_REFUNGIBLE_PIECES,842 <Error<T>>::WrongRefungiblePieces843 );844 }845846 let first_token_id = <TokensMinted<T>>::get(collection.id);847 let tokens_minted = first_token_id848 .checked_add(data.len() as u32)849 .ok_or(ArithmeticError::Overflow)?;850 ensure!(851 tokens_minted < collection.limits.token_limit(),852 <CommonError<T>>::CollectionTokenLimitExceeded853 );854855 let mut balances = BTreeMap::new();856 for data in &data {857 for owner in data.users.keys() {858 let balance = balances859 .entry(owner)860 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));861 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;862863 ensure!(864 *balance <= collection.limits.account_token_ownership_limit(),865 <CommonError<T>>::AccountTokenLimitExceeded,866 );867 }868 }869870 for (i, token) in data.iter().enumerate() {871 let token_id = TokenId(first_token_id + i as u32 + 1);872 for (to, _) in token.users.iter() {873 <PalletStructure<T>>::check_nesting(874 sender,875 to,876 collection.id,877 token_id,878 nesting_budget,879 )?;880 }881 }882883 // =========884885 let mut property_writer = pallet_common::NewTokenPropertyWriter::new(collection, sender);886887 with_transaction(|| {888 for (i, data) in data.iter().enumerate() {889 let token_id = first_token_id + i as u32 + 1;890 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);891892 let token = TokenId(token_id);893894 let mut mint_target_is_sender = true;895 for (user, amount) in data.users.iter() {896 if *amount == 0 {897 continue;898 }899900 mint_target_is_sender = mint_target_is_sender && sender.conv_eq(user);901902 <Balance<T>>::insert((collection.id, token_id, &user), amount);903 <Owned<T>>::insert((collection.id, &user, token), true);904 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(905 user,906 collection.id,907 token,908 );909 }910911 if let Err(e) = property_writer.write_token_properties(912 mint_target_is_sender,913 token,914 data.properties.clone().into_iter(),915 erc::ERC721TokenEvent::TokenChanged {916 token_id: token.into(),917 }918 .to_log(T::ContractAddress::get()),919 ) {920 return TransactionOutcome::Rollback(Err(e));921 }922 }923 TransactionOutcome::Commit(Ok(()))924 })?;925926 <TokensMinted<T>>::insert(collection.id, tokens_minted);927928 for (account, balance) in balances {929 <AccountBalance<T>>::insert((collection.id, account), balance);930 }931932 for (i, token) in data.into_iter().enumerate() {933 let token_id = first_token_id + i as u32 + 1;934935 let receivers = token936 .users937 .into_iter()938 .filter(|(_, amount)| *amount > 0)939 .collect::<Vec<_>>();940941 if let [(user, _)] = receivers.as_slice() {942 // if there is exactly one receiver943 <PalletEvm<T>>::deposit_log(944 ERC721Events::Transfer {945 from: H160::default(),946 to: *user.as_eth(),947 token_id: token_id.into(),948 }949 .to_log(collection_id_to_address(collection.id)),950 );951 } else if let [_, ..] = receivers.as_slice() {952 // if there is more than one receiver953 <PalletEvm<T>>::deposit_log(954 ERC721Events::Transfer {955 from: H160::default(),956 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,957 token_id: token_id.into(),958 }959 .to_log(collection_id_to_address(collection.id)),960 );961 }962963 for (user, amount) in receivers.into_iter() {964 <PalletEvm<T>>::deposit_log(965 ERC20Events::Transfer {966 from: H160::default(),967 to: *user.as_eth(),968 value: amount.into(),969 }970 .to_log(T::EvmTokenAddressMapping::token_to_address(971 collection.id,972 TokenId(token_id),973 )),974 );975 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(976 collection.id,977 TokenId(token_id),978 user,979 amount,980 ));981 }982 }983 Ok(())984 }985986 pub fn set_allowance_unchecked(987 collection: &RefungibleHandle<T>,988 sender: &T::CrossAccountId,989 spender: &T::CrossAccountId,990 token: TokenId,991 amount: u128,992 ) {993 if amount == 0 {994 <Allowance<T>>::remove((collection.id, token, sender, spender));995 } else {996 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);997 }998999 <PalletEvm<T>>::deposit_log(1000 ERC20Events::Approval {1001 owner: *sender.as_eth(),1002 spender: *spender.as_eth(),1003 value: amount.into(),1004 }1005 .to_log(T::EvmTokenAddressMapping::token_to_address(1006 collection.id,1007 token,1008 )),1009 );1010 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1011 collection.id,1012 token,1013 sender.clone(),1014 spender.clone(),1015 amount,1016 ))1017 }10181019 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1020 ///1021 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1022 pub fn set_allowance(1023 collection: &RefungibleHandle<T>,1024 sender: &T::CrossAccountId,1025 spender: &T::CrossAccountId,1026 token: TokenId,1027 amount: u128,1028 ) -> DispatchResult {1029 if collection.permissions.access() == AccessMode::AllowList {1030 collection.check_allowlist(sender)?;1031 collection.check_allowlist(spender)?;1032 }10331034 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10351036 if <Balance<T>>::get((collection.id, token, sender)) < amount {1037 ensure!(1038 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1039 <CommonError<T>>::CantApproveMoreThanOwned1040 );1041 }10421043 // =========10441045 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1046 Ok(())1047 }10481049 /// Set allowance to spend from sender's eth mirror1050 ///1051 /// - `from`: Address of sender's eth mirror.1052 /// - `to`: Adress of spender.1053 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1054 pub fn set_allowance_from(1055 collection: &RefungibleHandle<T>,1056 sender: &T::CrossAccountId,1057 from: &T::CrossAccountId,1058 to: &T::CrossAccountId,1059 token_id: TokenId,1060 amount: u128,1061 ) -> DispatchResult {1062 if collection.permissions.access() == AccessMode::AllowList {1063 collection.check_allowlist(sender)?;1064 collection.check_allowlist(from)?;1065 collection.check_allowlist(to)?;1066 }10671068 <PalletCommon<T>>::ensure_correct_receiver(to)?;10691070 ensure!(1071 sender.conv_eq(from),1072 <CommonError<T>>::AddressIsNotEthMirror1073 );10741075 if <Balance<T>>::get((collection.id, token_id, from)) < amount {1076 ensure!(1077 collection.limits.owner_can_transfer()1078 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1079 && Self::token_exists(collection, token_id),1080 <CommonError<T>>::CantApproveMoreThanOwned1081 );1082 }10831084 // =========10851086 Self::set_allowance_unchecked(collection, from, to, token_id, amount);1087 Ok(())1088 }10891090 /// Returns allowance, which should be set after transaction1091 fn check_allowed(1092 collection: &RefungibleHandle<T>,1093 spender: &T::CrossAccountId,1094 from: &T::CrossAccountId,1095 token: TokenId,1096 amount: u128,1097 nesting_budget: &dyn Budget,1098 ) -> Result<Option<u128>, DispatchError> {1099 if spender.conv_eq(from) {1100 return Ok(None);1101 }1102 if collection.permissions.access() == AccessMode::AllowList {1103 // `from`, `to` checked in [`transfer`]1104 collection.check_allowlist(spender)?;1105 }11061107 if collection.ignores_token_restrictions(spender) {1108 return Ok(Self::compute_allowance_decrease(1109 collection, token, from, spender, amount,1110 ));1111 }11121113 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1114 // TODO: should collection owner be allowed to perform this transfer?1115 ensure!(1116 <PalletStructure<T>>::check_indirectly_owned(1117 spender.clone(),1118 source.0,1119 source.1,1120 None,1121 nesting_budget1122 )?,1123 <CommonError<T>>::ApprovedValueTooLow,1124 );1125 return Ok(None);1126 }11271128 let allowance = Self::compute_allowance_decrease(collection, token, from, spender, amount);1129 if allowance.is_some() {1130 return Ok(allowance);1131 }11321133 // Allowance (if any) would be reduced if spender is also wallet operator1134 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1135 return Ok(allowance);1136 }11371138 Err(<CommonError<T>>::ApprovedValueTooLow.into())1139 }11401141 /// Returns `Some(amount)` if the `spender` have allowance to spend this amount.1142 /// Otherwise, it returns `None`.1143 fn compute_allowance_decrease(1144 collection: &RefungibleHandle<T>,1145 token: TokenId,1146 from: &T::CrossAccountId,1147 spender: &T::CrossAccountId,1148 amount: u128,1149 ) -> Option<u128> {1150 <Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1151 }11521153 /// Transfer RFT token pieces from one account to another.1154 ///1155 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1156 /// The owner should set allowance for the spender to transfer pieces.1157 ///1158 /// [`transfer`]: struct.Pallet.html#method.transfer1159 pub fn transfer_from(1160 collection: &RefungibleHandle<T>,1161 spender: &T::CrossAccountId,1162 from: &T::CrossAccountId,1163 to: &T::CrossAccountId,1164 token: TokenId,1165 amount: u128,1166 nesting_budget: &dyn Budget,1167 ) -> DispatchResult {1168 let allowance =1169 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11701171 // =========11721173 Self::transfer_internal(collection, spender, from, to, token, amount, nesting_budget)?;1174 if let Some(allowance) = allowance {1175 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1176 }1177 Ok(())1178 }11791180 /// Burn RFT token pieces from the account.1181 ///1182 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1183 /// set allowance for the spender to burn pieces1184 ///1185 /// [`burn`]: struct.Pallet.html#method.burn1186 pub fn burn_from(1187 collection: &RefungibleHandle<T>,1188 spender: &T::CrossAccountId,1189 from: &T::CrossAccountId,1190 token: TokenId,1191 amount: u128,1192 nesting_budget: &dyn Budget,1193 ) -> DispatchResult {1194 let allowance =1195 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11961197 // =========11981199 Self::burn(collection, from, token, amount)?;1200 if let Some(allowance) = allowance {1201 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1202 }1203 Ok(())1204 }12051206 /// Create RFT token.1207 ///1208 /// The sender should be the owner/admin of the collection or collection should be configured1209 /// to allow public minting.1210 ///1211 /// - `data`: Contains list of users who will become the owners of the token pieces and amount1212 /// of token pieces they will receive.1213 pub fn create_item(1214 collection: &RefungibleHandle<T>,1215 sender: &T::CrossAccountId,1216 data: CreateItemData<T>,1217 nesting_budget: &dyn Budget,1218 ) -> DispatchResult {1219 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1220 }12211222 /// Repartition RFT token.1223 ///1224 /// `repartition` will set token balance of the sender and total amount of token pieces.1225 /// Sender should own all of the token pieces. `repartition' could be done even if some1226 /// token pieces were burned before.1227 ///1228 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.1229 pub fn repartition(1230 collection: &RefungibleHandle<T>,1231 owner: &T::CrossAccountId,1232 token: TokenId,1233 amount: u128,1234 ) -> DispatchResult {1235 ensure!(1236 amount <= MAX_REFUNGIBLE_PIECES,1237 <Error<T>>::WrongRefungiblePieces1238 );1239 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1240 // Ensure user owns all pieces1241 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1242 let balance = <Balance<T>>::get((collection.id, token, owner));1243 ensure!(1244 total_pieces == balance,1245 <Error<T>>::RepartitionWhileNotOwningAllPieces1246 );12471248 <Balance<T>>::insert((collection.id, token, owner), amount);1249 <TotalSupply<T>>::insert((collection.id, token), amount);12501251 match total_pieces.cmp(&amount) {1252 Ordering::Less => {1253 let mint_amount = amount - total_pieces;1254 <PalletEvm<T>>::deposit_log(1255 ERC20Events::Transfer {1256 from: H160::default(),1257 to: *owner.as_eth(),1258 value: mint_amount.into(),1259 }1260 .to_log(T::EvmTokenAddressMapping::token_to_address(1261 collection.id,1262 token,1263 )),1264 );1265 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1266 collection.id,1267 token,1268 owner.clone(),1269 mint_amount,1270 ));1271 }1272 Ordering::Greater => {1273 let burn_amount = total_pieces - amount;1274 <PalletEvm<T>>::deposit_log(1275 ERC20Events::Transfer {1276 from: *owner.as_eth(),1277 to: H160::default(),1278 value: burn_amount.into(),1279 }1280 .to_log(T::EvmTokenAddressMapping::token_to_address(1281 collection.id,1282 token,1283 )),1284 );1285 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1286 collection.id,1287 token,1288 owner.clone(),1289 burn_amount,1290 ));1291 }1292 Ordering::Equal => {}1293 }12941295 Ok(())1296 }12971298 fn token_owner(1299 collection_id: CollectionId,1300 token_id: TokenId,1301 ) -> Result<T::CrossAccountId, TokenOwnerError> {1302 let mut owner = None;1303 let mut count = 0;1304 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1305 count += 1;1306 if count > 1 {1307 return Err(TokenOwnerError::MultipleOwners);1308 }1309 owner = Some(key);1310 }1311 owner.ok_or(TokenOwnerError::NotFound)1312 }13131314 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1315 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1316 }13171318 pub fn set_collection_properties(1319 collection: &RefungibleHandle<T>,1320 sender: &T::CrossAccountId,1321 properties: Vec<Property>,1322 ) -> DispatchResult {1323 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1324 }13251326 pub fn delete_collection_properties(1327 collection: &RefungibleHandle<T>,1328 sender: &T::CrossAccountId,1329 property_keys: Vec<PropertyKey>,1330 ) -> DispatchResult {1331 <PalletCommon<T>>::delete_collection_properties(1332 collection,1333 sender,1334 property_keys.into_iter(),1335 )1336 }13371338 pub fn set_token_property_permissions(1339 collection: &RefungibleHandle<T>,1340 sender: &T::CrossAccountId,1341 property_permissions: Vec<PropertyKeyPermission>,1342 ) -> DispatchResult {1343 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1344 }13451346 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1347 <PalletCommon<T>>::property_permissions(collection_id)1348 }13491350 pub fn set_scoped_token_property_permissions(1351 collection: &RefungibleHandle<T>,1352 sender: &T::CrossAccountId,1353 scope: PropertyScope,1354 property_permissions: Vec<PropertyKeyPermission>,1355 ) -> DispatchResult {1356 <PalletCommon<T>>::set_scoped_token_property_permissions(1357 collection,1358 sender,1359 scope,1360 property_permissions,1361 )1362 }13631364 /// Returns 10 token in no particular order.1365 ///1366 /// There is no direct way to get token holders in ascending order,1367 /// since `iter_prefix` returns values in no particular order.1368 /// Therefore, getting the 10 largest holders with a large value of holders1369 /// can lead to impact memory allocation + sorting with `n * log (n)`.1370 pub fn token_owners(1371 collection_id: CollectionId,1372 token: TokenId,1373 ) -> Option<Vec<T::CrossAccountId>> {1374 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1375 .map(|(owner, _amount)| owner)1376 .take(10)1377 .collect();13781379 if res.is_empty() {1380 None1381 } else {1382 Some(res)1383 }1384 }13851386 /// Sets or unsets the approval of a given operator.1387 ///1388 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1389 /// - `owner`: Token owner1390 /// - `operator`: Operator1391 /// - `approve`: Should operator status be granted or revoked?1392 pub fn set_allowance_for_all(1393 collection: &RefungibleHandle<T>,1394 owner: &T::CrossAccountId,1395 spender: &T::CrossAccountId,1396 approve: bool,1397 ) -> DispatchResult {1398 <PalletCommon<T>>::set_allowance_for_all(1399 collection,1400 owner,1401 spender,1402 approve,1403 || <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),1404 ERC721Events::ApprovalForAll {1405 owner: *owner.as_eth(),1406 operator: *spender.as_eth(),1407 approved: approve,1408 }1409 .to_log(collection_id_to_address(collection.id)),1410 )1411 }14121413 /// Tells whether the given `owner` approves the `operator`.1414 pub fn allowance_for_all(1415 collection: &RefungibleHandle<T>,1416 owner: &T::CrossAccountId,1417 spender: &T::CrossAccountId,1418 ) -> bool {1419 <CollectionAllowance<T>>::get((collection.id, owner, spender))1420 }14211422 pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1423 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1424 if let Some(properties) = properties {1425 properties.recompute_consumed_space();1426 }1427 });14281429 Ok(())1430 }1431}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 core::{cmp::Ordering, ops::Deref};9192use evm_coder::ToLog;93use frame_support::{ensure, storage::with_transaction, transactional};94pub use pallet::*;95use pallet_common::{96 eth::collection_id_to_address, Error as CommonError, Event as CommonEvent,97 Pallet as PalletCommon,98};99use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};100use pallet_evm_coder_substrate::WithRecorder;101use pallet_structure::Pallet as PalletStructure;102use sp_core::{Get, H160};103use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};104use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};105use up_data_structs::{106 budget::Budget, mapping::TokenAddressMapping, AccessMode, CollectionId,107 CreateRefungibleExMultipleOwners, PropertiesPermissionMap, Property, PropertyKey,108 PropertyKeyPermission, PropertyScope, PropertyValue, TokenId, TokenOwnerError,109 TokenProperties as TokenPropertiesT, MAX_REFUNGIBLE_PIECES,110};111112use crate::{erc::ERC721Events, erc_token::ERC20Events};113#[cfg(feature = "runtime-benchmarks")]114pub mod benchmarking;115pub mod common;116pub mod erc;117pub mod erc_token;118pub mod weights;119120pub type CreateItemData<T> =121 CreateRefungibleExMultipleOwners<<T as pallet_evm::Config>::CrossAccountId>;122pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;123124#[frame_support::pallet]125pub mod pallet {126 use frame_support::{127 pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128, Blake2_128Concat,128 Twox64Concat,129 };130 use up_data_structs::{CollectionId, TokenId};131132 use super::{weights::WeightInfo, *};133134 #[pallet::error]135 pub enum Error<T> {136 /// Not Refungible item data used to mint in Refungible collection.137 NotRefungibleDataUsedToMintFungibleCollectionToken,138 /// Maximum refungibility exceeded.139 WrongRefungiblePieces,140 /// Refungible token can't be repartitioned by user who isn't owns all pieces.141 RepartitionWhileNotOwningAllPieces,142 /// Refungible token can't nest other tokens.143 RefungibleDisallowsNesting,144 /// Setting item properties is not allowed.145 SettingPropertiesNotAllowed,146 }147148 #[pallet::config]149 pub trait Config:150 frame_system::Config + pallet_common::Config + pallet_structure::Config151 {152 type WeightInfo: WeightInfo;153 }154155 const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);156157 #[pallet::pallet]158 #[pallet::storage_version(STORAGE_VERSION)]159 pub struct Pallet<T>(_);160161 /// Total amount of minted tokens in a collection.162 #[pallet::storage]163 pub type TokensMinted<T: Config> =164 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;165166 /// Amount of tokens burnt in a collection.167 #[pallet::storage]168 pub type TokensBurnt<T: Config> =169 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;170171 /// Amount of pieces a refungible token is split into.172 #[pallet::storage]173 #[pallet::getter(fn token_properties)]174 pub type TokenProperties<T: Config> = StorageNMap<175 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),176 Value = TokenPropertiesT,177 QueryKind = OptionQuery,178 >;179180 /// Total amount of pieces for token181 #[pallet::storage]182 pub type TotalSupply<T: Config> = StorageNMap<183 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),184 Value = u128,185 QueryKind = ValueQuery,186 >;187188 /// Used to enumerate tokens owned by account.189 #[pallet::storage]190 pub type Owned<T: Config> = StorageNMap<191 Key = (192 Key<Twox64Concat, CollectionId>,193 Key<Blake2_128Concat, T::CrossAccountId>,194 Key<Twox64Concat, TokenId>,195 ),196 Value = bool,197 QueryKind = ValueQuery,198 >;199200 /// Amount of tokens (not pieces) partially owned by an account within a collection.201 #[pallet::storage]202 pub type AccountBalance<T: Config> = StorageNMap<203 Key = (204 Key<Twox64Concat, CollectionId>,205 // Owner206 Key<Blake2_128Concat, T::CrossAccountId>,207 ),208 Value = u32,209 QueryKind = ValueQuery,210 >;211212 /// Amount of token pieces owned by account.213 #[pallet::storage]214 pub type Balance<T: Config> = StorageNMap<215 Key = (216 Key<Twox64Concat, CollectionId>,217 Key<Twox64Concat, TokenId>,218 // Owner219 Key<Blake2_128Concat, T::CrossAccountId>,220 ),221 Value = u128,222 QueryKind = ValueQuery,223 >;224225 /// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.226 #[pallet::storage]227 pub type Allowance<T: Config> = StorageNMap<228 Key = (229 Key<Twox64Concat, CollectionId>,230 Key<Twox64Concat, TokenId>,231 // Owner232 Key<Blake2_128, T::CrossAccountId>,233 // Spender234 Key<Blake2_128Concat, T::CrossAccountId>,235 ),236 Value = u128,237 QueryKind = ValueQuery,238 >;239240 /// Spender set by a wallet owner that could perform certain transactions on all tokens in the wallet.241 #[pallet::storage]242 pub type CollectionAllowance<T: Config> = StorageNMap<243 Key = (244 Key<Twox64Concat, CollectionId>,245 Key<Blake2_128Concat, T::CrossAccountId>, // Owner246 Key<Blake2_128Concat, T::CrossAccountId>, // Spender247 ),248 Value = bool,249 QueryKind = ValueQuery,250 >;251}252253pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);254impl<T: Config> RefungibleHandle<T> {255 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {256 Self(inner)257 }258 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {259 self.0260 }261 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {262 &mut self.0263 }264}265266impl<T: Config> Deref for RefungibleHandle<T> {267 type Target = pallet_common::CollectionHandle<T>;268269 fn deref(&self) -> &Self::Target {270 &self.0271 }272}273274impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {275 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {276 self.0.recorder()277 }278 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {279 self.0.into_recorder()280 }281}282283impl<T: Config> Pallet<T> {284 /// Get number of RFT tokens in collection285 pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {286 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)287 }288289 /// Check that RFT token exists290 ///291 /// - `token`: Token ID.292 pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {293 <TotalSupply<T>>::contains_key((collection.id, token))294 }295}296297// unchecked calls skips any permission checks298impl<T: Config> Pallet<T> {299 /// Destroy RFT collection300 ///301 /// `destroy_collection` will throw error if collection contains any tokens.302 /// Only owner can destroy collection.303 pub fn destroy_collection(304 collection: RefungibleHandle<T>,305 sender: &T::CrossAccountId,306 ) -> DispatchResult {307 let id = collection.id;308309 if Self::collection_has_tokens(id) {310 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());311 }312313 // =========314315 PalletCommon::destroy_collection(collection.0, sender)?;316317 <TokensMinted<T>>::remove(id);318 <TokensBurnt<T>>::remove(id);319 let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);320 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);321 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);322 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);323 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);324 Ok(())325 }326327 fn collection_has_tokens(collection_id: CollectionId) -> bool {328 <TotalSupply<T>>::iter_prefix((collection_id,))329 .next()330 .is_some()331 }332333 pub fn burn_token_unchecked(334 collection: &RefungibleHandle<T>,335 owner: &T::CrossAccountId,336 token_id: TokenId,337 ) -> DispatchResult {338 let burnt = <TokensBurnt<T>>::get(collection.id)339 .checked_add(1)340 .ok_or(ArithmeticError::Overflow)?;341342 <TokensBurnt<T>>::insert(collection.id, burnt);343 <TokenProperties<T>>::remove((collection.id, token_id));344 <TotalSupply<T>>::remove((collection.id, token_id));345 let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);346 let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);347 <PalletEvm<T>>::deposit_log(348 ERC721Events::Transfer {349 from: *owner.as_eth(),350 to: H160::default(),351 token_id: token_id.into(),352 }353 .to_log(collection_id_to_address(collection.id)),354 );355 Ok(())356 }357358 /// Burn RFT token pieces359 ///360 /// `burn` will decrease total amount of token pieces and amount owned by sender.361 /// `burn` can be called even if there are multiple owners of the RFT token.362 /// If sender wouldn't have any pieces left after `burn` than she will stop being363 /// one of the owners of the token. If there is no account that owns any pieces of364 /// the token than token will be burned too.365 ///366 /// - `amount`: Amount of token pieces to burn.367 /// - `token`: Token who's pieces should be burned368 /// - `collection`: Collection that contains the token369 pub fn burn(370 collection: &RefungibleHandle<T>,371 owner: &T::CrossAccountId,372 token: TokenId,373 amount: u128,374 ) -> DispatchResult {375 if <Balance<T>>::get((collection.id, token, owner)) == 0 {376 return Err(<CommonError<T>>::TokenValueTooLow.into());377 }378379 let total_supply = <TotalSupply<T>>::get((collection.id, token))380 .checked_sub(amount)381 .ok_or(<CommonError<T>>::TokenValueTooLow)?;382383 // This was probally last owner of this token?384 if total_supply == 0 {385 // Ensure user actually owns this amount386 ensure!(387 <Balance<T>>::get((collection.id, token, owner)) == amount,388 <CommonError<T>>::TokenValueTooLow389 );390 let account_balance = <AccountBalance<T>>::get((collection.id, owner))391 .checked_sub(1)392 // Should not occur393 .ok_or(ArithmeticError::Underflow)?;394395 // =========396397 <Owned<T>>::remove((collection.id, owner, token));398 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);399 <AccountBalance<T>>::insert((collection.id, owner), account_balance);400 Self::burn_token_unchecked(collection, owner, token)?;401 <PalletEvm<T>>::deposit_log(402 ERC20Events::Transfer {403 from: *owner.as_eth(),404 to: H160::default(),405 value: amount.into(),406 }407 .to_log(collection_id_to_address(collection.id)),408 );409 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(410 collection.id,411 token,412 owner.clone(),413 amount,414 ));415 return Ok(());416 }417418 let balance = <Balance<T>>::get((collection.id, token, owner))419 .checked_sub(amount)420 .ok_or(<CommonError<T>>::TokenValueTooLow)?;421 let account_balance = if balance == 0 {422 <AccountBalance<T>>::get((collection.id, owner))423 .checked_sub(1)424 // Should not occur425 .ok_or(ArithmeticError::Underflow)?426 } else {427 0428 };429430 // =========431432 if balance == 0 {433 <Owned<T>>::remove((collection.id, owner, token));434 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);435 <Balance<T>>::remove((collection.id, token, owner));436 <AccountBalance<T>>::insert((collection.id, owner), account_balance);437438 if let Ok(user) = Self::token_owner(collection.id, token) {439 <PalletEvm<T>>::deposit_log(440 ERC721Events::Transfer {441 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,442 to: *user.as_eth(),443 token_id: token.into(),444 }445 .to_log(collection_id_to_address(collection.id)),446 );447 }448 } else {449 <Balance<T>>::insert((collection.id, token, owner), balance);450 }451 <TotalSupply<T>>::insert((collection.id, token), total_supply);452453 <PalletEvm<T>>::deposit_log(454 ERC20Events::Transfer {455 from: *owner.as_eth(),456 to: H160::default(),457 value: amount.into(),458 }459 .to_log(T::EvmTokenAddressMapping::token_to_address(460 collection.id,461 token,462 )),463 );464 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(465 collection.id,466 token,467 owner.clone(),468 amount,469 ));470 Ok(())471 }472473 /// A batch operation to add, edit or remove properties for a token.474 /// It sets or removes a token's properties according to475 /// `properties_updates` contents:476 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`477 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.478 ///479 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.480 ///481 /// All affected properties should have `mutable` permission482 /// to be **deleted** or to be **set more than once**,483 /// and the sender should have permission to edit those properties.484 ///485 /// This function fires an event for each property change.486 /// In case of an error, all the changes (including the events) will be reverted487 /// since the function is transactional.488 #[transactional]489 fn modify_token_properties(490 collection: &RefungibleHandle<T>,491 sender: &T::CrossAccountId,492 token_id: TokenId,493 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,494 nesting_budget: &dyn Budget,495 ) -> DispatchResult {496 let mut property_writer =497 pallet_common::ExistingTokenPropertyWriter::new(collection, sender);498499 property_writer.write_token_properties(500 sender,501 token_id,502 properties_updates,503 nesting_budget,504 erc::ERC721TokenEvent::TokenChanged {505 token_id: token_id.into(),506 }507 .to_log(T::ContractAddress::get()),508 )509 }510511 pub fn next_token_id(collection: &RefungibleHandle<T>) -> Result<TokenId, DispatchError> {512 let next_token_id = <TokensMinted<T>>::get(collection.id)513 .checked_add(1)514 .ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;515516 ensure!(517 collection.limits.token_limit() >= next_token_id,518 <CommonError<T>>::CollectionTokenLimitExceeded519 );520521 Ok(TokenId(next_token_id))522 }523524 pub fn set_token_properties(525 collection: &RefungibleHandle<T>,526 sender: &T::CrossAccountId,527 token_id: TokenId,528 properties: impl Iterator<Item = Property>,529 nesting_budget: &dyn Budget,530 ) -> DispatchResult {531 Self::modify_token_properties(532 collection,533 sender,534 token_id,535 properties.map(|p| (p.key, Some(p.value))),536 nesting_budget,537 )538 }539540 pub fn set_token_property(541 collection: &RefungibleHandle<T>,542 sender: &T::CrossAccountId,543 token_id: TokenId,544 property: Property,545 nesting_budget: &dyn Budget,546 ) -> DispatchResult {547 Self::set_token_properties(548 collection,549 sender,550 token_id,551 [property].into_iter(),552 nesting_budget,553 )554 }555556 pub fn delete_token_properties(557 collection: &RefungibleHandle<T>,558 sender: &T::CrossAccountId,559 token_id: TokenId,560 property_keys: impl Iterator<Item = PropertyKey>,561 nesting_budget: &dyn Budget,562 ) -> DispatchResult {563 Self::modify_token_properties(564 collection,565 sender,566 token_id,567 property_keys.into_iter().map(|key| (key, None)),568 nesting_budget,569 )570 }571572 pub fn delete_token_property(573 collection: &RefungibleHandle<T>,574 sender: &T::CrossAccountId,575 token_id: TokenId,576 property_key: PropertyKey,577 nesting_budget: &dyn Budget,578 ) -> DispatchResult {579 Self::delete_token_properties(580 collection,581 sender,582 token_id,583 [property_key].into_iter(),584 nesting_budget,585 )586 }587588 /// Transfer RFT token pieces from one account to another.589 ///590 /// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.591 ///592 /// - `from`: Owner of token pieces to transfer.593 /// - `to`: Recepient of transfered token pieces.594 /// - `amount`: Amount of token pieces to transfer.595 /// - `token`: Token whos pieces should be transfered596 /// - `collection`: Collection that contains the token597 pub fn transfer(598 collection: &RefungibleHandle<T>,599 from: &T::CrossAccountId,600 to: &T::CrossAccountId,601 token: TokenId,602 amount: u128,603 nesting_budget: &dyn Budget,604 ) -> DispatchResult {605 let depositor = from;606 Self::transfer_internal(607 collection,608 depositor,609 from,610 to,611 token,612 amount,613 nesting_budget,614 )615 }616617 /// Transfers RFT tokens from the `from` account to the `to` account.618 /// The `depositor` is the account who deposits the tokens.619 /// For instance, the nesting rules will be checked against the `depositor`'s permissions.620 pub fn transfer_internal(621 collection: &RefungibleHandle<T>,622 depositor: &T::CrossAccountId,623 from: &T::CrossAccountId,624 to: &T::CrossAccountId,625 token: TokenId,626 amount: u128,627 nesting_budget: &dyn Budget,628 ) -> DispatchResult {629 ensure!(630 collection.limits.transfers_enabled(),631 <CommonError<T>>::TransferNotAllowed632 );633634 if collection.permissions.access() == AccessMode::AllowList {635 collection.check_allowlist(from)?;636 collection.check_allowlist(to)?;637 }638 <PalletCommon<T>>::ensure_correct_receiver(to)?;639640 let initial_balance_from = <Balance<T>>::get((collection.id, token, from));641642 if initial_balance_from == 0 {643 return Err(<CommonError<T>>::TokenValueTooLow.into());644 }645646 let updated_balance_from = initial_balance_from647 .checked_sub(amount)648 .ok_or(<CommonError<T>>::TokenValueTooLow)?;649 let mut create_target = false;650 let from_to_differ = from != to;651 let updated_balance_to = if from != to && amount != 0 {652 let old_balance = <Balance<T>>::get((collection.id, token, to));653 if old_balance == 0 {654 create_target = true;655 }656 Some(657 old_balance658 .checked_add(amount)659 .ok_or(ArithmeticError::Overflow)?,660 )661 } else {662 None663 };664665 let account_balance_from = if updated_balance_from == 0 {666 Some(667 <AccountBalance<T>>::get((collection.id, from))668 .checked_sub(1)669 // Should not occur670 .ok_or(ArithmeticError::Underflow)?,671 )672 } else {673 None674 };675 // Account data is created in token, AccountBalance should be increased676 // But only if from != to as we shouldn't check overflow in this case677 let account_balance_to = if create_target && from_to_differ {678 let account_balance_to = <AccountBalance<T>>::get((collection.id, to))679 .checked_add(1)680 .ok_or(ArithmeticError::Overflow)?;681 ensure!(682 account_balance_to < collection.limits.account_token_ownership_limit(),683 <CommonError<T>>::AccountTokenLimitExceeded,684 );685686 Some(account_balance_to)687 } else {688 None689 };690691 // =========692693 if let Some(updated_balance_to) = updated_balance_to {694 // from != to && amount != 0695696 <PalletStructure<T>>::nest_if_sent_to_token(697 depositor,698 to,699 collection.id,700 token,701 nesting_budget,702 )?;703704 if updated_balance_from == 0 {705 <Balance<T>>::remove((collection.id, token, from));706 <PalletStructure<T>>::unnest_if_nested(from, collection.id, token);707 } else {708 <Balance<T>>::insert((collection.id, token, from), updated_balance_from);709 }710 <Balance<T>>::insert((collection.id, token, to), updated_balance_to);711 if let Some(account_balance_from) = account_balance_from {712 <AccountBalance<T>>::insert((collection.id, from), account_balance_from);713 <Owned<T>>::remove((collection.id, from, token));714 }715 if let Some(account_balance_to) = account_balance_to {716 <AccountBalance<T>>::insert((collection.id, to), account_balance_to);717 <Owned<T>>::insert((collection.id, to, token), true);718 }719 }720721 <PalletEvm<T>>::deposit_log(722 ERC20Events::Transfer {723 from: *from.as_eth(),724 to: *to.as_eth(),725 value: amount.into(),726 }727 .to_log(T::EvmTokenAddressMapping::token_to_address(728 collection.id,729 token,730 )),731 );732733 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(734 collection.id,735 token,736 from.clone(),737 to.clone(),738 amount,739 ));740741 let total_supply = <TotalSupply<T>>::get((collection.id, token));742743 if amount == total_supply {744 // if token was fully owned by `from` and will be fully owned by `to` after transfer745 <PalletEvm<T>>::deposit_log(746 ERC721Events::Transfer {747 from: *from.as_eth(),748 to: *to.as_eth(),749 token_id: token.into(),750 }751 .to_log(collection_id_to_address(collection.id)),752 );753 } else if let Some(updated_balance_to) = updated_balance_to {754 // if `from` not equals `to`. This condition is needed to avoid sending event755 // when `from` fully owns token and sends part of token pieces to itself.756 if initial_balance_from == total_supply {757 // if token was fully owned by `from` and will be only partially owned by `to`758 // and `from` after transfer759 <PalletEvm<T>>::deposit_log(760 ERC721Events::Transfer {761 from: *from.as_eth(),762 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,763 token_id: token.into(),764 }765 .to_log(collection_id_to_address(collection.id)),766 );767 } else if updated_balance_to == total_supply {768 // if token was partially owned by `from` and will be fully owned by `to` after transfer769 <PalletEvm<T>>::deposit_log(770 ERC721Events::Transfer {771 from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,772 to: *to.as_eth(),773 token_id: token.into(),774 }775 .to_log(collection_id_to_address(collection.id)),776 );777 }778 }779780 Ok(())781 }782783 /// Batched operation to create multiple RFT tokens.784 ///785 /// Same as `create_item` but creates multiple tokens.786 ///787 /// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.788 pub fn create_multiple_items(789 collection: &RefungibleHandle<T>,790 sender: &T::CrossAccountId,791 data: Vec<CreateItemData<T>>,792 nesting_budget: &dyn Budget,793 ) -> DispatchResult {794 if !collection.is_owner_or_admin(sender) {795 ensure!(796 collection.permissions.mint_mode(),797 <CommonError<T>>::PublicMintingNotAllowed798 );799 collection.check_allowlist(sender)?;800801 for item in data.iter() {802 for user in item.users.keys() {803 collection.check_allowlist(user)?;804 }805 }806 }807808 for item in data.iter() {809 for (owner, _) in item.users.iter() {810 <PalletCommon<T>>::ensure_correct_receiver(owner)?;811 }812 }813814 // Total pieces per tokens815 let totals = data816 .iter()817 .map(|data| {818 Ok(data819 .users820 .iter()821 .map(|u| u.1)822 .try_fold(0u128, |acc, v| acc.checked_add(*v))823 .ok_or(ArithmeticError::Overflow)?)824 })825 .collect::<Result<Vec<_>, DispatchError>>()?;826 for total in &totals {827 ensure!(828 *total <= MAX_REFUNGIBLE_PIECES,829 <Error<T>>::WrongRefungiblePieces830 );831 }832833 let first_token_id = <TokensMinted<T>>::get(collection.id);834 let tokens_minted = first_token_id835 .checked_add(data.len() as u32)836 .ok_or(ArithmeticError::Overflow)?;837 ensure!(838 tokens_minted < collection.limits.token_limit(),839 <CommonError<T>>::CollectionTokenLimitExceeded840 );841842 let mut balances = BTreeMap::new();843 for data in &data {844 for owner in data.users.keys() {845 let balance = balances846 .entry(owner)847 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));848 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;849850 ensure!(851 *balance <= collection.limits.account_token_ownership_limit(),852 <CommonError<T>>::AccountTokenLimitExceeded,853 );854 }855 }856857 for (i, token) in data.iter().enumerate() {858 let token_id = TokenId(first_token_id + i as u32 + 1);859 for (to, _) in token.users.iter() {860 <PalletStructure<T>>::check_nesting(861 sender,862 to,863 collection.id,864 token_id,865 nesting_budget,866 )?;867 }868 }869870 // =========871872 let mut property_writer = pallet_common::NewTokenPropertyWriter::new(collection, sender);873874 with_transaction(|| {875 for (i, data) in data.iter().enumerate() {876 let token_id = first_token_id + i as u32 + 1;877 <TotalSupply<T>>::insert((collection.id, token_id), totals[i]);878879 let token = TokenId(token_id);880881 let mut mint_target_is_sender = true;882 for (user, amount) in data.users.iter() {883 if *amount == 0 {884 continue;885 }886887 mint_target_is_sender = mint_target_is_sender && sender.conv_eq(user);888889 <Balance<T>>::insert((collection.id, token_id, &user), amount);890 <Owned<T>>::insert((collection.id, &user, token), true);891 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(892 user,893 collection.id,894 token,895 );896 }897898 if let Err(e) = property_writer.write_token_properties(899 mint_target_is_sender,900 token,901 data.properties.clone().into_iter(),902 erc::ERC721TokenEvent::TokenChanged {903 token_id: token.into(),904 }905 .to_log(T::ContractAddress::get()),906 ) {907 return TransactionOutcome::Rollback(Err(e));908 }909 }910 TransactionOutcome::Commit(Ok(()))911 })?;912913 <TokensMinted<T>>::insert(collection.id, tokens_minted);914915 for (account, balance) in balances {916 <AccountBalance<T>>::insert((collection.id, account), balance);917 }918919 for (i, token) in data.into_iter().enumerate() {920 let token_id = first_token_id + i as u32 + 1;921922 let receivers = token923 .users924 .into_iter()925 .filter(|(_, amount)| *amount > 0)926 .collect::<Vec<_>>();927928 if let [(user, _)] = receivers.as_slice() {929 // if there is exactly one receiver930 <PalletEvm<T>>::deposit_log(931 ERC721Events::Transfer {932 from: H160::default(),933 to: *user.as_eth(),934 token_id: token_id.into(),935 }936 .to_log(collection_id_to_address(collection.id)),937 );938 } else if let [_, ..] = receivers.as_slice() {939 // if there is more than one receiver940 <PalletEvm<T>>::deposit_log(941 ERC721Events::Transfer {942 from: H160::default(),943 to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,944 token_id: token_id.into(),945 }946 .to_log(collection_id_to_address(collection.id)),947 );948 }949950 for (user, amount) in receivers.into_iter() {951 <PalletEvm<T>>::deposit_log(952 ERC20Events::Transfer {953 from: H160::default(),954 to: *user.as_eth(),955 value: amount.into(),956 }957 .to_log(T::EvmTokenAddressMapping::token_to_address(958 collection.id,959 TokenId(token_id),960 )),961 );962 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(963 collection.id,964 TokenId(token_id),965 user,966 amount,967 ));968 }969 }970 Ok(())971 }972973 pub fn set_allowance_unchecked(974 collection: &RefungibleHandle<T>,975 sender: &T::CrossAccountId,976 spender: &T::CrossAccountId,977 token: TokenId,978 amount: u128,979 ) {980 if amount == 0 {981 <Allowance<T>>::remove((collection.id, token, sender, spender));982 } else {983 <Allowance<T>>::insert((collection.id, token, sender, spender), amount);984 }985986 <PalletEvm<T>>::deposit_log(987 ERC20Events::Approval {988 owner: *sender.as_eth(),989 spender: *spender.as_eth(),990 value: amount.into(),991 }992 .to_log(T::EvmTokenAddressMapping::token_to_address(993 collection.id,994 token,995 )),996 );997 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(998 collection.id,999 token,1000 sender.clone(),1001 spender.clone(),1002 amount,1003 ))1004 }10051006 /// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1007 ///1008 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1009 pub fn set_allowance(1010 collection: &RefungibleHandle<T>,1011 sender: &T::CrossAccountId,1012 spender: &T::CrossAccountId,1013 token: TokenId,1014 amount: u128,1015 ) -> DispatchResult {1016 if collection.permissions.access() == AccessMode::AllowList {1017 collection.check_allowlist(sender)?;1018 collection.check_allowlist(spender)?;1019 }10201021 <PalletCommon<T>>::ensure_correct_receiver(spender)?;10221023 if <Balance<T>>::get((collection.id, token, sender)) < amount {1024 ensure!(1025 collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1026 <CommonError<T>>::CantApproveMoreThanOwned1027 );1028 }10291030 // =========10311032 Self::set_allowance_unchecked(collection, sender, spender, token, amount);1033 Ok(())1034 }10351036 /// Set allowance to spend from sender's eth mirror1037 ///1038 /// - `from`: Address of sender's eth mirror.1039 /// - `to`: Adress of spender.1040 /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1041 pub fn set_allowance_from(1042 collection: &RefungibleHandle<T>,1043 sender: &T::CrossAccountId,1044 from: &T::CrossAccountId,1045 to: &T::CrossAccountId,1046 token_id: TokenId,1047 amount: u128,1048 ) -> DispatchResult {1049 if collection.permissions.access() == AccessMode::AllowList {1050 collection.check_allowlist(sender)?;1051 collection.check_allowlist(from)?;1052 collection.check_allowlist(to)?;1053 }10541055 <PalletCommon<T>>::ensure_correct_receiver(to)?;10561057 ensure!(1058 sender.conv_eq(from),1059 <CommonError<T>>::AddressIsNotEthMirror1060 );10611062 if <Balance<T>>::get((collection.id, token_id, from)) < amount {1063 ensure!(1064 collection.limits.owner_can_transfer()1065 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1066 && Self::token_exists(collection, token_id),1067 <CommonError<T>>::CantApproveMoreThanOwned1068 );1069 }10701071 // =========10721073 Self::set_allowance_unchecked(collection, from, to, token_id, amount);1074 Ok(())1075 }10761077 /// Returns allowance, which should be set after transaction1078 fn check_allowed(1079 collection: &RefungibleHandle<T>,1080 spender: &T::CrossAccountId,1081 from: &T::CrossAccountId,1082 token: TokenId,1083 amount: u128,1084 nesting_budget: &dyn Budget,1085 ) -> Result<Option<u128>, DispatchError> {1086 if spender.conv_eq(from) {1087 return Ok(None);1088 }1089 if collection.permissions.access() == AccessMode::AllowList {1090 // `from`, `to` checked in [`transfer`]1091 collection.check_allowlist(spender)?;1092 }10931094 if collection.ignores_token_restrictions(spender) {1095 return Ok(Self::compute_allowance_decrease(1096 collection, token, from, spender, amount,1097 ));1098 }10991100 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1101 // TODO: should collection owner be allowed to perform this transfer?1102 ensure!(1103 <PalletStructure<T>>::check_indirectly_owned(1104 spender.clone(),1105 source.0,1106 source.1,1107 None,1108 nesting_budget1109 )?,1110 <CommonError<T>>::ApprovedValueTooLow,1111 );1112 return Ok(None);1113 }11141115 let allowance = Self::compute_allowance_decrease(collection, token, from, spender, amount);1116 if allowance.is_some() {1117 return Ok(allowance);1118 }11191120 // Allowance (if any) would be reduced if spender is also wallet operator1121 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1122 return Ok(allowance);1123 }11241125 Err(<CommonError<T>>::ApprovedValueTooLow.into())1126 }11271128 /// Returns `Some(amount)` if the `spender` have allowance to spend this amount.1129 /// Otherwise, it returns `None`.1130 fn compute_allowance_decrease(1131 collection: &RefungibleHandle<T>,1132 token: TokenId,1133 from: &T::CrossAccountId,1134 spender: &T::CrossAccountId,1135 amount: u128,1136 ) -> Option<u128> {1137 <Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1138 }11391140 /// Transfer RFT token pieces from one account to another.1141 ///1142 /// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1143 /// The owner should set allowance for the spender to transfer pieces.1144 ///1145 /// [`transfer`]: struct.Pallet.html#method.transfer1146 pub fn transfer_from(1147 collection: &RefungibleHandle<T>,1148 spender: &T::CrossAccountId,1149 from: &T::CrossAccountId,1150 to: &T::CrossAccountId,1151 token: TokenId,1152 amount: u128,1153 nesting_budget: &dyn Budget,1154 ) -> DispatchResult {1155 let allowance =1156 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11571158 // =========11591160 Self::transfer_internal(collection, spender, from, to, token, amount, nesting_budget)?;1161 if let Some(allowance) = allowance {1162 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1163 }1164 Ok(())1165 }11661167 /// Burn RFT token pieces from the account.1168 ///1169 /// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1170 /// set allowance for the spender to burn pieces1171 ///1172 /// [`burn`]: struct.Pallet.html#method.burn1173 pub fn burn_from(1174 collection: &RefungibleHandle<T>,1175 spender: &T::CrossAccountId,1176 from: &T::CrossAccountId,1177 token: TokenId,1178 amount: u128,1179 nesting_budget: &dyn Budget,1180 ) -> DispatchResult {1181 let allowance =1182 Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11831184 // =========11851186 Self::burn(collection, from, token, amount)?;1187 if let Some(allowance) = allowance {1188 Self::set_allowance_unchecked(collection, from, spender, token, allowance);1189 }1190 Ok(())1191 }11921193 /// Create RFT token.1194 ///1195 /// The sender should be the owner/admin of the collection or collection should be configured1196 /// to allow public minting.1197 ///1198 /// - `data`: Contains list of users who will become the owners of the token pieces and amount1199 /// of token pieces they will receive.1200 pub fn create_item(1201 collection: &RefungibleHandle<T>,1202 sender: &T::CrossAccountId,1203 data: CreateItemData<T>,1204 nesting_budget: &dyn Budget,1205 ) -> DispatchResult {1206 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1207 }12081209 /// Repartition RFT token.1210 ///1211 /// `repartition` will set token balance of the sender and total amount of token pieces.1212 /// Sender should own all of the token pieces. `repartition' could be done even if some1213 /// token pieces were burned before.1214 ///1215 /// - `amount`: Total amount of token pieces that the token will have after `repartition`.1216 pub fn repartition(1217 collection: &RefungibleHandle<T>,1218 owner: &T::CrossAccountId,1219 token: TokenId,1220 amount: u128,1221 ) -> DispatchResult {1222 ensure!(1223 amount <= MAX_REFUNGIBLE_PIECES,1224 <Error<T>>::WrongRefungiblePieces1225 );1226 ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1227 // Ensure user owns all pieces1228 let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1229 let balance = <Balance<T>>::get((collection.id, token, owner));1230 ensure!(1231 total_pieces == balance,1232 <Error<T>>::RepartitionWhileNotOwningAllPieces1233 );12341235 <Balance<T>>::insert((collection.id, token, owner), amount);1236 <TotalSupply<T>>::insert((collection.id, token), amount);12371238 match total_pieces.cmp(&amount) {1239 Ordering::Less => {1240 let mint_amount = amount - total_pieces;1241 <PalletEvm<T>>::deposit_log(1242 ERC20Events::Transfer {1243 from: H160::default(),1244 to: *owner.as_eth(),1245 value: mint_amount.into(),1246 }1247 .to_log(T::EvmTokenAddressMapping::token_to_address(1248 collection.id,1249 token,1250 )),1251 );1252 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1253 collection.id,1254 token,1255 owner.clone(),1256 mint_amount,1257 ));1258 }1259 Ordering::Greater => {1260 let burn_amount = total_pieces - amount;1261 <PalletEvm<T>>::deposit_log(1262 ERC20Events::Transfer {1263 from: *owner.as_eth(),1264 to: H160::default(),1265 value: burn_amount.into(),1266 }1267 .to_log(T::EvmTokenAddressMapping::token_to_address(1268 collection.id,1269 token,1270 )),1271 );1272 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1273 collection.id,1274 token,1275 owner.clone(),1276 burn_amount,1277 ));1278 }1279 Ordering::Equal => {}1280 }12811282 Ok(())1283 }12841285 fn token_owner(1286 collection_id: CollectionId,1287 token_id: TokenId,1288 ) -> Result<T::CrossAccountId, TokenOwnerError> {1289 let mut owner = None;1290 let mut count = 0;1291 for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1292 count += 1;1293 if count > 1 {1294 return Err(TokenOwnerError::MultipleOwners);1295 }1296 owner = Some(key);1297 }1298 owner.ok_or(TokenOwnerError::NotFound)1299 }13001301 fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1302 <TotalSupply<T>>::try_get((collection_id, token_id)).ok()1303 }13041305 pub fn set_collection_properties(1306 collection: &RefungibleHandle<T>,1307 sender: &T::CrossAccountId,1308 properties: Vec<Property>,1309 ) -> DispatchResult {1310 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1311 }13121313 pub fn delete_collection_properties(1314 collection: &RefungibleHandle<T>,1315 sender: &T::CrossAccountId,1316 property_keys: Vec<PropertyKey>,1317 ) -> DispatchResult {1318 <PalletCommon<T>>::delete_collection_properties(1319 collection,1320 sender,1321 property_keys.into_iter(),1322 )1323 }13241325 pub fn set_token_property_permissions(1326 collection: &RefungibleHandle<T>,1327 sender: &T::CrossAccountId,1328 property_permissions: Vec<PropertyKeyPermission>,1329 ) -> DispatchResult {1330 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1331 }13321333 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1334 <PalletCommon<T>>::property_permissions(collection_id)1335 }13361337 pub fn set_scoped_token_property_permissions(1338 collection: &RefungibleHandle<T>,1339 sender: &T::CrossAccountId,1340 scope: PropertyScope,1341 property_permissions: Vec<PropertyKeyPermission>,1342 ) -> DispatchResult {1343 <PalletCommon<T>>::set_scoped_token_property_permissions(1344 collection,1345 sender,1346 scope,1347 property_permissions,1348 )1349 }13501351 /// Returns 10 token in no particular order.1352 ///1353 /// There is no direct way to get token holders in ascending order,1354 /// since `iter_prefix` returns values in no particular order.1355 /// Therefore, getting the 10 largest holders with a large value of holders1356 /// can lead to impact memory allocation + sorting with `n * log (n)`.1357 pub fn token_owners(1358 collection_id: CollectionId,1359 token: TokenId,1360 ) -> Option<Vec<T::CrossAccountId>> {1361 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1362 .map(|(owner, _amount)| owner)1363 .take(10)1364 .collect();13651366 if res.is_empty() {1367 None1368 } else {1369 Some(res)1370 }1371 }13721373 /// Sets or unsets the approval of a given operator.1374 ///1375 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1376 /// - `owner`: Token owner1377 /// - `operator`: Operator1378 /// - `approve`: Should operator status be granted or revoked?1379 pub fn set_allowance_for_all(1380 collection: &RefungibleHandle<T>,1381 owner: &T::CrossAccountId,1382 spender: &T::CrossAccountId,1383 approve: bool,1384 ) -> DispatchResult {1385 <PalletCommon<T>>::set_allowance_for_all(1386 collection,1387 owner,1388 spender,1389 approve,1390 || <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),1391 ERC721Events::ApprovalForAll {1392 owner: *owner.as_eth(),1393 operator: *spender.as_eth(),1394 approved: approve,1395 }1396 .to_log(collection_id_to_address(collection.id)),1397 )1398 }13991400 /// Tells whether the given `owner` approves the `operator`.1401 pub fn allowance_for_all(1402 collection: &RefungibleHandle<T>,1403 owner: &T::CrossAccountId,1404 spender: &T::CrossAccountId,1405 ) -> bool {1406 <CollectionAllowance<T>>::get((collection.id, owner, spender))1407 }14081409 pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1410 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1411 if let Some(properties) = properties {1412 properties.recompute_consumed_space();1413 }1414 });14151416 Ok(())1417 }1418}primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -380,7 +380,7 @@
pub struct CollectionFlags {
/// Reserved flag
#[bondrewd(bits = "0..1")]
- pub reserved_0: bool,
+ pub foreign: bool,
/// Supports ERC721Metadata
#[bondrewd(bits = "1..2")]
pub erc721metadata: bool,
@@ -395,7 +395,7 @@
impl CollectionFlags {
pub fn is_allowed_for_user(self) -> bool {
- !self.reserved_0 && !self.external && self.reserved == 0
+ !self.foreign && !self.external && self.reserved == 0
}
}
@@ -461,6 +461,8 @@
#[derive(Debug, Encode, Decode, Clone, PartialEq, TypeInfo, Serialize, Deserialize)]
pub struct RpcCollectionFlags {
+ /// Is collection is foreign.
+ pub foreign: bool,
/// Collection supports ERC721Metadata.
pub erc721metadata: bool,
}
@@ -503,7 +505,7 @@
pub read_only: bool,
/// Extra collection flags
- #[version(2.., upper(RpcCollectionFlags {erc721metadata: false}))]
+ #[version(2.., upper(RpcCollectionFlags {foreign: false, erc721metadata: false}))]
pub flags: RpcCollectionFlags,
}
@@ -540,6 +542,7 @@
read_only: true,
flags: RpcCollectionFlags {
+ foreign: false,
erc721metadata: false,
},
}
runtime/common/config/pallets/foreign_asset.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/foreign_asset.rs
+++ b/runtime/common/config/pallets/foreign_asset.rs
@@ -1,4 +1,6 @@
use frame_support::{parameter_types, PalletId};
+#[cfg(not(feature = "governance"))]
+use frame_system::EnsureRoot;
use pallet_evm::account::CrossAccountId;
use sp_core::H160;
use staging_xcm::prelude::*;
@@ -6,10 +8,6 @@
#[cfg(feature = "governance")]
use crate::runtime_common::config::governance;
-
-#[cfg(not(feature = "governance"))]
-use frame_system::EnsureRoot;
-
use crate::{
runtime_common::config::{
ethereum::CrossAccountId as ConfigCrossAccountId,
runtime/common/dispatch.rsdiffbeforeafterboth--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -66,9 +66,10 @@
}
}
- fn create(
+ fn create_internal(
sender: T::CrossAccountId,
payer: Option<T::CrossAccountId>,
+ is_special_collection: bool,
data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError> {
match data.mode {
@@ -86,7 +87,7 @@
_ => {}
};
- <PalletCommon<T>>::init_collection(sender, payer, data)
+ <PalletCommon<T>>::init_collection(sender, payer, is_special_collection, data)
}
fn destroy(sender: T::CrossAccountId, collection_id: CollectionId) -> DispatchResult {