difftreelog
fix use OptionQuery for TokenProperties
in: master
9 files changed
pallets/balances-adapter/src/common.rsdiffbeforeafterboth--- a/pallets/balances-adapter/src/common.rs
+++ b/pallets/balances-adapter/src/common.rs
@@ -172,18 +172,16 @@
fail!(<pallet_common::Error<T>>::UnsupportedOperation);
}
- fn get_token_properties_map(&self, _token_id: TokenId) -> up_data_structs::TokenProperties {
+ fn get_token_properties_raw(
+ &self,
+ _token_id: TokenId,
+ ) -> Option<up_data_structs::TokenProperties> {
// No token properties are defined on fungibles
- up_data_structs::TokenProperties::new()
+ None
}
- fn set_token_properties_map(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
- // No token properties are defined on fungibles
- }
-
- fn properties_exist(&self, _token: TokenId) -> bool {
+ fn set_token_properties_raw(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
// No token properties are defined on fungibles
- false
}
fn set_token_property_permissions(
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -2098,18 +2098,13 @@
/// Get token properties raw map.
///
/// * `token_id` - The token which properties are needed.
- fn get_token_properties_map(&self, token_id: TokenId) -> TokenProperties;
+ fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;
/// Set token properties raw map.
///
/// * `token_id` - The token for which the properties are being set.
/// * `map` - The raw map containing the token's properties.
- fn set_token_properties_map(&self, token_id: TokenId, map: TokenProperties);
-
- /// Whether the given token has properties.
- ///
- /// * `token_id` - The token in question.
- fn properties_exist(&self, token: TokenId) -> bool;
+ fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);
/// Set token property permissions.
///
@@ -2590,7 +2585,7 @@
<PalletEvm<T>>::deposit_log(log);
self.collection
- .set_token_properties_map(token_id, stored_properties.into_inner());
+ .set_token_properties_raw(token_id, stored_properties.into_inner());
}
Ok(())
@@ -2624,7 +2619,7 @@
true
},
get_properties: |token_id| {
- debug_assert!(!collection.properties_exist(token_id));
+ debug_assert!(collection.get_token_properties_raw(token_id).is_none());
TokenProperties::new()
},
_phantom: PhantomData,
@@ -2686,7 +2681,11 @@
is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),
property_permissions: LazyValue::new(|| <Pallet<T>>::property_permissions(collection.id)),
check_token_exist: |token_id| collection.token_exists(token_id),
- get_properties: |token_id| collection.get_token_properties_map(token_id),
+ get_properties: |token_id| {
+ collection
+ .get_token_properties_raw(token_id)
+ .unwrap_or_default()
+ },
_phantom: PhantomData,
}
}
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -364,18 +364,16 @@
fail!(<Error<T>>::SettingPropertiesNotAllowed)
}
- fn get_token_properties_map(&self, _token_id: TokenId) -> up_data_structs::TokenProperties {
+ fn get_token_properties_raw(
+ &self,
+ _token_id: TokenId,
+ ) -> Option<up_data_structs::TokenProperties> {
// No token properties are defined on fungibles
- up_data_structs::TokenProperties::new()
+ None
}
- fn set_token_properties_map(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
- // No token properties are defined on fungibles
- }
-
- fn properties_exist(&self, _token: TokenId) -> bool {
+ fn set_token_properties_raw(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
// No token properties are defined on fungibles
- false
}
fn check_nesting(
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -265,12 +265,15 @@
)
}
- fn get_token_properties_map(&self, token_id: TokenId) -> up_data_structs::TokenProperties {
+ fn get_token_properties_raw(
+ &self,
+ token_id: TokenId,
+ ) -> Option<up_data_structs::TokenProperties> {
<TokenProperties<T>>::get((self.id, token_id))
}
- fn set_token_properties_map(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
- <TokenProperties<T>>::set((self.id, token_id), map)
+ fn set_token_properties_raw(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
+ <TokenProperties<T>>::insert((self.id, token_id), map)
}
fn set_token_property_permissions(
@@ -287,10 +290,6 @@
)
}
- fn properties_exist(&self, token: TokenId) -> bool {
- <TokenProperties<T>>::contains_key((self.id, token))
- }
-
fn burn_item(
&self,
sender: T::CrossAccountId,
@@ -482,13 +481,15 @@
}
fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {
- <Pallet<T>>::token_properties((self.id, token_id))
+ <Pallet<T>>::token_properties((self.id, token_id))?
.get(key)
.cloned()
}
fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {
- let properties = <Pallet<T>>::token_properties((self.id, token_id));
+ let Some(properties) = <Pallet<T>>::token_properties((self.id, token_id)) else {
+ return vec![];
+ };
keys.map(|keys| {
keys.into_iter()
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -272,7 +272,8 @@
.try_into()
.map_err(|_| "key too long")?;
- let props = <TokenProperties<T>>::get((self.id, token_id));
+ let props =
+ <TokenProperties<T>>::get((self.id, token_id)).ok_or("Token properties not found")?;
let prop = props.get(&key).ok_or("key not found")?;
Ok(prop.to_vec().into())
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -102,8 +102,8 @@
use up_data_structs::{
AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,
- PropertyKeyPermission, PropertyScope, TrySetProperty, TokenChild, AuxPropertyValue,
- PropertiesPermissionMap, TokenProperties as TokenPropertiesT,
+ PropertyKeyPermission, PropertyScope, TokenChild, AuxPropertyValue, PropertiesPermissionMap,
+ TokenProperties as TokenPropertiesT,
};
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_common::{
@@ -201,7 +201,7 @@
pub type TokenProperties<T: Config> = StorageNMap<
Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
Value = TokenPropertiesT,
- QueryKind = ValueQuery,
+ QueryKind = OptionQuery,
>;
/// Custom data of a token that is serialized to bytes,
@@ -340,40 +340,8 @@
/// - `token`: Token ID.
pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {
<TokenData<T>>::contains_key((collection.id, token))
- }
-
- /// Set the token property with the scope.
- ///
- /// - `property`: Contains key-value pair.
- pub fn set_scoped_token_property(
- collection_id: CollectionId,
- token_id: TokenId,
- scope: PropertyScope,
- property: Property,
- ) -> DispatchResult {
- TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {
- properties.try_scoped_set(scope, property.key, property.value)
- })
- .map_err(<CommonError<T>>::from)?;
-
- Ok(())
}
- /// Batch operation to set multiple properties with the same scope.
- pub fn set_scoped_token_properties(
- collection_id: CollectionId,
- token_id: TokenId,
- scope: PropertyScope,
- properties: impl Iterator<Item = Property>,
- ) -> DispatchResult {
- TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {
- stored_properties.try_scoped_set_from_iter(scope, properties)
- })
- .map_err(<CommonError<T>>::from)?;
-
- Ok(())
- }
-
/// Add or edit auxiliary data for the property.
///
/// - `f`: function that adds or edits auxiliary data.
@@ -1394,7 +1362,9 @@
pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {
<TokenProperties<T>>::mutate((collection.id, token), |properties| {
- properties.recompute_consumed_space();
+ if let Some(properties) = properties {
+ properties.recompute_consumed_space();
+ }
});
Ok(())
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -435,16 +435,15 @@
)
}
- fn get_token_properties_map(&self, token_id: TokenId) -> up_data_structs::TokenProperties {
+ fn get_token_properties_raw(
+ &self,
+ token_id: TokenId,
+ ) -> Option<up_data_structs::TokenProperties> {
<TokenProperties<T>>::get((self.id, token_id))
}
- fn set_token_properties_map(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
- <TokenProperties<T>>::set((self.id, token_id), map)
- }
-
- fn properties_exist(&self, token: TokenId) -> bool {
- <TokenProperties<T>>::contains_key((self.id, token))
+ fn set_token_properties_raw(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
+ <TokenProperties<T>>::insert((self.id, token_id), map)
}
fn check_nesting(
@@ -514,13 +513,15 @@
}
fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {
- <Pallet<T>>::token_properties((self.id, token_id))
+ <Pallet<T>>::token_properties((self.id, token_id))?
.get(key)
.cloned()
}
fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {
- let properties = <Pallet<T>>::token_properties((self.id, token_id));
+ let Some(properties) = <Pallet<T>>::token_properties((self.id, token_id)) else {
+ return vec![];
+ };
keys.map(|keys| {
keys.into_iter()
pallets/refungible/src/erc.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 Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use alloc::string::ToString;25use core::{26 char::{REPLACEMENT_CHARACTER, decode_utf16},27 convert::TryInto,28};29use evm_coder::{abi::AbiType, AbiCoder, ToLog, generate_stubgen, solidity_interface, types::*};30use frame_support::{BoundedBTreeMap, BoundedVec};31use pallet_common::{32 CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,33 Error as CommonError,34 erc::{CommonEvmHandler, CollectionCall, static_property::key},35 eth::{self, TokenUri},36};37use pallet_evm::{account::CrossAccountId, PrecompileHandle};38use pallet_evm_coder_substrate::{39 call, dispatch_to_evm,40 execution::{PreDispatch, Result, Error},41 frontier_contract,42};43use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};44use sp_core::{H160, U256, Get};45use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};46use up_data_structs::{47 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,48 PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,49};5051use crate::{52 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, TokenProperties,53 TokensMinted, TotalSupply, SelfWeightOf, weights::WeightInfo,54};5556frontier_contract! {57 macro_rules! RefungibleHandle_result {...}58 impl<T: Config> Contract for RefungibleHandle<T> {...}59}6061pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);6263/// Rft events.64#[derive(ToLog)]65pub enum ERC721TokenEvent {66 /// The token has been changed.67 TokenChanged {68 /// Token ID.69 #[indexed]70 token_id: U256,71 },72}7374/// Token minting parameters75#[derive(AbiCoder, Default, Debug)]76pub struct OwnerPieces {77 /// Minted token owner78 pub owner: eth::CrossAddress,79 /// Number of token pieces80 pub pieces: u128,81}8283/// Token minting parameters84#[derive(AbiCoder, Default, Debug)]85pub struct MintTokenData {86 /// Minted token owner and number of pieces87 pub owners: Vec<OwnerPieces>,88 /// Minted token properties89 pub properties: Vec<eth::Property>,90}9192/// @title A contract that allows to set and delete token properties and change token property permissions.93#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]94impl<T: Config> RefungibleHandle<T> {95 /// @notice Set permissions for token property.96 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.97 /// @param key Property key.98 /// @param isMutable Permission to mutate property.99 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.100 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.101 #[solidity(hide)]102 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]103 fn set_token_property_permission(104 &mut self,105 caller: Caller,106 key: String,107 is_mutable: bool,108 collection_admin: bool,109 token_owner: bool,110 ) -> Result<()> {111 let caller = T::CrossAccountId::from_eth(caller);112 <Pallet<T>>::set_token_property_permissions(113 self,114 &caller,115 vec![PropertyKeyPermission {116 key: <Vec<u8>>::from(key)117 .try_into()118 .map_err(|_| "too long key")?,119 permission: PropertyPermission {120 mutable: is_mutable,121 collection_admin,122 token_owner,123 },124 }],125 )126 .map_err(dispatch_to_evm::<T>)127 }128129 /// @notice Set permissions for token property.130 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.131 /// @param permissions Permissions for keys.132 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]133 fn set_token_property_permissions(134 &mut self,135 caller: Caller,136 permissions: Vec<eth::TokenPropertyPermission>,137 ) -> Result<()> {138 let caller = T::CrossAccountId::from_eth(caller);139 let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;140141 <Pallet<T>>::set_token_property_permissions(self, &caller, perms)142 .map_err(dispatch_to_evm::<T>)143 }144145 /// @notice Get permissions for token properties.146 fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {147 let perms = <Pallet<T>>::token_property_permission(self.id);148 Ok(perms149 .into_iter()150 .map(eth::TokenPropertyPermission::from)151 .collect())152 }153154 /// @notice Set token property value.155 /// @dev Throws error if `msg.sender` has no permission to edit the property.156 /// @param tokenId ID of the token.157 /// @param key Property key.158 /// @param value Property value.159 #[solidity(hide)]160 #[weight(<SelfWeightOf<T>>::set_token_properties(1))]161 fn set_property(162 &mut self,163 caller: Caller,164 token_id: U256,165 key: String,166 value: Bytes,167 ) -> Result<()> {168 let caller = T::CrossAccountId::from_eth(caller);169 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;170 let key = <Vec<u8>>::from(key)171 .try_into()172 .map_err(|_| "key too long")?;173 let value = value.0.try_into().map_err(|_| "value too long")?;174175 let nesting_budget = self176 .recorder177 .weight_calls_budget(<StructureWeight<T>>::find_parent());178179 <Pallet<T>>::set_token_property(180 self,181 &caller,182 TokenId(token_id),183 Property { key, value },184 &nesting_budget,185 )186 .map_err(dispatch_to_evm::<T>)187 }188189 /// @notice Set token properties value.190 /// @dev Throws error if `msg.sender` has no permission to edit the property.191 /// @param tokenId ID of the token.192 /// @param properties settable properties193 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]194 fn set_properties(195 &mut self,196 caller: Caller,197 token_id: U256,198 properties: Vec<eth::Property>,199 ) -> Result<()> {200 let caller = T::CrossAccountId::from_eth(caller);201 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;202203 let nesting_budget = self204 .recorder205 .weight_calls_budget(<StructureWeight<T>>::find_parent());206207 let properties = properties208 .into_iter()209 .map(eth::Property::try_into)210 .collect::<Result<Vec<_>>>()?;211212 <Pallet<T>>::set_token_properties(213 self,214 &caller,215 TokenId(token_id),216 properties.into_iter(),217 &nesting_budget,218 )219 .map_err(dispatch_to_evm::<T>)220 }221222 /// @notice Delete token property value.223 /// @dev Throws error if `msg.sender` has no permission to edit the property.224 /// @param tokenId ID of the token.225 /// @param key Property key.226 #[solidity(hide)]227 #[weight(<SelfWeightOf<T>>::delete_token_properties(1))]228 fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {229 let caller = T::CrossAccountId::from_eth(caller);230 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;231 let key = <Vec<u8>>::from(key)232 .try_into()233 .map_err(|_| "key too long")?;234235 let nesting_budget = self236 .recorder237 .weight_calls_budget(<StructureWeight<T>>::find_parent());238239 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)240 .map_err(dispatch_to_evm::<T>)241 }242243 /// @notice Delete token properties value.244 /// @dev Throws error if `msg.sender` has no permission to edit the property.245 /// @param tokenId ID of the token.246 /// @param keys Properties key.247 #[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]248 fn delete_properties(249 &mut self,250 token_id: U256,251 caller: Caller,252 keys: Vec<String>,253 ) -> Result<()> {254 let caller = T::CrossAccountId::from_eth(caller);255 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;256 let keys = keys257 .into_iter()258 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))259 .collect::<Result<Vec<_>>>()?;260261 let nesting_budget = self262 .recorder263 .weight_calls_budget(<StructureWeight<T>>::find_parent());264265 <Pallet<T>>::delete_token_properties(266 self,267 &caller,268 TokenId(token_id),269 keys.into_iter(),270 &nesting_budget,271 )272 .map_err(dispatch_to_evm::<T>)273 }274275 /// @notice Get token property value.276 /// @dev Throws error if key not found277 /// @param tokenId ID of the token.278 /// @param key Property key.279 /// @return Property value bytes280 fn property(&self, token_id: U256, key: String) -> Result<Bytes> {281 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;282 let key = <Vec<u8>>::from(key)283 .try_into()284 .map_err(|_| "key too long")?;285286 let props = <TokenProperties<T>>::get((self.id, token_id));287 let prop = props.get(&key).ok_or("key not found")?;288289 Ok(prop.to_vec().into())290 }291}292293#[derive(ToLog)]294pub enum ERC721Events {295 /// @dev This event emits when NFTs are created (`from` == 0) and destroyed296 /// (`to` == 0). Exception: during contract creation, any number of RFTs297 /// may be created and assigned without emitting Transfer.298 Transfer {299 #[indexed]300 from: Address,301 #[indexed]302 to: Address,303 #[indexed]304 token_id: U256,305 },306 /// @dev Not supported307 Approval {308 #[indexed]309 owner: Address,310 #[indexed]311 approved: Address,312 #[indexed]313 token_id: U256,314 },315 /// @dev Not supported316 #[allow(dead_code)]317 ApprovalForAll {318 #[indexed]319 owner: Address,320 #[indexed]321 operator: Address,322 approved: bool,323 },324}325326/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension327/// @dev See https://eips.ethereum.org/EIPS/eip-721328#[solidity_interface(name = ERC721Metadata, enum(derive(PreDispatch)), expect_selector = 0x5b5e139f)]329impl<T: Config> RefungibleHandle<T>330where331 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,332{333 /// @notice A descriptive name for a collection of NFTs in this contract334 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`335 #[solidity(hide, rename_selector = "name")]336 fn name_proxy(&self) -> Result<String> {337 self.name()338 }339340 /// @notice An abbreviated name for NFTs in this contract341 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`342 #[solidity(hide, rename_selector = "symbol")]343 fn symbol_proxy(&self) -> Result<String> {344 self.symbol()345 }346347 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.348 ///349 /// @dev If the token has a `url` property and it is not empty, it is returned.350 /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.351 /// If the collection property `baseURI` is empty or absent, return "" (empty string)352 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix353 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).354 ///355 /// @return token's const_metadata356 #[solidity(rename_selector = "tokenURI")]357 fn token_uri(&self, token_id: U256) -> Result<String> {358 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;359360 match get_token_property(self, token_id_u32, &key::url()).as_deref() {361 Err(_) | Ok("") => (),362 Ok(url) => {363 return Ok(url.into());364 }365 };366367 let base_uri =368 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())369 .map(BoundedVec::into_inner)370 .map(String::from_utf8)371 .transpose()372 .map_err(|e| {373 Error::Revert(alloc::format!(374 "Can not convert value \"baseURI\" to string with error \"{e}\""375 ))376 })?;377378 let base_uri = match base_uri.as_deref() {379 None | Some("") => {380 return Ok("".into());381 }382 Some(base_uri) => base_uri.into(),383 };384385 Ok(386 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {387 Err(_) | Ok("") => base_uri,388 Ok(suffix) => base_uri + suffix,389 },390 )391 }392}393394/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension395/// @dev See https://eips.ethereum.org/EIPS/eip-721396#[solidity_interface(name = ERC721Enumerable, enum(derive(PreDispatch)), expect_selector = 0x780e9d63)]397impl<T: Config> RefungibleHandle<T> {398 /// @notice Enumerate valid RFTs399 /// @param index A counter less than `totalSupply()`400 /// @return The token identifier for the `index`th NFT,401 /// (sort order not specified)402 fn token_by_index(&self, index: U256) -> U256 {403 index404 }405406 /// Not implemented407 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {408 // TODO: Not implemetable409 Err("not implemented".into())410 }411412 /// @notice Count RFTs tracked by this contract413 /// @return A count of valid RFTs tracked by this contract, where each one of414 /// them has an assigned and queryable owner not equal to the zero address415 fn total_supply(&self) -> Result<U256> {416 self.consume_store_reads(1)?;417 Ok(<Pallet<T>>::total_supply(self).into())418 }419}420421/// @title ERC-721 Non-Fungible Token Standard422/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md423#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]424impl<T: Config> RefungibleHandle<T> {425 /// @notice Count all RFTs assigned to an owner426 /// @dev RFTs assigned to the zero address are considered invalid, and this427 /// function throws for queries about the zero address.428 /// @param owner An address for whom to query the balance429 /// @return The number of RFTs owned by `owner`, possibly zero430 fn balance_of(&self, owner: Address) -> Result<U256> {431 self.consume_store_reads(1)?;432 let owner = T::CrossAccountId::from_eth(owner);433 let balance = <AccountBalance<T>>::get((self.id, owner));434 Ok(balance.into())435 }436437 /// @notice Find the owner of an RFT438 /// @dev RFTs assigned to zero address are considered invalid, and queries439 /// about them do throw.440 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for441 /// the tokens that are partially owned.442 /// @param tokenId The identifier for an RFT443 /// @return The address of the owner of the RFT444 fn owner_of(&self, token_id: U256) -> Result<Address> {445 self.consume_store_reads(2)?;446 let token = token_id.try_into()?;447 let owner = <Pallet<T>>::token_owner(self.id, token);448 owner449 .map(|address| *address.as_eth())450 .or_else(|err| match err {451 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),452 TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),453 })454 }455456 /// @dev Not implemented457 #[solidity(rename_selector = "safeTransferFrom")]458 fn safe_transfer_from_with_data(459 &mut self,460 _from: Address,461 _to: Address,462 _token_id: U256,463 _data: Bytes,464 ) -> Result<()> {465 // TODO: Not implemetable466 Err("not implemented".into())467 }468469 /// @dev Not implemented470 #[solidity(rename_selector = "safeTransferFrom")]471 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {472 // TODO: Not implemetable473 Err("not implemented".into())474 }475476 /// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE477 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE478 /// THEY MAY BE PERMANENTLY LOST479 /// @dev Throws unless `msg.sender` is the current owner or an authorized480 /// operator for this RFT. Throws if `from` is not the current owner. Throws481 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.482 /// Throws if RFT pieces have multiple owners.483 /// @param from The current owner of the NFT484 /// @param to The new owner485 /// @param tokenId The NFT to transfer486 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]487 fn transfer_from(488 &mut self,489 caller: Caller,490 from: Address,491 to: Address,492 token_id: U256,493 ) -> Result<()> {494 let caller = T::CrossAccountId::from_eth(caller);495 let from = T::CrossAccountId::from_eth(from);496 let to = T::CrossAccountId::from_eth(to);497 let token = token_id.try_into()?;498 let budget = self499 .recorder500 .weight_calls_budget(<StructureWeight<T>>::find_parent());501502 let balance = balance(self, token, &from)?;503 ensure_single_owner(self, token, balance)?;504505 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)506 .map_err(dispatch_to_evm::<T>)?;507508 Ok(())509 }510511 /// @dev Not implemented512 fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {513 Err("not implemented".into())514 }515516 /// @notice Sets or unsets the approval of a given operator.517 /// The `operator` is allowed to transfer all token pieces of the `caller` on their behalf.518 /// @param operator Operator519 /// @param approved Should operator status be granted or revoked?520 #[weight(<SelfWeightOf<T>>::set_allowance_for_all())]521 fn set_approval_for_all(522 &mut self,523 caller: Caller,524 operator: Address,525 approved: bool,526 ) -> Result<()> {527 let caller = T::CrossAccountId::from_eth(caller);528 let operator = T::CrossAccountId::from_eth(operator);529530 <Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)531 .map_err(dispatch_to_evm::<T>)?;532 Ok(())533 }534535 /// @dev Not implemented536 fn get_approved(&self, _token_id: U256) -> Result<Address> {537 // TODO: Not implemetable538 Err("not implemented".into())539 }540541 /// @notice Tells whether the given `owner` approves the `operator`.542 #[weight(<SelfWeightOf<T>>::allowance_for_all())]543 fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {544 let owner = T::CrossAccountId::from_eth(owner);545 let operator = T::CrossAccountId::from_eth(operator);546547 Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))548 }549}550551/// Returns amount of pieces of `token` that `owner` have552pub fn balance<T: Config>(553 collection: &RefungibleHandle<T>,554 token: TokenId,555 owner: &T::CrossAccountId,556) -> Result<u128> {557 collection.consume_store_reads(1)?;558 let balance = <Balance<T>>::get((collection.id, token, &owner));559 Ok(balance)560}561562/// Throws if `owner_balance` is lower than total amount of `token` pieces563pub fn ensure_single_owner<T: Config>(564 collection: &RefungibleHandle<T>,565 token: TokenId,566 owner_balance: u128,567) -> Result<()> {568 collection.consume_store_reads(1)?;569 let total_supply = <TotalSupply<T>>::get((collection.id, token));570571 if owner_balance == 0 {572 return Err(dispatch_to_evm::<T>(573 <CommonError<T>>::MustBeTokenOwner.into(),574 ));575 }576577 if total_supply != owner_balance {578 return Err("token has multiple owners".into());579 }580 Ok(())581}582583/// @title ERC721 Token that can be irreversibly burned (destroyed).584#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]585impl<T: Config> RefungibleHandle<T> {586 /// @notice Burns a specific ERC721 token.587 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized588 /// operator of the current owner.589 /// @param tokenId The RFT to approve590 #[weight(<SelfWeightOf<T>>::burn_item_fully())]591 fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {592 let caller = T::CrossAccountId::from_eth(caller);593 let token = token_id.try_into()?;594595 let balance = balance(self, token, &caller)?;596 ensure_single_owner(self, token, balance)?;597598 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;599 Ok(())600 }601}602603/// @title ERC721 minting logic.604#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]605impl<T: Config> RefungibleHandle<T> {606 /// @notice Function to mint a token.607 /// @param to The new owner608 /// @return uint256 The id of the newly minted token609 #[weight(<SelfWeightOf<T>>::create_item())]610 fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {611 let token_id: U256 = <TokensMinted<T>>::get(self.id)612 .checked_add(1)613 .ok_or("item id overflow")?614 .into();615 self.mint_check_id(caller, to, token_id)?;616 Ok(token_id)617 }618619 /// @notice Function to mint a token.620 /// @dev `tokenId` should be obtained with `nextTokenId` method,621 /// unlike standard, you can't specify it manually622 /// @param to The new owner623 /// @param tokenId ID of the minted RFT624 #[solidity(hide, rename_selector = "mint")]625 #[weight(<SelfWeightOf<T>>::create_item())]626 fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {627 let caller = T::CrossAccountId::from_eth(caller);628 let to = T::CrossAccountId::from_eth(to);629 let token_id: u32 = token_id.try_into()?;630 let budget = self631 .recorder632 .weight_calls_budget(<StructureWeight<T>>::find_parent());633634 if <TokensMinted<T>>::get(self.id)635 .checked_add(1)636 .ok_or("item id overflow")?637 != token_id638 {639 return Err("item id should be next".into());640 }641642 let users = [(to, 1)]643 .into_iter()644 .collect::<BTreeMap<_, _>>()645 .try_into()646 .unwrap();647 <Pallet<T>>::create_item(648 self,649 &caller,650 CreateItemData::<T> {651 users,652 properties: CollectionPropertiesVec::default(),653 },654 &budget,655 )656 .map_err(dispatch_to_evm::<T>)?;657658 Ok(true)659 }660661 /// @notice Function to mint token with the given tokenUri.662 /// @param to The new owner663 /// @param tokenUri Token URI that would be stored in the NFT properties664 /// @return uint256 The id of the newly minted token665 #[solidity(rename_selector = "mintWithTokenURI")]666 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]667 fn mint_with_token_uri(668 &mut self,669 caller: Caller,670 to: Address,671 token_uri: String,672 ) -> Result<U256> {673 let token_id: U256 = <TokensMinted<T>>::get(self.id)674 .checked_add(1)675 .ok_or("item id overflow")?676 .into();677 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;678 Ok(token_id)679 }680681 /// @notice Function to mint token with the given tokenUri.682 /// @dev `tokenId` should be obtained with `nextTokenId` method,683 /// unlike standard, you can't specify it manually684 /// @param to The new owner685 /// @param tokenId ID of the minted RFT686 /// @param tokenUri Token URI that would be stored in the RFT properties687 #[solidity(hide, rename_selector = "mintWithTokenURI")]688 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]689 fn mint_with_token_uri_check_id(690 &mut self,691 caller: Caller,692 to: Address,693 token_id: U256,694 token_uri: String,695 ) -> Result<bool> {696 let key = key::url();697 let permission = get_token_permission::<T>(self.id, &key)?;698 if !permission.collection_admin {699 return Err("Operation is not allowed".into());700 }701702 let caller = T::CrossAccountId::from_eth(caller);703 let to = T::CrossAccountId::from_eth(to);704 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;705 let budget = self706 .recorder707 .weight_calls_budget(<StructureWeight<T>>::find_parent());708709 if <TokensMinted<T>>::get(self.id)710 .checked_add(1)711 .ok_or("item id overflow")?712 != token_id713 {714 return Err("item id should be next".into());715 }716717 let mut properties = CollectionPropertiesVec::default();718 properties719 .try_push(Property {720 key,721 value: token_uri722 .into_bytes()723 .try_into()724 .map_err(|_| "token uri is too long")?,725 })726 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;727728 let users = [(to, 1)]729 .into_iter()730 .collect::<BTreeMap<_, _>>()731 .try_into()732 .unwrap();733 <Pallet<T>>::create_item(734 self,735 &caller,736 CreateItemData::<T> { users, properties },737 &budget,738 )739 .map_err(dispatch_to_evm::<T>)?;740 Ok(true)741 }742}743744fn get_token_property<T: Config>(745 collection: &CollectionHandle<T>,746 token_id: u32,747 key: &up_data_structs::PropertyKey,748) -> Result<String> {749 collection.consume_store_reads(1)?;750 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))751 .map_err(|_| Error::Revert("Token properties not found".into()))?;752 if let Some(property) = properties.get(key) {753 return Ok(String::from_utf8_lossy(property).into());754 }755756 Err("Property tokenURI not found".into())757}758759fn get_token_permission<T: Config>(760 collection_id: CollectionId,761 key: &PropertyKey,762) -> Result<PropertyPermission> {763 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)764 .map_err(|_| Error::Revert("No permissions for collection".into()))?;765 let a = token_property_permissions766 .get(key)767 .map(Clone::clone)768 .ok_or_else(|| {769 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();770 Error::Revert(alloc::format!("No permission for key {key}"))771 })?;772 Ok(a)773}774775/// @title Unique extensions for ERC721.776#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]777impl<T: Config> RefungibleHandle<T>778where779 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,780{781 /// @notice A descriptive name for a collection of NFTs in this contract782 fn name(&self) -> Result<String> {783 Ok(decode_utf16(self.name.iter().copied())784 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))785 .collect::<String>())786 }787788 /// @notice An abbreviated name for NFTs in this contract789 fn symbol(&self) -> Result<String> {790 Ok(String::from_utf8_lossy(&self.token_prefix).into())791 }792793 /// @notice A description for the collection.794 fn description(&self) -> Result<String> {795 Ok(decode_utf16(self.description.iter().copied())796 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))797 .collect::<String>())798 }799800 /// Returns the owner (in cross format) of the token.801 ///802 /// @param tokenId Id for the token.803 #[solidity(hide)]804 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {805 Self::owner_of_cross(self, token_id)806 }807808 /// Returns the owner (in cross format) of the token.809 ///810 /// @param tokenId Id for the token.811 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {812 Self::token_owner(self, token_id.try_into()?)813 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))814 .or_else(|err| match err {815 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),816 TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(817 ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,818 )),819 })820 }821822 /// @notice Count all RFTs assigned to an owner823 /// @param owner An cross address for whom to query the balance824 /// @return The number of RFTs owned by `owner`, possibly zero825 fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {826 self.consume_store_reads(1)?;827 let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));828 Ok(balance.into())829 }830831 /// Returns the token properties.832 ///833 /// @param tokenId Id for the token.834 /// @param keys Properties keys. Empty keys for all propertyes.835 /// @return Vector of properties key/value pairs.836 fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {837 let keys = keys838 .into_iter()839 .map(|key| {840 <Vec<u8>>::from(key)841 .try_into()842 .map_err(|_| Error::Revert("key too large".into()))843 })844 .collect::<Result<Vec<_>>>()?;845846 <Self as CommonCollectionOperations<T>>::token_properties(847 self,848 token_id.try_into()?,849 if keys.is_empty() { None } else { Some(keys) },850 )851 .into_iter()852 .map(eth::Property::try_from)853 .collect::<Result<Vec<_>>>()854 }855 /// @notice Transfer ownership of an RFT856 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`857 /// is the zero address. Throws if `tokenId` is not a valid RFT.858 /// Throws if RFT pieces have multiple owners.859 /// @param to The new owner860 /// @param tokenId The RFT to transfer861 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]862 fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {863 let caller = T::CrossAccountId::from_eth(caller);864 let to = T::CrossAccountId::from_eth(to);865 let token = token_id.try_into()?;866 let budget = self867 .recorder868 .weight_calls_budget(<StructureWeight<T>>::find_parent());869870 let balance = balance(self, token, &caller)?;871 ensure_single_owner(self, token, balance)?;872873 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)874 .map_err(dispatch_to_evm::<T>)?;875 Ok(())876 }877878 /// @notice Transfer ownership of an RFT879 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`880 /// is the zero address. Throws if `tokenId` is not a valid RFT.881 /// Throws if RFT pieces have multiple owners.882 /// @param to The new owner883 /// @param tokenId The RFT to transfer884 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]885 fn transfer_cross(886 &mut self,887 caller: Caller,888 to: eth::CrossAddress,889 token_id: U256,890 ) -> Result<()> {891 let caller = T::CrossAccountId::from_eth(caller);892 let to = to.into_sub_cross_account::<T>()?;893 let token = token_id.try_into()?;894 let budget = self895 .recorder896 .weight_calls_budget(<StructureWeight<T>>::find_parent());897898 let balance = balance(self, token, &caller)?;899 ensure_single_owner(self, token, balance)?;900901 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)902 .map_err(dispatch_to_evm::<T>)?;903 Ok(())904 }905906 /// @notice Transfer ownership of an RFT907 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`908 /// is the zero address. Throws if `tokenId` is not a valid RFT.909 /// Throws if RFT pieces have multiple owners.910 /// @param to The new owner911 /// @param tokenId The RFT to transfer912 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]913 fn transfer_from_cross(914 &mut self,915 caller: Caller,916 from: eth::CrossAddress,917 to: eth::CrossAddress,918 token_id: U256,919 ) -> Result<()> {920 let caller = T::CrossAccountId::from_eth(caller);921 let from = from.into_sub_cross_account::<T>()?;922 let to = to.into_sub_cross_account::<T>()?;923 let token_id = token_id.try_into()?;924 let budget = self925 .recorder926 .weight_calls_budget(<StructureWeight<T>>::find_parent());927928 let balance = balance(self, token_id, &from)?;929 ensure_single_owner(self, token_id, balance)?;930931 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)932 .map_err(dispatch_to_evm::<T>)?;933 Ok(())934 }935936 /// @notice Burns a specific ERC721 token.937 /// @dev Throws unless `msg.sender` is the current owner or an authorized938 /// operator for this RFT. Throws if `from` is not the current owner. Throws939 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.940 /// Throws if RFT pieces have multiple owners.941 /// @param from The current owner of the RFT942 /// @param tokenId The RFT to transfer943 #[solidity(hide)]944 #[weight(<SelfWeightOf<T>>::burn_from())]945 fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {946 let caller = T::CrossAccountId::from_eth(caller);947 let from = T::CrossAccountId::from_eth(from);948 let token = token_id.try_into()?;949 let budget = self950 .recorder951 .weight_calls_budget(<StructureWeight<T>>::find_parent());952953 let balance = balance(self, token, &from)?;954 ensure_single_owner(self, token, balance)?;955956 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)957 .map_err(dispatch_to_evm::<T>)?;958 Ok(())959 }960961 /// @notice Burns a specific ERC721 token.962 /// @dev Throws unless `msg.sender` is the current owner or an authorized963 /// operator for this RFT. Throws if `from` is not the current owner. Throws964 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.965 /// Throws if RFT pieces have multiple owners.966 /// @param from The current owner of the RFT967 /// @param tokenId The RFT to transfer968 #[weight(<SelfWeightOf<T>>::burn_from())]969 fn burn_from_cross(970 &mut self,971 caller: Caller,972 from: eth::CrossAddress,973 token_id: U256,974 ) -> Result<()> {975 let caller = T::CrossAccountId::from_eth(caller);976 let from = from.into_sub_cross_account::<T>()?;977 let token = token_id.try_into()?;978 let budget = self979 .recorder980 .weight_calls_budget(<StructureWeight<T>>::find_parent());981982 let balance = balance(self, token, &from)?;983 ensure_single_owner(self, token, balance)?;984985 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)986 .map_err(dispatch_to_evm::<T>)?;987 Ok(())988 }989990 /// @notice Returns next free RFT ID.991 fn next_token_id(&self) -> Result<U256> {992 self.consume_store_reads(1)?;993 Ok(<Pallet<T>>::next_token_id(self)994 .map_err(dispatch_to_evm::<T>)?995 .into())996 }997998 /// @notice Function to mint multiple tokens.999 /// @dev `tokenIds` should be an array of consecutive numbers and first number1000 /// should be obtained with `nextTokenId` method1001 /// @param to The new owner1002 /// @param tokenIds IDs of the minted RFTs1003 #[solidity(hide)]1004 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]1005 fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {1006 let caller = T::CrossAccountId::from_eth(caller);1007 let to = T::CrossAccountId::from_eth(to);1008 let mut expected_index = <TokensMinted<T>>::get(self.id)1009 .checked_add(1)1010 .ok_or("item id overflow")?;1011 let budget = self1012 .recorder1013 .weight_calls_budget(<StructureWeight<T>>::find_parent());10141015 let total_tokens = token_ids.len();1016 for id in token_ids.into_iter() {1017 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1018 if id != expected_index {1019 return Err("item id should be next".into());1020 }1021 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;1022 }1023 let users = [(to, 1)]1024 .into_iter()1025 .collect::<BTreeMap<_, _>>()1026 .try_into()1027 .unwrap();1028 let create_item_data = CreateItemData::<T> {1029 users,1030 properties: CollectionPropertiesVec::default(),1031 };1032 let data = (0..total_tokens)1033 .map(|_| create_item_data.clone())1034 .collect();10351036 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1037 .map_err(dispatch_to_evm::<T>)?;1038 Ok(true)1039 }10401041 /// @notice Function to mint a token.1042 /// @param tokenProperties Properties of minted token1043 #[weight(if token_properties.len() == 1 {1044 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(token_properties.iter().next().unwrap().owners.len() as u32)1045 } else {1046 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(token_properties.len() as u32)1047 } + <SelfWeightOf<T>>::set_token_properties(token_properties.len() as u32))]1048 fn mint_bulk_cross(1049 &mut self,1050 caller: Caller,1051 token_properties: Vec<MintTokenData>,1052 ) -> Result<bool> {1053 let caller = T::CrossAccountId::from_eth(caller);1054 let budget = self1055 .recorder1056 .weight_calls_budget(<StructureWeight<T>>::find_parent());1057 let has_multiple_tokens = token_properties.len() > 1;10581059 let mut create_rft_data = Vec::with_capacity(token_properties.len());1060 for MintTokenData { owners, properties } in token_properties {1061 let has_multiple_owners = owners.len() > 1;1062 if has_multiple_tokens & has_multiple_owners {1063 return Err(1064 "creation of multiple tokens supported only if they have single owner each"1065 .into(),1066 );1067 }1068 let users: BoundedBTreeMap<_, _, _> = owners1069 .into_iter()1070 .map(|data| Ok((data.owner.into_sub_cross_account::<T>()?, data.pieces)))1071 .collect::<Result<BTreeMap<_, _>>>()?1072 .try_into()1073 .map_err(|_| "too many users")?;1074 create_rft_data.push(CreateItemData::<T> {1075 properties: properties1076 .into_iter()1077 .map(|property| property.try_into())1078 .collect::<Result<Vec<_>>>()?1079 .try_into()1080 .map_err(|_| "too many properties")?,1081 users,1082 });1083 }10841085 <Pallet<T>>::create_multiple_items(self, &caller, create_rft_data, &budget)1086 .map_err(dispatch_to_evm::<T>)?;1087 Ok(true)1088 }10891090 /// @notice Function to mint multiple tokens with the given tokenUris.1091 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive1092 /// numbers and first number should be obtained with `nextTokenId` method1093 /// @param to The new owner1094 /// @param tokens array of pairs of token ID and token URI for minted tokens1095 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1096 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]1097 fn mint_bulk_with_token_uri(1098 &mut self,1099 caller: Caller,1100 to: Address,1101 tokens: Vec<TokenUri>,1102 ) -> Result<bool> {1103 let key = key::url();1104 let caller = T::CrossAccountId::from_eth(caller);1105 let to = T::CrossAccountId::from_eth(to);1106 let mut expected_index = <TokensMinted<T>>::get(self.id)1107 .checked_add(1)1108 .ok_or("item id overflow")?;1109 let budget = self1110 .recorder1111 .weight_calls_budget(<StructureWeight<T>>::find_parent());11121113 let mut data = Vec::with_capacity(tokens.len());1114 let users: BoundedBTreeMap<_, _, _> = [(to, 1)]1115 .into_iter()1116 .collect::<BTreeMap<_, _>>()1117 .try_into()1118 .unwrap();1119 for TokenUri { id, uri } in tokens {1120 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1121 if id != expected_index {1122 return Err("item id should be next".into());1123 }1124 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;11251126 let mut properties = CollectionPropertiesVec::default();1127 properties1128 .try_push(Property {1129 key: key.clone(),1130 value: uri1131 .into_bytes()1132 .try_into()1133 .map_err(|_| "token uri is too long")?,1134 })1135 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;11361137 let create_item_data = CreateItemData::<T> {1138 users: users.clone(),1139 properties,1140 };1141 data.push(create_item_data);1142 }11431144 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1145 .map_err(dispatch_to_evm::<T>)?;1146 Ok(true)1147 }11481149 /// @notice Function to mint a token.1150 /// @param to The new owner crossAccountId1151 /// @param properties Properties of minted token1152 /// @return uint256 The id of the newly minted token1153 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1154 fn mint_cross(1155 &mut self,1156 caller: Caller,1157 to: eth::CrossAddress,1158 properties: Vec<eth::Property>,1159 ) -> Result<U256> {1160 let token_id = <TokensMinted<T>>::get(self.id)1161 .checked_add(1)1162 .ok_or("item id overflow")?;11631164 let to = to.into_sub_cross_account::<T>()?;11651166 let properties = properties1167 .into_iter()1168 .map(eth::Property::try_into)1169 .collect::<Result<Vec<_>>>()?1170 .try_into()1171 .map_err(|_| Error::Revert("too many properties".to_string()))?;11721173 let caller = T::CrossAccountId::from_eth(caller);11741175 let budget = self1176 .recorder1177 .weight_calls_budget(<StructureWeight<T>>::find_parent());11781179 let users = [(to, 1)]1180 .into_iter()1181 .collect::<BTreeMap<_, _>>()1182 .try_into()1183 .unwrap();1184 <Pallet<T>>::create_item(1185 self,1186 &caller,1187 CreateItemData::<T> { users, properties },1188 &budget,1189 )1190 .map_err(dispatch_to_evm::<T>)?;11911192 Ok(token_id.into())1193 }11941195 /// Returns EVM address for refungible token1196 ///1197 /// @param token ID of the token1198 fn token_contract_address(&self, token: U256) -> Result<Address> {1199 Ok(T::EvmTokenAddressMapping::token_to_address(1200 self.id,1201 token.try_into().map_err(|_| "token id overflow")?,1202 ))1203 }12041205 /// @notice Returns collection helper contract address1206 fn collection_helper_address(&self) -> Result<Address> {1207 Ok(T::ContractAddress::get())1208 }1209}12101211#[solidity_interface(1212 name = UniqueRefungible,1213 is(1214 ERC721,1215 ERC721Enumerable,1216 ERC721UniqueExtensions,1217 ERC721UniqueMintable,1218 ERC721Burnable,1219 ERC721Metadata(if(this.flags.erc721metadata)),1220 Collection(via(common_mut returns CollectionHandle<T>)),1221 TokenProperties,1222 ),1223 enum(derive(PreDispatch)),1224)]1225impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}12261227// Not a tests, but code generators1228generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1229generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);12301231impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1232where1233 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1234{1235 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1236 fn call(1237 self,1238 handle: &mut impl PrecompileHandle,1239 ) -> Option<pallet_common::erc::PrecompileResult> {1240 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1241 }1242}pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -106,8 +106,8 @@
use up_data_structs::{
AccessMode, budget::Budget, CollectionId, CreateCollectionData, mapping::TokenAddressMapping,
MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyScope,
- PropertyValue, TokenId, TrySetProperty, PropertiesPermissionMap,
- CreateRefungibleExMultipleOwners, TokenOwnerError, TokenProperties as TokenPropertiesT,
+ PropertyValue, TokenId, PropertiesPermissionMap, CreateRefungibleExMultipleOwners,
+ TokenOwnerError, TokenProperties as TokenPropertiesT,
};
pub use pallet::*;
@@ -175,7 +175,7 @@
pub type TokenProperties<T: Config> = StorageNMap<
Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
Value = TokenPropertiesT,
- QueryKind = ValueQuery,
+ QueryKind = OptionQuery,
>;
/// Total amount of pieces for token
@@ -292,35 +292,7 @@
/// - `token`: Token ID.
pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {
<TotalSupply<T>>::contains_key((collection.id, token))
- }
-
- pub fn set_scoped_token_property(
- collection_id: CollectionId,
- token_id: TokenId,
- scope: PropertyScope,
- property: Property,
- ) -> DispatchResult {
- TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {
- properties.try_scoped_set(scope, property.key, property.value)
- })
- .map_err(<CommonError<T>>::from)?;
-
- Ok(())
}
-
- pub fn set_scoped_token_properties(
- collection_id: CollectionId,
- token_id: TokenId,
- scope: PropertyScope,
- properties: impl Iterator<Item = Property>,
- ) -> DispatchResult {
- TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {
- stored_properties.try_scoped_set_from_iter(scope, properties)
- })
- .map_err(<CommonError<T>>::from)?;
-
- Ok(())
- }
}
// unchecked calls skips any permission checks
@@ -1426,7 +1398,9 @@
pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {
<TokenProperties<T>>::mutate((collection.id, token), |properties| {
- properties.recompute_consumed_space();
+ if let Some(properties) = properties {
+ properties.recompute_consumed_space();
+ }
});
Ok(())