difftreelog
refactor remove redundant foreign flag, use foreign-assets pallet instead
in: master
8 files changed
pallets/balances-adapter/src/common.rsdiffbeforeafterboth--- a/pallets/balances-adapter/src/common.rs
+++ b/pallets/balances-adapter/src/common.rs
@@ -368,10 +368,6 @@
}
impl<T: Config> pallet_common::XcmExtensions<T> for NativeFungibleHandle<T> {
- fn is_foreign(&self) -> bool {
- false
- }
-
fn create_item_internal(
&self,
_depositor: &<T>::CrossAccountId,
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1088,7 +1088,6 @@
read_only: flags.external,
flags: RpcCollectionFlags {
- foreign: flags.foreign,
erc721metadata: flags.erc721metadata,
},
})
@@ -1128,17 +1127,17 @@
/// Create new collection.
///
/// * `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.
- /// * `flags` - Extra flags to store.
pub fn init_collection(
owner: T::CrossAccountId,
- payer: T::CrossAccountId,
+ payer: Option<T::CrossAccountId>,
data: CreateCollectionData<T::CrossAccountId>,
) -> Result<CollectionId, DispatchError> {
ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);
// Take a (non-refundable) deposit of collection creation
- {
+ if let Some(payer) = payer {
let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();
imbalance.subsume(<T as Config>::Currency::deposit(
&T::TreasuryAccountId::get(),
@@ -1153,16 +1152,6 @@
}
Self::init_collection_internal(owner, data)
- }
-
- /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.
- pub fn init_foreign_collection(
- owner: T::CrossAccountId,
- mut data: CreateCollectionData<T::CrossAccountId>,
- ) -> Result<CollectionId, DispatchError> {
- data.flags.foreign = true;
- let id = Self::init_collection_internal(owner, data)?;
- Ok(id)
}
fn init_collection_internal(
@@ -2348,9 +2337,6 @@
where
T: Config,
{
- /// Is the collection a foreign one?
- fn is_foreign(&self) -> bool;
-
/// Does the token have children?
fn token_has_children(&self, _token: TokenId) -> bool {
false
pallets/foreign-assets/src/lib.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -304,11 +304,10 @@
/// If the `asset_instance` is a part of a local collection,
/// the function will return either `Ok(Some(<token ID>))` or an error if the token is not found.
fn asset_instance_to_token_id(
- xcm_ext: &dyn XcmExtensions<T>,
collection_id: CollectionId,
asset_instance: &AssetInstance,
) -> Result<Option<TokenId>, XcmError> {
- if xcm_ext.is_foreign() {
+ if <CollectionToForeignReserveLocation<T>>::contains_key(collection_id) {
Ok(Self::foreign_reserve_asset_instance_to_token_id(
collection_id,
asset_instance,
@@ -363,7 +362,7 @@
to: T::CrossAccountId,
) -> XcmResult {
let deposit_result = if let Some(token_id) =
- Self::asset_instance_to_token_id(xcm_ext, collection_id, asset_instance)?
+ Self::asset_instance_to_token_id(collection_id, asset_instance)?
{
let depositor = &Self::pallet_account();
let from = depositor;
@@ -389,7 +388,7 @@
asset_instance: &AssetInstance,
from: T::CrossAccountId,
) -> XcmResult {
- let token_id = Self::asset_instance_to_token_id(xcm_ext, collection_id, &asset_instance)?
+ let token_id = Self::asset_instance_to_token_id(collection_id, &asset_instance)?
.ok_or(XcmError::AssetNotFound)?;
if xcm_ext.token_has_children(token_id) {
@@ -517,9 +516,8 @@
}
Fungibility::NonFungible(asset_instance) => {
- token_id =
- Self::asset_instance_to_token_id(xcm_ext, collection_id, &asset_instance)?
- .ok_or(XcmError::AssetNotFound)?;
+ token_id = Self::asset_instance_to_token_id(collection_id, &asset_instance)?
+ .ok_or(XcmError::AssetNotFound)?;
amount = 1;
map_error = |_| XcmError::FailedToTransactAsset("nonfungible item transfer failed")
@@ -542,17 +540,11 @@
if collection_id == NATIVE_FUNGIBLE_COLLECTION_ID {
Some(Here.into())
} else {
- let dispatch = T::CollectionDispatch::dispatch(collection_id).ok()?;
- let collection = dispatch.as_dyn();
- let xcm_ext = collection.xcm_extensions()?;
-
- if xcm_ext.is_foreign() {
- <Pallet<T>>::collection_to_foreign_reserve_location(collection_id)
- } else {
+ <Pallet<T>>::collection_to_foreign_reserve_location(collection_id).or_else(|| {
T::SelfLocation::get()
.pushed_with_interior(GeneralIndex(collection_id.0.into()))
.ok()
- }
+ })
}
}
}
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -459,10 +459,6 @@
}
impl<T: Config> XcmExtensions<T> for FungibleHandle<T> {
- fn is_foreign(&self) -> bool {
- self.flags.foreign
- }
-
fn create_item_internal(
&self,
depositor: &<T>::CrossAccountId,
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -572,10 +572,6 @@
}
impl<T: Config> XcmExtensions<T> for NonfungibleHandle<T> {
- fn is_foreign(&self) -> bool {
- self.flags.foreign
- }
-
fn token_has_children(&self, token: TokenId) -> bool {
<Pallet<T>>::token_has_children(self.id, token)
}
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, 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}primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -378,9 +378,9 @@
#[derive(AbiCoderFlags, Bitfields, Clone, Copy, PartialEq, Eq, Debug, Default)]
#[bondrewd(enforce_bytes = 1)]
pub struct CollectionFlags {
- /// Tokens in foreign collections can be transferred, but not burnt
+ /// Reserved flag
#[bondrewd(bits = "0..1")]
- pub foreign: bool,
+ pub reserved_0: 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.foreign && !self.external && self.reserved == 0
+ !self.reserved_0 && !self.external && self.reserved == 0
}
}
@@ -461,8 +461,6 @@
#[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,
}
@@ -505,7 +503,7 @@
pub read_only: bool,
/// Extra collection flags
- #[version(2.., upper(RpcCollectionFlags {foreign: false, erc721metadata: false}))]
+ #[version(2.., upper(RpcCollectionFlags {erc721metadata: false}))]
pub flags: RpcCollectionFlags,
}
@@ -542,7 +540,6 @@
read_only: true,
flags: RpcCollectionFlags {
- foreign: false,
erc721metadata: false,
},
}
runtime/common/dispatch.rsdiffbeforeafterboth--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -86,7 +86,7 @@
_ => {}
};
- <PalletCommon<T>>::init_collection(sender, payer, data)
+ <PalletCommon<T>>::init_collection(sender, Some(payer), data)
}
fn create_foreign(
@@ -106,7 +106,8 @@
_ => {}
};
- <PalletCommon<T>>::init_foreign_collection(sender, data)
+ let payer = None;
+ <PalletCommon<T>>::init_collection(sender, payer, data)
}
fn destroy(sender: T::CrossAccountId, collection_id: CollectionId) -> DispatchResult {