difftreelog
fix set prop for not existed token (#933)
in: master
* fix: set prop for not existed token * optimize token checking * remove comments * test(token properties): on token non-existence * fix PR comments * rename value * refactor(modify token properties): readability + grammar * revert: unused import used for try-runtime * fix prop permission check * Add self_mint flag * Add LazyValue * fix tests * fix unit tests * fix docker * fix mintCross sponsoring * Generalize next_token_id * fix: set sponsored properties ---------
20 files changed
.docker/Dockerfile-chain-dev-unitdiffbeforeafterboth--- a/.docker/Dockerfile-chain-dev-unit
+++ b/.docker/Dockerfile-chain-dev-unit
@@ -17,4 +17,4 @@
WORKDIR /dev_chain
-CMD cargo test --features=limit-testing --workspace
+CMD cargo test --features=limit-testing,tests --workspace
pallets/common/Cargo.tomldiffbeforeafterboth--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -36,4 +36,5 @@
"up-pov-estimate-rpc/std",
]
stubgen = ["evm-coder/stubgen"]
+tests = []
try-runtime = ["frame-support/try-runtime"]
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -131,6 +131,18 @@
value: evm_coder::types::Bytes,
}
+impl Property {
+ /// Property key.
+ pub fn key(&self) -> &str {
+ self.key.as_str()
+ }
+
+ /// Property value.
+ pub fn value(&self) -> &[u8] {
+ self.value.0.as_slice()
+ }
+}
+
impl TryFrom<up_data_structs::Property> for Property {
type Error = pallet_evm_coder_substrate::execution::Error;
@@ -227,11 +239,9 @@
Some(value) => match value {
0 => Ok(Some(false)),
1 => Ok(Some(true)),
- _ => {
- return Err(Self::Error::Revert(format!(
- "can't convert value to boolean \"{value}\""
- )))
- }
+ _ => Err(Self::Error::Revert(format!(
+ "can't convert value to boolean \"{value}\""
+ ))),
},
None => Ok(None),
};
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -216,7 +216,6 @@
///
/// # Arguments
///
- /// * `sender`: Caller's account.
/// * `sponsor`: ID of the account of the sponsor-to-be.
pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {
self.check_is_internal()?;
@@ -867,6 +866,74 @@
>;
}
+/// Represents the change mode for the token property.
+pub enum SetPropertyMode {
+ /// The token already exists.
+ ExistingToken,
+
+ /// New token.
+ NewToken {
+ /// The creator of the token is the recipient.
+ mint_target_is_sender: bool,
+ },
+}
+
+/// Value representation with delayed initialization time.
+pub struct LazyValue<T, F: FnOnce() -> T> {
+ value: Option<T>,
+ f: Option<F>,
+}
+
+impl<T, F: FnOnce() -> T> LazyValue<T, F> {
+ /// Create a new LazyValue.
+ pub fn new(f: F) -> Self {
+ Self {
+ value: None,
+ f: Some(f),
+ }
+ }
+
+ /// Get the value. If it call furst time the value will be initialized.
+ pub fn value(&mut self) -> &T {
+ if self.value.is_none() {
+ self.value = Some(self.f.take().unwrap()())
+ }
+
+ self.value.as_ref().unwrap()
+ }
+
+ /// Is value initialized.
+ pub fn has_value(&self) -> bool {
+ self.value.is_some()
+ }
+}
+
+fn check_token_permissions<T, FCA, FTO, FTE>(
+ collection_admin_permitted: bool,
+ token_owner_permitted: bool,
+ is_collection_admin: &mut LazyValue<bool, FCA>,
+ is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,
+ is_token_exist: &mut LazyValue<bool, FTE>,
+) -> DispatchResult
+where
+ T: Config,
+ FCA: FnOnce() -> bool,
+ FTO: FnOnce() -> Result<bool, DispatchError>,
+ FTE: FnOnce() -> bool,
+{
+ if !(collection_admin_permitted && *is_collection_admin.value()
+ || token_owner_permitted && (*is_token_owner.value())?)
+ {
+ fail!(<Error<T>>::NoPermission);
+ }
+
+ let token_certainly_exist = is_token_owner.has_value() && (*is_token_owner.value())?;
+ if !token_certainly_exist && !is_token_exist.value() {
+ fail!(<Error<T>>::TokenNotFound);
+ }
+ Ok(())
+}
+
impl<T: Config> Pallet<T> {
/// Enshure that receiver address is correct.
///
@@ -1218,10 +1285,6 @@
/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`
/// * removes a property under the <key> if the value is `None` `(<key>, None)`.
///
- /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
- /// - `is_token_create`: Indicates that method is called during token initialization.
- /// Allows to bypass ownership check.
- ///
/// All affected properties should have `mutable` permission
/// to be **deleted** or to be **set more than once**,
/// and the sender should have permission to edit those properties.
@@ -1229,35 +1292,36 @@
/// This function fires an event for each property change.
/// In case of an error, all the changes (including the events) will be reverted
/// since the function is transactional.
- pub fn modify_token_properties(
+ #[allow(clippy::too_many_arguments)]
+ pub fn modify_token_properties<FTO, FTE>(
collection: &CollectionHandle<T>,
sender: &T::CrossAccountId,
token_id: TokenId,
+ is_token_exist: &mut LazyValue<bool, FTE>,
properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
- is_token_create: bool,
mut stored_properties: TokenProperties,
- is_token_owner: impl Fn() -> Result<bool, DispatchError>,
+ is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,
set_token_properties: impl FnOnce(TokenProperties),
log: evm_coder::ethereum::Log,
- ) -> DispatchResult {
- let is_collection_admin = collection.is_owner_or_admin(sender);
+ ) -> DispatchResult
+ where
+ FTO: FnOnce() -> Result<bool, DispatchError>,
+ FTE: FnOnce() -> bool,
+ {
+ let mut is_collection_admin = LazyValue::new(|| collection.is_owner_or_admin(sender));
let permissions = Self::property_permissions(collection.id);
- let mut token_owner_result = None;
- let mut is_token_owner = || -> Result<bool, DispatchError> {
- *token_owner_result.get_or_insert_with(&is_token_owner)
- };
-
+ let mut changed = false;
for (key, value) in properties_updates {
let permission = permissions
.get(&key)
.cloned()
.unwrap_or_else(PropertyPermission::none);
- let is_property_exists = stored_properties.get(&key).is_some();
+ let property_exists = stored_properties.get(&key).is_some();
match permission {
- PropertyPermission { mutable: false, .. } if is_property_exists => {
+ PropertyPermission { mutable: false, .. } if property_exists => {
return Err(<Error<T>>::NoPermission.into());
}
@@ -1265,17 +1329,13 @@
collection_admin,
token_owner,
..
- } => {
- //TODO: investigate threats during public minting.
- let is_token_create =
- is_token_create && (collection_admin || token_owner) && value.is_some();
- if !(is_token_create
- || (collection_admin && is_collection_admin)
- || (token_owner && is_token_owner()?))
- {
- fail!(<Error<T>>::NoPermission);
- }
- }
+ } => check_token_permissions::<T, _, FTO, FTE>(
+ collection_admin,
+ token_owner,
+ &mut is_collection_admin,
+ is_token_owner,
+ is_token_exist,
+ )?,
}
match value {
@@ -1293,9 +1353,13 @@
}
}
- <PalletEvm<T>>::deposit_log(log.clone());
+ changed = true;
}
+ if changed {
+ <PalletEvm<T>>::deposit_log(log);
+ }
+
set_token_properties(stored_properties);
Ok(())
@@ -2322,3 +2386,86 @@
}
}
}
+
+#[cfg(feature = "tests")]
+pub mod tests {
+ use crate::{DispatchResult, DispatchError, LazyValue, Config};
+
+ const fn to_bool(u: u8) -> bool {
+ u != 0
+ }
+
+ #[derive(Debug)]
+ pub struct TestCase {
+ pub collection_admin: bool,
+ pub is_collection_admin: bool,
+ pub token_owner: bool,
+ pub is_token_owner: bool,
+ pub no_permission: bool,
+ }
+
+ impl TestCase {
+ const fn new(
+ collection_admin: u8,
+ is_collection_admin: u8,
+ token_owner: u8,
+ is_token_owner: u8,
+ no_permission: u8,
+ ) -> Self {
+ Self {
+ collection_admin: to_bool(collection_admin),
+ is_collection_admin: to_bool(is_collection_admin),
+ token_owner: to_bool(token_owner),
+ is_token_owner: to_bool(is_token_owner),
+ no_permission: to_bool(no_permission),
+ }
+ }
+ }
+
+ #[rustfmt::skip]
+ pub const table: [TestCase; 16] = [
+ // ┌╴collection_admin
+ // │ ┌╴is_collection_admin
+ // │ │ ┌╴token_owner
+ // │ │ │ ┌╴is_token_ownership
+ // │ │ │ │ ┌╴no_permission
+ /* 0*/ TestCase::new(0, 0, 0, 0, 1),
+ /* 1*/ TestCase::new(0, 0, 0, 1, 1),
+ /* 2*/ TestCase::new(0, 0, 1, 0, 1),
+ /* 3*/ TestCase::new(0, 0, 1, 1, 0),
+ /* 4*/ TestCase::new(0, 1, 0, 0, 1),
+ /* 5*/ TestCase::new(0, 1, 0, 1, 1),
+ /* 6*/ TestCase::new(0, 1, 1, 0, 1),
+ /* 7*/ TestCase::new(0, 1, 1, 1, 0),
+ /* 8*/ TestCase::new(1, 0, 0, 0, 1),
+ /* 9*/ TestCase::new(1, 0, 0, 1, 1),
+ /* 10*/ TestCase::new(1, 0, 1, 0, 1),
+ /* 11*/ TestCase::new(1, 0, 1, 1, 0),
+ /* 12*/ TestCase::new(1, 1, 0, 0, 0),
+ /* 13*/ TestCase::new(1, 1, 0, 1, 0),
+ /* 14*/ TestCase::new(1, 1, 1, 0, 0),
+ /* 15*/ TestCase::new(1, 1, 1, 1, 0),
+ ];
+
+ pub fn check_token_permissions<T, FCA, FTO, FTE>(
+ collection_admin_permitted: bool,
+ token_owner_permitted: bool,
+ is_collection_admin: &mut LazyValue<bool, FCA>,
+ check_token_ownership: &mut LazyValue<Result<bool, DispatchError>, FTO>,
+ check_token_existence: &mut LazyValue<bool, FTE>,
+ ) -> DispatchResult
+ where
+ T: Config,
+ FCA: FnOnce() -> bool,
+ FTO: FnOnce() -> Result<bool, DispatchError>,
+ FTE: FnOnce() -> bool,
+ {
+ crate::check_token_permissions::<T, FCA, FTO, FTE>(
+ collection_admin_permitted,
+ token_owner_permitted,
+ is_collection_admin,
+ check_token_ownership,
+ check_token_existence,
+ )
+ }
+}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -245,7 +245,7 @@
&sender,
token_id,
properties.into_iter(),
- false,
+ pallet_common::SetPropertyMode::ExistingToken,
nesting_budget,
),
weight,
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -194,7 +194,7 @@
&caller,
TokenId(token_id),
properties.into_iter(),
- false,
+ pallet_common::SetPropertyMode::ExistingToken,
&nesting_budget,
)
.map_err(dispatch_to_evm::<T>)
@@ -939,9 +939,8 @@
/// @notice Returns next free NFT ID.
fn next_token_id(&self) -> Result<U256> {
self.consume_store_reads(1)?;
- Ok(<TokensMinted<T>>::get(self.id)
- .checked_add(1)
- .ok_or("item id overflow")?
+ Ok(<Pallet<T>>::next_token_id(self)
+ .map_err(dispatch_to_evm::<T>)?
.into())
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -109,7 +109,7 @@
use pallet_common::{
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,
- weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,
+ weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info, SetPropertyMode,
};
use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
@@ -585,8 +585,6 @@
/// A batch operation to add, edit or remove properties for a token.
///
/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
- /// - `is_token_create`: Indicates that method is called during token initialization.
- /// Allows to bypass ownership check.
///
/// All affected properties should have `mutable` permission
/// to be **deleted** or to be **set more than once**,
@@ -601,10 +599,17 @@
sender: &T::CrossAccountId,
token_id: TokenId,
properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
- is_token_create: bool,
+ mode: SetPropertyMode,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- let is_token_owner = || {
+ let mut is_token_owner = pallet_common::LazyValue::new(|| {
+ if let SetPropertyMode::NewToken {
+ mint_target_is_sender,
+ } = mode
+ {
+ return Ok(mint_target_is_sender);
+ }
+
let is_owned = <PalletStructure<T>>::check_indirectly_owned(
sender.clone(),
collection.id,
@@ -614,18 +619,21 @@
)?;
Ok(is_owned)
- };
+ });
+ let mut is_token_exist =
+ pallet_common::LazyValue::new(|| Self::token_exists(collection, token_id));
+
let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));
<PalletCommon<T>>::modify_token_properties(
collection,
sender,
token_id,
+ &mut is_token_exist,
properties_updates,
- is_token_create,
stored_properties,
- is_token_owner,
+ &mut is_token_owner,
|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),
erc::ERC721TokenEvent::TokenChanged {
token_id: token_id.into(),
@@ -634,6 +642,19 @@
)
}
+ pub fn next_token_id(collection: &NonfungibleHandle<T>) -> Result<TokenId, DispatchError> {
+ let next_token_id = <TokensMinted<T>>::get(collection.id)
+ .checked_add(1)
+ .ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;
+
+ ensure!(
+ collection.limits.token_limit() >= next_token_id,
+ <CommonError<T>>::CollectionTokenLimitExceeded
+ );
+
+ Ok(TokenId(next_token_id))
+ }
+
/// Batch operation to add or edit properties for the token
///
/// Same as [`modify_token_properties`] but doesn't allow to remove properties
@@ -644,7 +665,7 @@
sender: &T::CrossAccountId,
token_id: TokenId,
properties: impl Iterator<Item = Property>,
- is_token_create: bool,
+ mode: SetPropertyMode,
nesting_budget: &dyn Budget,
) -> DispatchResult {
Self::modify_token_properties(
@@ -652,7 +673,7 @@
sender,
token_id,
properties.map(|p| (p.key, Some(p.value))),
- is_token_create,
+ mode,
nesting_budget,
)
}
@@ -669,14 +690,12 @@
property: Property,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- let is_token_create = false;
-
Self::set_token_properties(
collection,
sender,
token_id,
[property].into_iter(),
- is_token_create,
+ SetPropertyMode::ExistingToken,
nesting_budget,
)
}
@@ -693,14 +712,12 @@
property_keys: impl Iterator<Item = PropertyKey>,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- let is_token_create = false;
-
Self::modify_token_properties(
collection,
sender,
token_id,
property_keys.into_iter().map(|key| (key, None)),
- is_token_create,
+ SetPropertyMode::ExistingToken,
nesting_budget,
)
}
@@ -985,7 +1002,9 @@
sender,
TokenId(token),
data.properties.clone().into_iter(),
- true,
+ SetPropertyMode::NewToken {
+ mint_target_is_sender: sender.conv_eq(&data.owner),
+ },
nesting_budget,
) {
return TransactionOutcome::Rollback(Err(e));
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -399,7 +399,7 @@
&sender,
token_id,
properties.into_iter(),
- false,
+ pallet_common::SetPropertyMode::ExistingToken,
nesting_budget,
),
weight,
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, 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/// @title A contract that allows to set and delete token properties and change token property permissions.75#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]76impl<T: Config> RefungibleHandle<T> {77 /// @notice Set permissions for token property.78 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.79 /// @param key Property key.80 /// @param isMutable Permission to mutate property.81 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.82 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.83 #[solidity(hide)]84 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]85 fn set_token_property_permission(86 &mut self,87 caller: Caller,88 key: String,89 is_mutable: bool,90 collection_admin: bool,91 token_owner: bool,92 ) -> Result<()> {93 let caller = T::CrossAccountId::from_eth(caller);94 <Pallet<T>>::set_token_property_permissions(95 self,96 &caller,97 vec![PropertyKeyPermission {98 key: <Vec<u8>>::from(key)99 .try_into()100 .map_err(|_| "too long key")?,101 permission: PropertyPermission {102 mutable: is_mutable,103 collection_admin,104 token_owner,105 },106 }],107 )108 .map_err(dispatch_to_evm::<T>)109 }110111 /// @notice Set permissions for token property.112 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.113 /// @param permissions Permissions for keys.114 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]115 fn set_token_property_permissions(116 &mut self,117 caller: Caller,118 permissions: Vec<eth::TokenPropertyPermission>,119 ) -> Result<()> {120 let caller = T::CrossAccountId::from_eth(caller);121 let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;122123 <Pallet<T>>::set_token_property_permissions(self, &caller, perms)124 .map_err(dispatch_to_evm::<T>)125 }126127 /// @notice Get permissions for token properties.128 fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {129 let perms = <Pallet<T>>::token_property_permission(self.id);130 Ok(perms131 .into_iter()132 .map(eth::TokenPropertyPermission::from)133 .collect())134 }135136 /// @notice Set token property value.137 /// @dev Throws error if `msg.sender` has no permission to edit the property.138 /// @param tokenId ID of the token.139 /// @param key Property key.140 /// @param value Property value.141 #[solidity(hide)]142 #[weight(<SelfWeightOf<T>>::set_token_properties(1))]143 fn set_property(144 &mut self,145 caller: Caller,146 token_id: U256,147 key: String,148 value: Bytes,149 ) -> Result<()> {150 let caller = T::CrossAccountId::from_eth(caller);151 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;152 let key = <Vec<u8>>::from(key)153 .try_into()154 .map_err(|_| "key too long")?;155 let value = value.0.try_into().map_err(|_| "value too long")?;156157 let nesting_budget = self158 .recorder159 .weight_calls_budget(<StructureWeight<T>>::find_parent());160161 <Pallet<T>>::set_token_property(162 self,163 &caller,164 TokenId(token_id),165 Property { key, value },166 &nesting_budget,167 )168 .map_err(dispatch_to_evm::<T>)169 }170171 /// @notice Set token properties value.172 /// @dev Throws error if `msg.sender` has no permission to edit the property.173 /// @param tokenId ID of the token.174 /// @param properties settable properties175 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]176 fn set_properties(177 &mut self,178 caller: Caller,179 token_id: U256,180 properties: Vec<eth::Property>,181 ) -> Result<()> {182 let caller = T::CrossAccountId::from_eth(caller);183 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;184185 let nesting_budget = self186 .recorder187 .weight_calls_budget(<StructureWeight<T>>::find_parent());188189 let properties = properties190 .into_iter()191 .map(eth::Property::try_into)192 .collect::<Result<Vec<_>>>()?;193194 <Pallet<T>>::set_token_properties(195 self,196 &caller,197 TokenId(token_id),198 properties.into_iter(),199 false,200 &nesting_budget,201 )202 .map_err(dispatch_to_evm::<T>)203 }204205 /// @notice Delete token property value.206 /// @dev Throws error if `msg.sender` has no permission to edit the property.207 /// @param tokenId ID of the token.208 /// @param key Property key.209 #[solidity(hide)]210 #[weight(<SelfWeightOf<T>>::delete_token_properties(1))]211 fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {212 let caller = T::CrossAccountId::from_eth(caller);213 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;214 let key = <Vec<u8>>::from(key)215 .try_into()216 .map_err(|_| "key too long")?;217218 let nesting_budget = self219 .recorder220 .weight_calls_budget(<StructureWeight<T>>::find_parent());221222 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)223 .map_err(dispatch_to_evm::<T>)224 }225226 /// @notice Delete token properties value.227 /// @dev Throws error if `msg.sender` has no permission to edit the property.228 /// @param tokenId ID of the token.229 /// @param keys Properties key.230 #[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]231 fn delete_properties(232 &mut self,233 token_id: U256,234 caller: Caller,235 keys: Vec<String>,236 ) -> Result<()> {237 let caller = T::CrossAccountId::from_eth(caller);238 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;239 let keys = keys240 .into_iter()241 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))242 .collect::<Result<Vec<_>>>()?;243244 let nesting_budget = self245 .recorder246 .weight_calls_budget(<StructureWeight<T>>::find_parent());247248 <Pallet<T>>::delete_token_properties(249 self,250 &caller,251 TokenId(token_id),252 keys.into_iter(),253 &nesting_budget,254 )255 .map_err(dispatch_to_evm::<T>)256 }257258 /// @notice Get token property value.259 /// @dev Throws error if key not found260 /// @param tokenId ID of the token.261 /// @param key Property key.262 /// @return Property value bytes263 fn property(&self, token_id: U256, key: String) -> Result<Bytes> {264 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;265 let key = <Vec<u8>>::from(key)266 .try_into()267 .map_err(|_| "key too long")?;268269 let props = <TokenProperties<T>>::get((self.id, token_id));270 let prop = props.get(&key).ok_or("key not found")?;271272 Ok(prop.to_vec().into())273 }274}275276#[derive(ToLog)]277pub enum ERC721Events {278 /// @dev This event emits when NFTs are created (`from` == 0) and destroyed279 /// (`to` == 0). Exception: during contract creation, any number of RFTs280 /// may be created and assigned without emitting Transfer.281 Transfer {282 #[indexed]283 from: Address,284 #[indexed]285 to: Address,286 #[indexed]287 token_id: U256,288 },289 /// @dev Not supported290 Approval {291 #[indexed]292 owner: Address,293 #[indexed]294 approved: Address,295 #[indexed]296 token_id: U256,297 },298 /// @dev Not supported299 #[allow(dead_code)]300 ApprovalForAll {301 #[indexed]302 owner: Address,303 #[indexed]304 operator: Address,305 approved: bool,306 },307}308309/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension310/// @dev See https://eips.ethereum.org/EIPS/eip-721311#[solidity_interface(name = ERC721Metadata, enum(derive(PreDispatch)), expect_selector = 0x5b5e139f)]312impl<T: Config> RefungibleHandle<T>313where314 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,315{316 /// @notice A descriptive name for a collection of NFTs in this contract317 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`318 #[solidity(hide, rename_selector = "name")]319 fn name_proxy(&self) -> Result<String> {320 self.name()321 }322323 /// @notice An abbreviated name for NFTs in this contract324 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`325 #[solidity(hide, rename_selector = "symbol")]326 fn symbol_proxy(&self) -> Result<String> {327 self.symbol()328 }329330 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.331 ///332 /// @dev If the token has a `url` property and it is not empty, it is returned.333 /// 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`.334 /// If the collection property `baseURI` is empty or absent, return "" (empty string)335 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix336 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).337 ///338 /// @return token's const_metadata339 #[solidity(rename_selector = "tokenURI")]340 fn token_uri(&self, token_id: U256) -> Result<String> {341 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;342343 match get_token_property(self, token_id_u32, &key::url()).as_deref() {344 Err(_) | Ok("") => (),345 Ok(url) => {346 return Ok(url.into());347 }348 };349350 let base_uri =351 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())352 .map(BoundedVec::into_inner)353 .map(String::from_utf8)354 .transpose()355 .map_err(|e| {356 Error::Revert(alloc::format!(357 "Can not convert value \"baseURI\" to string with error \"{e}\""358 ))359 })?;360361 let base_uri = match base_uri.as_deref() {362 None | Some("") => {363 return Ok("".into());364 }365 Some(base_uri) => base_uri.into(),366 };367368 Ok(369 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {370 Err(_) | Ok("") => base_uri,371 Ok(suffix) => base_uri + suffix,372 },373 )374 }375}376377/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension378/// @dev See https://eips.ethereum.org/EIPS/eip-721379#[solidity_interface(name = ERC721Enumerable, enum(derive(PreDispatch)), expect_selector = 0x780e9d63)]380impl<T: Config> RefungibleHandle<T> {381 /// @notice Enumerate valid RFTs382 /// @param index A counter less than `totalSupply()`383 /// @return The token identifier for the `index`th NFT,384 /// (sort order not specified)385 fn token_by_index(&self, index: U256) -> U256 {386 index387 }388389 /// Not implemented390 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {391 // TODO: Not implemetable392 Err("not implemented".into())393 }394395 /// @notice Count RFTs tracked by this contract396 /// @return A count of valid RFTs tracked by this contract, where each one of397 /// them has an assigned and queryable owner not equal to the zero address398 fn total_supply(&self) -> Result<U256> {399 self.consume_store_reads(1)?;400 Ok(<Pallet<T>>::total_supply(self).into())401 }402}403404/// @title ERC-721 Non-Fungible Token Standard405/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md406#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]407impl<T: Config> RefungibleHandle<T> {408 /// @notice Count all RFTs assigned to an owner409 /// @dev RFTs assigned to the zero address are considered invalid, and this410 /// function throws for queries about the zero address.411 /// @param owner An address for whom to query the balance412 /// @return The number of RFTs owned by `owner`, possibly zero413 fn balance_of(&self, owner: Address) -> Result<U256> {414 self.consume_store_reads(1)?;415 let owner = T::CrossAccountId::from_eth(owner);416 let balance = <AccountBalance<T>>::get((self.id, owner));417 Ok(balance.into())418 }419420 /// @notice Find the owner of an RFT421 /// @dev RFTs assigned to zero address are considered invalid, and queries422 /// about them do throw.423 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for424 /// the tokens that are partially owned.425 /// @param tokenId The identifier for an RFT426 /// @return The address of the owner of the RFT427 fn owner_of(&self, token_id: U256) -> Result<Address> {428 self.consume_store_reads(2)?;429 let token = token_id.try_into()?;430 let owner = <Pallet<T>>::token_owner(self.id, token);431 owner432 .map(|address| *address.as_eth())433 .or_else(|err| match err {434 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),435 TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),436 })437 }438439 /// @dev Not implemented440 #[solidity(rename_selector = "safeTransferFrom")]441 fn safe_transfer_from_with_data(442 &mut self,443 _from: Address,444 _to: Address,445 _token_id: U256,446 _data: Bytes,447 ) -> Result<()> {448 // TODO: Not implemetable449 Err("not implemented".into())450 }451452 /// @dev Not implemented453 #[solidity(rename_selector = "safeTransferFrom")]454 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {455 // TODO: Not implemetable456 Err("not implemented".into())457 }458459 /// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE460 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE461 /// THEY MAY BE PERMANENTLY LOST462 /// @dev Throws unless `msg.sender` is the current owner or an authorized463 /// operator for this RFT. Throws if `from` is not the current owner. Throws464 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.465 /// Throws if RFT pieces have multiple owners.466 /// @param from The current owner of the NFT467 /// @param to The new owner468 /// @param tokenId The NFT to transfer469 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]470 fn transfer_from(471 &mut self,472 caller: Caller,473 from: Address,474 to: Address,475 token_id: U256,476 ) -> Result<()> {477 let caller = T::CrossAccountId::from_eth(caller);478 let from = T::CrossAccountId::from_eth(from);479 let to = T::CrossAccountId::from_eth(to);480 let token = token_id.try_into()?;481 let budget = self482 .recorder483 .weight_calls_budget(<StructureWeight<T>>::find_parent());484485 let balance = balance(self, token, &from)?;486 ensure_single_owner(self, token, balance)?;487488 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)489 .map_err(dispatch_to_evm::<T>)?;490491 Ok(())492 }493494 /// @dev Not implemented495 fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {496 Err("not implemented".into())497 }498499 /// @notice Sets or unsets the approval of a given operator.500 /// The `operator` is allowed to transfer all token pieces of the `caller` on their behalf.501 /// @param operator Operator502 /// @param approved Should operator status be granted or revoked?503 #[weight(<SelfWeightOf<T>>::set_allowance_for_all())]504 fn set_approval_for_all(505 &mut self,506 caller: Caller,507 operator: Address,508 approved: bool,509 ) -> Result<()> {510 let caller = T::CrossAccountId::from_eth(caller);511 let operator = T::CrossAccountId::from_eth(operator);512513 <Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)514 .map_err(dispatch_to_evm::<T>)?;515 Ok(())516 }517518 /// @dev Not implemented519 fn get_approved(&self, _token_id: U256) -> Result<Address> {520 // TODO: Not implemetable521 Err("not implemented".into())522 }523524 /// @notice Tells whether the given `owner` approves the `operator`.525 #[weight(<SelfWeightOf<T>>::allowance_for_all())]526 fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {527 let owner = T::CrossAccountId::from_eth(owner);528 let operator = T::CrossAccountId::from_eth(operator);529530 Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))531 }532}533534/// Returns amount of pieces of `token` that `owner` have535pub fn balance<T: Config>(536 collection: &RefungibleHandle<T>,537 token: TokenId,538 owner: &T::CrossAccountId,539) -> Result<u128> {540 collection.consume_store_reads(1)?;541 let balance = <Balance<T>>::get((collection.id, token, &owner));542 Ok(balance)543}544545/// Throws if `owner_balance` is lower than total amount of `token` pieces546pub fn ensure_single_owner<T: Config>(547 collection: &RefungibleHandle<T>,548 token: TokenId,549 owner_balance: u128,550) -> Result<()> {551 collection.consume_store_reads(1)?;552 let total_supply = <TotalSupply<T>>::get((collection.id, token));553554 if owner_balance == 0 {555 return Err(dispatch_to_evm::<T>(556 <CommonError<T>>::MustBeTokenOwner.into(),557 ));558 }559560 if total_supply != owner_balance {561 return Err("token has multiple owners".into());562 }563 Ok(())564}565566/// @title ERC721 Token that can be irreversibly burned (destroyed).567#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]568impl<T: Config> RefungibleHandle<T> {569 /// @notice Burns a specific ERC721 token.570 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized571 /// operator of the current owner.572 /// @param tokenId The RFT to approve573 #[weight(<SelfWeightOf<T>>::burn_item_fully())]574 fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {575 let caller = T::CrossAccountId::from_eth(caller);576 let token = token_id.try_into()?;577578 let balance = balance(self, token, &caller)?;579 ensure_single_owner(self, token, balance)?;580581 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;582 Ok(())583 }584}585586/// @title ERC721 minting logic.587#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]588impl<T: Config> RefungibleHandle<T> {589 /// @notice Function to mint a token.590 /// @param to The new owner591 /// @return uint256 The id of the newly minted token592 #[weight(<SelfWeightOf<T>>::create_item())]593 fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {594 let token_id: U256 = <TokensMinted<T>>::get(self.id)595 .checked_add(1)596 .ok_or("item id overflow")?597 .into();598 self.mint_check_id(caller, to, token_id)?;599 Ok(token_id)600 }601602 /// @notice Function to mint a token.603 /// @dev `tokenId` should be obtained with `nextTokenId` method,604 /// unlike standard, you can't specify it manually605 /// @param to The new owner606 /// @param tokenId ID of the minted RFT607 #[solidity(hide, rename_selector = "mint")]608 #[weight(<SelfWeightOf<T>>::create_item())]609 fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {610 let caller = T::CrossAccountId::from_eth(caller);611 let to = T::CrossAccountId::from_eth(to);612 let token_id: u32 = token_id.try_into()?;613 let budget = self614 .recorder615 .weight_calls_budget(<StructureWeight<T>>::find_parent());616617 if <TokensMinted<T>>::get(self.id)618 .checked_add(1)619 .ok_or("item id overflow")?620 != token_id621 {622 return Err("item id should be next".into());623 }624625 let users = [(to, 1)]626 .into_iter()627 .collect::<BTreeMap<_, _>>()628 .try_into()629 .unwrap();630 <Pallet<T>>::create_item(631 self,632 &caller,633 CreateItemData::<T> {634 users,635 properties: CollectionPropertiesVec::default(),636 },637 &budget,638 )639 .map_err(dispatch_to_evm::<T>)?;640641 Ok(true)642 }643644 /// @notice Function to mint token with the given tokenUri.645 /// @param to The new owner646 /// @param tokenUri Token URI that would be stored in the NFT properties647 /// @return uint256 The id of the newly minted token648 #[solidity(rename_selector = "mintWithTokenURI")]649 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]650 fn mint_with_token_uri(651 &mut self,652 caller: Caller,653 to: Address,654 token_uri: String,655 ) -> Result<U256> {656 let token_id: U256 = <TokensMinted<T>>::get(self.id)657 .checked_add(1)658 .ok_or("item id overflow")?659 .into();660 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;661 Ok(token_id)662 }663664 /// @notice Function to mint token with the given tokenUri.665 /// @dev `tokenId` should be obtained with `nextTokenId` method,666 /// unlike standard, you can't specify it manually667 /// @param to The new owner668 /// @param tokenId ID of the minted RFT669 /// @param tokenUri Token URI that would be stored in the RFT properties670 #[solidity(hide, rename_selector = "mintWithTokenURI")]671 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]672 fn mint_with_token_uri_check_id(673 &mut self,674 caller: Caller,675 to: Address,676 token_id: U256,677 token_uri: String,678 ) -> Result<bool> {679 let key = key::url();680 let permission = get_token_permission::<T>(self.id, &key)?;681 if !permission.collection_admin {682 return Err("Operation is not allowed".into());683 }684685 let caller = T::CrossAccountId::from_eth(caller);686 let to = T::CrossAccountId::from_eth(to);687 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;688 let budget = self689 .recorder690 .weight_calls_budget(<StructureWeight<T>>::find_parent());691692 if <TokensMinted<T>>::get(self.id)693 .checked_add(1)694 .ok_or("item id overflow")?695 != token_id696 {697 return Err("item id should be next".into());698 }699700 let mut properties = CollectionPropertiesVec::default();701 properties702 .try_push(Property {703 key,704 value: token_uri705 .into_bytes()706 .try_into()707 .map_err(|_| "token uri is too long")?,708 })709 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;710711 let users = [(to, 1)]712 .into_iter()713 .collect::<BTreeMap<_, _>>()714 .try_into()715 .unwrap();716 <Pallet<T>>::create_item(717 self,718 &caller,719 CreateItemData::<T> { users, properties },720 &budget,721 )722 .map_err(dispatch_to_evm::<T>)?;723 Ok(true)724 }725}726727fn get_token_property<T: Config>(728 collection: &CollectionHandle<T>,729 token_id: u32,730 key: &up_data_structs::PropertyKey,731) -> Result<String> {732 collection.consume_store_reads(1)?;733 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))734 .map_err(|_| Error::Revert("Token properties not found".into()))?;735 if let Some(property) = properties.get(key) {736 return Ok(String::from_utf8_lossy(property).into());737 }738739 Err("Property tokenURI not found".into())740}741742fn get_token_permission<T: Config>(743 collection_id: CollectionId,744 key: &PropertyKey,745) -> Result<PropertyPermission> {746 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)747 .map_err(|_| Error::Revert("No permissions for collection".into()))?;748 let a = token_property_permissions749 .get(key)750 .map(Clone::clone)751 .ok_or_else(|| {752 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();753 Error::Revert(alloc::format!("No permission for key {key}"))754 })?;755 Ok(a)756}757758/// @title Unique extensions for ERC721.759#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]760impl<T: Config> RefungibleHandle<T>761where762 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,763{764 /// @notice A descriptive name for a collection of NFTs in this contract765 fn name(&self) -> Result<String> {766 Ok(decode_utf16(self.name.iter().copied())767 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))768 .collect::<String>())769 }770771 /// @notice An abbreviated name for NFTs in this contract772 fn symbol(&self) -> Result<String> {773 Ok(String::from_utf8_lossy(&self.token_prefix).into())774 }775776 /// @notice A description for the collection.777 fn description(&self) -> Result<String> {778 Ok(decode_utf16(self.description.iter().copied())779 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))780 .collect::<String>())781 }782783 /// Returns the owner (in cross format) of the token.784 ///785 /// @param tokenId Id for the token.786 #[solidity(hide)]787 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {788 Self::owner_of_cross(self, token_id)789 }790791 /// Returns the owner (in cross format) of the token.792 ///793 /// @param tokenId Id for the token.794 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {795 Self::token_owner(self, token_id.try_into()?)796 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))797 .or_else(|err| match err {798 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),799 TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(800 ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,801 )),802 })803 }804805 /// @notice Count all RFTs assigned to an owner806 /// @param owner An cross address for whom to query the balance807 /// @return The number of RFTs owned by `owner`, possibly zero808 fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {809 self.consume_store_reads(1)?;810 let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));811 Ok(balance.into())812 }813814 /// Returns the token properties.815 ///816 /// @param tokenId Id for the token.817 /// @param keys Properties keys. Empty keys for all propertyes.818 /// @return Vector of properties key/value pairs.819 fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {820 let keys = keys821 .into_iter()822 .map(|key| {823 <Vec<u8>>::from(key)824 .try_into()825 .map_err(|_| Error::Revert("key too large".into()))826 })827 .collect::<Result<Vec<_>>>()?;828829 <Self as CommonCollectionOperations<T>>::token_properties(830 self,831 token_id.try_into()?,832 if keys.is_empty() { None } else { Some(keys) },833 )834 .into_iter()835 .map(eth::Property::try_from)836 .collect::<Result<Vec<_>>>()837 }838 /// @notice Transfer ownership of an RFT839 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`840 /// is the zero address. Throws if `tokenId` is not a valid RFT.841 /// Throws if RFT pieces have multiple owners.842 /// @param to The new owner843 /// @param tokenId The RFT to transfer844 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]845 fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {846 let caller = T::CrossAccountId::from_eth(caller);847 let to = T::CrossAccountId::from_eth(to);848 let token = token_id.try_into()?;849 let budget = self850 .recorder851 .weight_calls_budget(<StructureWeight<T>>::find_parent());852853 let balance = balance(self, token, &caller)?;854 ensure_single_owner(self, token, balance)?;855856 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)857 .map_err(dispatch_to_evm::<T>)?;858 Ok(())859 }860861 /// @notice Transfer ownership of an RFT862 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`863 /// is the zero address. Throws if `tokenId` is not a valid RFT.864 /// Throws if RFT pieces have multiple owners.865 /// @param to The new owner866 /// @param tokenId The RFT to transfer867 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]868 fn transfer_cross(869 &mut self,870 caller: Caller,871 to: eth::CrossAddress,872 token_id: U256,873 ) -> Result<()> {874 let caller = T::CrossAccountId::from_eth(caller);875 let to = to.into_sub_cross_account::<T>()?;876 let token = token_id.try_into()?;877 let budget = self878 .recorder879 .weight_calls_budget(<StructureWeight<T>>::find_parent());880881 let balance = balance(self, token, &caller)?;882 ensure_single_owner(self, token, balance)?;883884 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)885 .map_err(dispatch_to_evm::<T>)?;886 Ok(())887 }888889 /// @notice Transfer ownership of an RFT890 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`891 /// is the zero address. Throws if `tokenId` is not a valid RFT.892 /// Throws if RFT pieces have multiple owners.893 /// @param to The new owner894 /// @param tokenId The RFT to transfer895 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]896 fn transfer_from_cross(897 &mut self,898 caller: Caller,899 from: eth::CrossAddress,900 to: eth::CrossAddress,901 token_id: U256,902 ) -> Result<()> {903 let caller = T::CrossAccountId::from_eth(caller);904 let from = from.into_sub_cross_account::<T>()?;905 let to = to.into_sub_cross_account::<T>()?;906 let token_id = token_id.try_into()?;907 let budget = self908 .recorder909 .weight_calls_budget(<StructureWeight<T>>::find_parent());910911 let balance = balance(self, token_id, &from)?;912 ensure_single_owner(self, token_id, balance)?;913914 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)915 .map_err(dispatch_to_evm::<T>)?;916 Ok(())917 }918919 /// @notice Burns a specific ERC721 token.920 /// @dev Throws unless `msg.sender` is the current owner or an authorized921 /// operator for this RFT. Throws if `from` is not the current owner. Throws922 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.923 /// Throws if RFT pieces have multiple owners.924 /// @param from The current owner of the RFT925 /// @param tokenId The RFT to transfer926 #[solidity(hide)]927 #[weight(<SelfWeightOf<T>>::burn_from())]928 fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {929 let caller = T::CrossAccountId::from_eth(caller);930 let from = T::CrossAccountId::from_eth(from);931 let token = token_id.try_into()?;932 let budget = self933 .recorder934 .weight_calls_budget(<StructureWeight<T>>::find_parent());935936 let balance = balance(self, token, &from)?;937 ensure_single_owner(self, token, balance)?;938939 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)940 .map_err(dispatch_to_evm::<T>)?;941 Ok(())942 }943944 /// @notice Burns a specific ERC721 token.945 /// @dev Throws unless `msg.sender` is the current owner or an authorized946 /// operator for this RFT. Throws if `from` is not the current owner. Throws947 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.948 /// Throws if RFT pieces have multiple owners.949 /// @param from The current owner of the RFT950 /// @param tokenId The RFT to transfer951 #[weight(<SelfWeightOf<T>>::burn_from())]952 fn burn_from_cross(953 &mut self,954 caller: Caller,955 from: eth::CrossAddress,956 token_id: U256,957 ) -> Result<()> {958 let caller = T::CrossAccountId::from_eth(caller);959 let from = from.into_sub_cross_account::<T>()?;960 let token = token_id.try_into()?;961 let budget = self962 .recorder963 .weight_calls_budget(<StructureWeight<T>>::find_parent());964965 let balance = balance(self, token, &from)?;966 ensure_single_owner(self, token, balance)?;967968 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)969 .map_err(dispatch_to_evm::<T>)?;970 Ok(())971 }972973 /// @notice Returns next free RFT ID.974 fn next_token_id(&self) -> Result<U256> {975 self.consume_store_reads(1)?;976 Ok(<TokensMinted<T>>::get(self.id)977 .checked_add(1)978 .ok_or("item id overflow")?979 .into())980 }981982 /// @notice Function to mint multiple tokens.983 /// @dev `tokenIds` should be an array of consecutive numbers and first number984 /// should be obtained with `nextTokenId` method985 /// @param to The new owner986 /// @param tokenIds IDs of the minted RFTs987 #[solidity(hide)]988 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]989 fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {990 let caller = T::CrossAccountId::from_eth(caller);991 let to = T::CrossAccountId::from_eth(to);992 let mut expected_index = <TokensMinted<T>>::get(self.id)993 .checked_add(1)994 .ok_or("item id overflow")?;995 let budget = self996 .recorder997 .weight_calls_budget(<StructureWeight<T>>::find_parent());998999 let total_tokens = token_ids.len();1000 for id in token_ids.into_iter() {1001 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1002 if id != expected_index {1003 return Err("item id should be next".into());1004 }1005 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;1006 }1007 let users = [(to, 1)]1008 .into_iter()1009 .collect::<BTreeMap<_, _>>()1010 .try_into()1011 .unwrap();1012 let create_item_data = CreateItemData::<T> {1013 users,1014 properties: CollectionPropertiesVec::default(),1015 };1016 let data = (0..total_tokens)1017 .map(|_| create_item_data.clone())1018 .collect();10191020 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1021 .map_err(dispatch_to_evm::<T>)?;1022 Ok(true)1023 }10241025 /// @notice Function to mint multiple tokens with the given tokenUris.1026 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive1027 /// numbers and first number should be obtained with `nextTokenId` method1028 /// @param to The new owner1029 /// @param tokens array of pairs of token ID and token URI for minted tokens1030 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1031 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]1032 fn mint_bulk_with_token_uri(1033 &mut self,1034 caller: Caller,1035 to: Address,1036 tokens: Vec<TokenUri>,1037 ) -> Result<bool> {1038 let key = key::url();1039 let caller = T::CrossAccountId::from_eth(caller);1040 let to = T::CrossAccountId::from_eth(to);1041 let mut expected_index = <TokensMinted<T>>::get(self.id)1042 .checked_add(1)1043 .ok_or("item id overflow")?;1044 let budget = self1045 .recorder1046 .weight_calls_budget(<StructureWeight<T>>::find_parent());10471048 let mut data = Vec::with_capacity(tokens.len());1049 let users: BoundedBTreeMap<_, _, _> = [(to, 1)]1050 .into_iter()1051 .collect::<BTreeMap<_, _>>()1052 .try_into()1053 .unwrap();1054 for TokenUri { id, uri } in tokens {1055 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1056 if id != expected_index {1057 return Err("item id should be next".into());1058 }1059 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10601061 let mut properties = CollectionPropertiesVec::default();1062 properties1063 .try_push(Property {1064 key: key.clone(),1065 value: uri1066 .into_bytes()1067 .try_into()1068 .map_err(|_| "token uri is too long")?,1069 })1070 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;10711072 let create_item_data = CreateItemData::<T> {1073 users: users.clone(),1074 properties,1075 };1076 data.push(create_item_data);1077 }10781079 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1080 .map_err(dispatch_to_evm::<T>)?;1081 Ok(true)1082 }10831084 /// @notice Function to mint a token.1085 /// @param to The new owner crossAccountId1086 /// @param properties Properties of minted token1087 /// @return uint256 The id of the newly minted token1088 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1089 fn mint_cross(1090 &mut self,1091 caller: Caller,1092 to: eth::CrossAddress,1093 properties: Vec<eth::Property>,1094 ) -> Result<U256> {1095 let token_id = <TokensMinted<T>>::get(self.id)1096 .checked_add(1)1097 .ok_or("item id overflow")?;10981099 let to = to.into_sub_cross_account::<T>()?;11001101 let properties = properties1102 .into_iter()1103 .map(eth::Property::try_into)1104 .collect::<Result<Vec<_>>>()?1105 .try_into()1106 .map_err(|_| Error::Revert("too many properties".to_string()))?;11071108 let caller = T::CrossAccountId::from_eth(caller);11091110 let budget = self1111 .recorder1112 .weight_calls_budget(<StructureWeight<T>>::find_parent());11131114 let users = [(to, 1)]1115 .into_iter()1116 .collect::<BTreeMap<_, _>>()1117 .try_into()1118 .unwrap();1119 <Pallet<T>>::create_item(1120 self,1121 &caller,1122 CreateItemData::<T> { users, properties },1123 &budget,1124 )1125 .map_err(dispatch_to_evm::<T>)?;11261127 Ok(token_id.into())1128 }11291130 /// Returns EVM address for refungible token1131 ///1132 /// @param token ID of the token1133 fn token_contract_address(&self, token: U256) -> Result<Address> {1134 Ok(T::EvmTokenAddressMapping::token_to_address(1135 self.id,1136 token.try_into().map_err(|_| "token id overflow")?,1137 ))1138 }11391140 /// @notice Returns collection helper contract address1141 fn collection_helper_address(&self) -> Result<Address> {1142 Ok(T::ContractAddress::get())1143 }1144}11451146#[solidity_interface(1147 name = UniqueRefungible,1148 is(1149 ERC721,1150 ERC721Enumerable,1151 ERC721UniqueExtensions,1152 ERC721UniqueMintable,1153 ERC721Burnable,1154 ERC721Metadata(if(this.flags.erc721metadata)),1155 Collection(via(common_mut returns CollectionHandle<T>)),1156 TokenProperties,1157 ),1158 enum(derive(PreDispatch)),1159)]1160impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}11611162// Not a tests, but code generators1163generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1164generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);11651166impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1167where1168 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1169{1170 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1171 fn call(1172 self,1173 handle: &mut impl PrecompileHandle,1174 ) -> Option<pallet_common::erc::PrecompileResult> {1175 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1176 }1177}pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -97,7 +97,7 @@
use pallet_evm_coder_substrate::WithRecorder;
use pallet_common::{
CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,
- Event as CommonEvent, Pallet as PalletCommon,
+ Event as CommonEvent, Pallet as PalletCommon, SetPropertyMode,
};
use pallet_structure::Pallet as PalletStructure;
use sp_core::{Get, H160};
@@ -521,8 +521,6 @@
/// * removes a property under the <key> if the value is `None` `(<key>, None)`.
///
/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
- /// - `is_token_create`: Indicates that method is called during token initialization.
- /// Allows to bypass ownership check.
///
/// All affected properties should have `mutable` permission
/// to be **deleted** or to be **set more than once**,
@@ -537,27 +535,38 @@
sender: &T::CrossAccountId,
token_id: TokenId,
properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
- is_token_create: bool,
+ mode: SetPropertyMode,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- let is_token_owner = || -> Result<bool, DispatchError> {
- let balance = collection.balance(sender.clone(), token_id);
- let total_pieces: u128 =
- Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);
- if balance != total_pieces {
- return Ok(false);
- }
+ let mut is_token_owner =
+ pallet_common::LazyValue::new(|| -> Result<bool, DispatchError> {
+ if let SetPropertyMode::NewToken {
+ mint_target_is_sender,
+ } = mode
+ {
+ return Ok(mint_target_is_sender);
+ }
- let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(
- sender.clone(),
- collection.id,
- token_id,
- None,
- nesting_budget,
- )?;
+ let balance = collection.balance(sender.clone(), token_id);
+ let total_pieces: u128 =
+ Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);
+ if balance != total_pieces {
+ return Ok(false);
+ }
+
+ let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(
+ sender.clone(),
+ collection.id,
+ token_id,
+ None,
+ nesting_budget,
+ )?;
+
+ Ok(is_bundle_owner)
+ });
- Ok(is_bundle_owner)
- };
+ let mut is_token_exist =
+ pallet_common::LazyValue::new(|| Self::token_exists(collection, token_id));
let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));
@@ -565,10 +574,10 @@
collection,
sender,
token_id,
+ &mut is_token_exist,
properties_updates,
- is_token_create,
stored_properties,
- is_token_owner,
+ &mut is_token_owner,
|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),
erc::ERC721TokenEvent::TokenChanged {
token_id: token_id.into(),
@@ -577,12 +586,25 @@
)
}
+ pub fn next_token_id(collection: &RefungibleHandle<T>) -> Result<TokenId, DispatchError> {
+ let next_token_id = <TokensMinted<T>>::get(collection.id)
+ .checked_add(1)
+ .ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;
+
+ ensure!(
+ collection.limits.token_limit() >= next_token_id,
+ <CommonError<T>>::CollectionTokenLimitExceeded
+ );
+
+ Ok(TokenId(next_token_id))
+ }
+
pub fn set_token_properties(
collection: &RefungibleHandle<T>,
sender: &T::CrossAccountId,
token_id: TokenId,
properties: impl Iterator<Item = Property>,
- is_token_create: bool,
+ mode: SetPropertyMode,
nesting_budget: &dyn Budget,
) -> DispatchResult {
Self::modify_token_properties(
@@ -590,7 +612,7 @@
sender,
token_id,
properties.map(|p| (p.key, Some(p.value))),
- is_token_create,
+ mode,
nesting_budget,
)
}
@@ -602,14 +624,12 @@
property: Property,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- let is_token_create = false;
-
Self::set_token_properties(
collection,
sender,
token_id,
[property].into_iter(),
- is_token_create,
+ SetPropertyMode::ExistingToken,
nesting_budget,
)
}
@@ -621,14 +641,12 @@
property_keys: impl Iterator<Item = PropertyKey>,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- let is_token_create = false;
-
Self::modify_token_properties(
collection,
sender,
token_id,
property_keys.into_iter().map(|key| (key, None)),
- is_token_create,
+ SetPropertyMode::ExistingToken,
nesting_budget,
)
}
@@ -914,10 +932,14 @@
let token_id = first_token_id + i as u32 + 1;
<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);
+ let mut mint_target_is_sender = true;
for (user, amount) in data.users.iter() {
if *amount == 0 {
continue;
}
+
+ mint_target_is_sender = mint_target_is_sender && sender.conv_eq(user);
+
<Balance<T>>::insert((collection.id, token_id, &user), amount);
<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);
<PalletStructure<T>>::nest_if_sent_to_token_unchecked(
@@ -932,7 +954,9 @@
sender,
TokenId(token_id),
data.properties.clone().into_iter(),
- true,
+ SetPropertyMode::NewToken {
+ mint_target_is_sender,
+ },
nesting_budget,
) {
return TransactionOutcome::Rollback(Err(e));
runtime/common/ethereum/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -22,7 +22,7 @@
use pallet_evm::account::CrossAccountId;
use pallet_evm_transaction_payment::CallContext;
use pallet_nonfungible::{
- Config as NonfungibleConfig,
+ Config as NonfungibleConfig, Pallet as NonfungiblePallet, NonfungibleHandle,
erc::{
UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721UniqueMintableCall, ERC721Call,
TokenPropertiesCall,
@@ -56,6 +56,8 @@
pub struct UniqueEthSponsorshipHandler<T: UniqueConfig>(PhantomData<*const T>);
impl<T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig>
SponsorshipHandler<T::CrossAccountId, CallContext> for UniqueEthSponsorshipHandler<T>
+where
+ T::AccountId: From<[u8; 32]>,
{
fn get_sponsor(
who: &T::CrossAccountId,
@@ -67,29 +69,71 @@
let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;
Some(T::CrossAccountId::from_sub(match &collection.mode {
CollectionMode::NFT => {
+ let collection = NonfungibleHandle::cast(collection);
let call = <UniqueNFTCall<T>>::parse(method_id, &mut reader).ok()??;
match call {
- UniqueNFTCall::TokenProperties(TokenPropertiesCall::SetProperty {
- token_id,
- key,
- value,
- ..
- }) => {
- let token_id: TokenId = token_id.try_into().ok()?;
- withdraw_set_token_property::<T>(
- &collection,
- who,
- &token_id,
- key.len() + value.len(),
- )
- .map(|()| sponsor)
- }
- UniqueNFTCall::ERC721UniqueExtensions(
- ERC721UniqueExtensionsCall::Transfer { token_id, .. },
- ) => {
- let token_id: TokenId = token_id.try_into().ok()?;
- withdraw_transfer::<T>(&collection, who, &token_id).map(|()| sponsor)
- }
+ UniqueNFTCall::TokenProperties(call) => match call {
+ TokenPropertiesCall::SetProperty {
+ token_id,
+ key,
+ value,
+ ..
+ } => {
+ let token_id: TokenId = token_id.try_into().ok()?;
+ withdraw_set_existing_token_property::<T>(
+ &collection,
+ who,
+ &token_id,
+ key.len() + value.len(),
+ )
+ .map(|()| sponsor)
+ }
+ TokenPropertiesCall::SetProperties {
+ token_id,
+ properties,
+ ..
+ } => {
+ let token_id: TokenId = token_id.try_into().ok()?;
+ let data_size = properties
+ .into_iter()
+ .map(|p| p.key().len() + p.value().len())
+ .sum();
+
+ withdraw_set_existing_token_property::<T>(
+ &collection,
+ who,
+ &token_id,
+ data_size,
+ )
+ .map(|()| sponsor)
+ }
+ _ => None,
+ },
+ UniqueNFTCall::ERC721UniqueExtensions(call) => match call {
+ ERC721UniqueExtensionsCall::Transfer { token_id, .. } => {
+ let token_id: TokenId = token_id.try_into().ok()?;
+ withdraw_transfer::<T>(&collection, who, &token_id)
+ .map(|()| sponsor)
+ }
+ ERC721UniqueExtensionsCall::MintCross { properties, .. } => {
+ withdraw_create_item::<T>(
+ &collection,
+ who,
+ &CreateItemData::NFT(CreateNftData::default()),
+ )?;
+
+ let token_id =
+ <NonfungiblePallet<T>>::next_token_id(&collection).ok()?;
+ let data_size: usize = properties
+ .into_iter()
+ .map(|p| p.key().len() + p.value().len())
+ .sum();
+
+ withdraw_set_token_property::<T>(&collection, &token_id, data_size)
+ .map(|()| sponsor)
+ }
+ _ => None,
+ },
UniqueNFTCall::ERC721UniqueMintable(
ERC721UniqueMintableCall::Mint { .. }
| ERC721UniqueMintableCall::MintCheckId { .. }
runtime/common/ethereum/sponsoring/refungible.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring/refungible.rs
+++ b/runtime/common/ethereum/sponsoring/refungible.rs
@@ -94,7 +94,12 @@
..
} => {
let token_id = TokenId::try_from(token_id).ok()?;
- withdraw_set_token_property::<T>(&collection, who, &token_id, key.len() + value.len())
+ withdraw_set_existing_token_property::<T>(
+ &collection,
+ who,
+ &token_id,
+ key.len() + value.len(),
+ )
}
}
}
runtime/common/sponsoring.rsdiffbeforeafterboth--- a/runtime/common/sponsoring.rs
+++ b/runtime/common/sponsoring.rs
@@ -39,7 +39,7 @@
impl<T> Config for T where T: UniqueConfig + FungibleConfig + NonfungibleConfig + RefungibleConfig {}
// TODO: permission check?
-pub fn withdraw_set_token_property<T: Config>(
+pub fn withdraw_set_existing_token_property<T: Config>(
collection: &CollectionHandle<T>,
who: &T::CrossAccountId,
item_id: &TokenId,
@@ -64,6 +64,17 @@
}
}
+ withdraw_set_token_property(collection, item_id, data_size)
+}
+
+pub fn withdraw_set_token_property<T: Config>(
+ collection: &CollectionHandle<T>,
+ item_id: &TokenId,
+ data_size: usize,
+) -> Option<()> {
+ if data_size == 0 {
+ return Some(());
+ }
if data_size > collection.limits.sponsored_data_size() as usize {
return None;
}
@@ -173,7 +184,6 @@
return None;
}
}
-
CreateItemBasket::<T>::insert((collection.id, who.as_sub()), block_number);
Some(())
@@ -237,7 +247,7 @@
..
} => {
let (sponsor, collection) = load::<T>(*collection_id)?;
- withdraw_set_token_property(
+ withdraw_set_existing_token_property(
&collection,
&T::CrossAccountId::from_sub(who.clone()),
token_id,
runtime/tests/Cargo.tomldiffbeforeafterboth--- a/runtime/tests/Cargo.toml
+++ b/runtime/tests/Cargo.toml
@@ -5,6 +5,7 @@
[features]
default = ['refungible']
+tests = ['pallet-common/tests']
refungible = []
runtime/tests/src/tests.rsdiffbeforeafterboth--- a/runtime/tests/src/tests.rs
+++ b/runtime/tests/src/tests.rs
@@ -1737,6 +1737,11 @@
let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
let origin1 = RuntimeOrigin::signed(1);
+ assert_ok!(Unique::add_collection_admin(
+ origin1.clone(),
+ collection_id,
+ account(1)
+ ));
let data = default_nft_data();
create_test_item(collection_id, &data.into());
@@ -2610,3 +2615,67 @@
));
});
}
+
+mod check_token_permissions {
+ use super::*;
+ use frame_support::once_cell::sync::Lazy;
+ use pallet_common::LazyValue;
+ use sp_runtime::DispatchError;
+
+ fn test<FTE: FnOnce() -> bool>(
+ i: usize,
+ test_case: &pallet_common::tests::TestCase,
+ check_token_existence: &mut LazyValue<bool, FTE>,
+ ) {
+ let collection_admin = test_case.collection_admin;
+ let mut is_collection_admin = LazyValue::new(|| test_case.is_collection_admin);
+ let token_owner = test_case.token_owner;
+ let mut is_token_owner = LazyValue::new(|| Ok(test_case.is_token_owner));
+ let is_no_permission = test_case.no_permission;
+
+ let result = pallet_common::tests::check_token_permissions::<Test, _, _, FTE>(
+ collection_admin,
+ token_owner,
+ &mut is_collection_admin,
+ &mut is_token_owner,
+ check_token_existence,
+ );
+
+ if is_no_permission {
+ assert!(
+ result.is_err(),
+ "{i}: {test_case:?}, token_exist: {}",
+ check_token_existence.value()
+ );
+ assert_err!(result, pallet_common::Error::<Test>::NoPermission,);
+ } else if check_token_existence.has_value() && !check_token_existence.value() {
+ assert!(
+ result.is_err(),
+ "{i}: {test_case:?}, token_exist: {}",
+ check_token_existence.value()
+ );
+ assert_err!(result, pallet_common::Error::<Test>::TokenNotFound,);
+ }
+ }
+
+ #[test]
+ fn no_permission_only() {
+ new_test_ext().execute_with(|| {
+ let mut check_token_existence = LazyValue::new(|| true);
+ for (i, row) in pallet_common::tests::table.iter().enumerate() {
+ test(i, row, &mut check_token_existence);
+ }
+ });
+ }
+
+ #[test]
+ fn no_permission_and_token_not_found() {
+ new_test_ext().execute_with(|| {
+ for (i, row) in pallet_common::tests::table.iter().enumerate() {
+ // This is inside the loop to keep track of whether the lambda was called
+ let mut check_token_existence = LazyValue::new(|| false);
+ test(i, row, &mut check_token_existence);
+ }
+ });
+ }
+}
tests/src/createMultipleItemsEx.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItemsEx.test.ts
+++ b/tests/src/createMultipleItemsEx.test.ts
@@ -195,7 +195,7 @@
description: 'descr',
tokenPrefix: 'COL',
tokenPropertyPermissions: [
- {key: 'k', permission: {tokenOwner: true, mutable: false, collectionAdmin: false}},
+ {key: 'k', permission: {tokenOwner: false, mutable: false, collectionAdmin: true}},
],
});
tests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -17,6 +17,7 @@
import {IKeyringPair} from '@polkadot/types/types';
import {Pallets, requirePalletsOrSkip, usingPlaygrounds} from '../util/index';
import {itEth, expect} from './util';
+import {CollectionLimitField, TokenPermissionField} from './util/playgrounds/types';
describe('evm nft collection sponsoring', () => {
let donor: IKeyringPair;
@@ -138,8 +139,7 @@
expect(sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsorEth, true));
// Create user with no balance:
- const user = helper.eth.createAccount();
- const userCross = helper.ethCrossAccount.fromAddress(user);
+ const user = helper.ethCrossAccount.createAccount();
const nextTokenId = await collectionEvm.methods.nextTokenId().call();
expect(nextTokenId).to.be.equal('1');
@@ -149,20 +149,29 @@
expect(oldPermissions.access).to.be.equal('Normal');
await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});
- await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});
+ await collectionEvm.methods.addToCollectionAllowListCross(user).send({from: owner});
await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
+ await collectionEvm.methods.setCollectionLimit({field: CollectionLimitField.SponsoredDataRateLimit, value: {status: true, value: 30}}).send();
const newPermissions = (await collectionSub.getData())!.raw.permissions;
expect(newPermissions.mintMode).to.be.true;
expect(newPermissions.access).to.be.equal('AllowList');
+ // Set token permissions
+ await collectionEvm.methods.setTokenPropertyPermissions([
+ ['key', [
+ [TokenPermissionField.TokenOwner, true],
+ ],
+ ],
+ ]).send({from: owner});
+
const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
- const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+ const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));
// User can mint token without balance:
{
- const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
+ const result = await collectionEvm.methods.mintCross(user, [{key: 'key', value: Buffer.from('Value')}]).send({from: user.eth});
const event = helper.eth.normalizeEvents(result.events)
.find(event => event.event === 'Transfer');
@@ -171,22 +180,102 @@
event: 'Transfer',
args: {
from: '0x0000000000000000000000000000000000000000',
- to: user,
+ to: user.eth,
tokenId: '1',
},
});
+ // await collectionEvm.methods.setProperties(1, [{key: 'key', value: Buffer.from('Value1')}]).send({from: user.eth});
+
const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
- const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
+ const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));
- expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+ expect(await collectionEvm.methods.properties(nextTokenId, []).call())
+ .to.be.like([
+ [
+ 'key',
+ '0x' + Buffer.from('Value').toString('hex'),
+ ],
+ ]);
expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
expect(userBalanceAfter).to.be.eq(userBalanceBefore);
expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;
}
}));
+ itEth('Can sponsor [set token properties] via access list', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const sponsorEth = await helper.eth.createAccountWithBalance(donor);
+ const sponsorCrossEth = helper.ethCrossAccount.fromAddress(sponsorEth);
+
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Sponsor collection', '1', '1', '');
+ const collectionEvm = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner, false);
+
+ // Set collection sponsor:
+ await collectionEvm.methods.setCollectionSponsorCross(sponsorCrossEth).send({from: owner});
+
+ // Sponsor can confirm sponsorship:
+ await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsorEth});
+
+ // Create user with no balance:
+ const user = helper.ethCrossAccount.createAccount();
+ const nextTokenId = await collectionEvm.methods.nextTokenId().call();
+ expect(nextTokenId).to.be.equal('1');
+
+ // Set collection permissions:
+ await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});
+ await collectionEvm.methods.addToCollectionAllowListCross(user).send({from: owner});
+ await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
+ await collectionEvm.methods.setCollectionLimit({field: CollectionLimitField.SponsoredDataRateLimit, value: {status: true, value: 30}}).send();
+
+ // Set token permissions
+ await collectionEvm.methods.setTokenPropertyPermissions([
+ ['key', [
+ [TokenPermissionField.TokenOwner, true],
+ ],
+ ],
+ ]).send({from: owner});
+
+ const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
+ const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));
+
+ // User can mint token without balance:
+ {
+ const result = await collectionEvm.methods.mintCross(user, []).send({from: user.eth});
+ const event = helper.eth.normalizeEvents(result.events)
+ .find(event => event.event === 'Transfer');
+
+ expect(event).to.be.deep.equal({
+ address: collectionAddress,
+ event: 'Transfer',
+ args: {
+ from: '0x0000000000000000000000000000000000000000',
+ to: user.eth,
+ tokenId: '1',
+ },
+ });
+
+ await collectionEvm.methods.setProperties(1, [{key: 'key', value: Buffer.from('Value')}]).send({from: user.eth});
+
+ const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
+ const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
+ const userBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user.eth));
+
+ expect(await collectionEvm.methods.properties(nextTokenId, []).call())
+ .to.be.like([
+ [
+ 'key',
+ '0x' + Buffer.from('Value').toString('hex'),
+ ],
+ ]);
+ expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
+ expect(userBalanceAfter).to.be.eq(userBalanceBefore);
+ expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;
+ }
+ });
+
// TODO: Temprorary off. Need refactor
// itWeb3('Sponsoring collection from substrate address via access list', async ({api, web3, privateKeyWrapper}) => {
// const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
@@ -456,6 +545,15 @@
expect(newPermissions.mintMode).to.be.true;
expect(newPermissions.access).to.be.equal('AllowList');
+ // Set token permissions
+ await collectionEvm.methods.setTokenPropertyPermissions([
+ ['URI', [
+ [TokenPermissionField.TokenOwner, true],
+ [TokenPermissionField.CollectionAdmin, true],
+ ],
+ ],
+ ]).send({from: owner});
+
const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsorEth));
const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
@@ -623,6 +721,15 @@
await collectionEvm.methods.addToCollectionAllowListCross(userCross).send({from: owner});
await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
+ // Set token permissions
+ await collectionEvm.methods.setTokenPropertyPermissions([
+ ['URI', [
+ [TokenPermissionField.TokenOwner, true],
+ [TokenPermissionField.CollectionAdmin, true],
+ ],
+ ],
+ ]).send({from: owner});
+
const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
const sponsorBalanceBefore = await helper.balance.getSubstrate(sponsor.address);
const userBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(user));
tests/src/eth/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/tokenProperties.test.ts
+++ b/tests/src/eth/tokenProperties.test.ts
@@ -553,6 +553,63 @@
]).call({from: owner})).to.be.rejectedWith('NoPermission');
}
}));
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Can't be multiple set/read for non-existent token`, testCase.requiredPallets, async({helper}) => {
+ const caller = await helper.eth.createAccountWithBalance(donor);
+
+ const properties = Array(5).fill(0).map((_, i) => { return {key: `key_${i}`, value: Buffer.from(`value_${i}`)}; });
+ const permissions: ITokenPropertyPermission[] = properties.map(p => { return {key: p.key, permission: {tokenOwner: true,
+ collectionAdmin: true,
+ mutable: true}}; });
+
+ const collection = await helper[testCase.mode].mintCollection(alice, {
+ tokenPrefix: 'ethp',
+ tokenPropertyPermissions: permissions,
+ }) as UniqueNFTCollection | UniqueRFTCollection;
+
+ await collection.addAdmin(alice, {Ethereum: caller});
+
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = await helper.ethNativeContract.collection(address, testCase.mode, caller);
+
+ await expect(contract.methods.setProperties(1, properties).call({from: caller})).to.be.rejectedWith('TokenNotFound');
+ }));
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itEth.ifWithPallets(`[${testCase.mode}] Can't be deleted for non-existent token`, testCase.requiredPallets, async({helper}) => {
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const collection = await helper[testCase.mode].mintCollection(alice, {
+ tokenPropertyPermissions: [{
+ key: 'testKey',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ },
+ },
+ {
+ key: 'testKey_1',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ },
+ }],
+ });
+
+
+ await collection.addAdmin(alice, {Ethereum: caller});
+
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const contract = await helper.ethNativeContract.collection(address, testCase.mode, caller);
+
+ await expect(contract.methods.deleteProperties(1, ['testKey', 'testKey_1']).call({from: caller})).to.be.rejectedWith('TokenNotFound');
+ }));
});
tests/src/getPropertiesRpc.test.tsdiffbeforeafterboth--- a/tests/src/getPropertiesRpc.test.ts
+++ b/tests/src/getPropertiesRpc.test.ts
@@ -120,3 +120,31 @@
expect(propPermissions).to.be.deep.equal(tokenPropPermissions);
});
});
+
+[
+ {mode: 'nft' as const},
+ {mode: 'rft' as const},
+].map(testCase =>
+ describe('negative properties', () => {
+ let alice: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (_, privateKey) => {
+ alice = await privateKey({url: import.meta.url});
+ });
+ });
+
+ itSub(`[${testCase.mode}] set token property for non-existent token`, async ({helper}) => {
+ const collection = await helper[testCase.mode].mintCollection(alice);
+ await collection.setTokenPropertyPermissions(alice, [{key: 'key', permission: {mutable: true, tokenOwner: true, collectionAdmin: true}}]);
+ await expect(collection.setTokenProperties(alice, 1, [{key: 'key', value: 'value'}])).to.be.rejectedWith('common.TokenNotFound');
+ expect(await collection.getTokenProperties(1, ['key'])).to.be.empty;
+ });
+
+ itSub(`[${testCase.mode}] delete token property for non-existent token`, async ({helper}) => {
+ const collection = await helper[testCase.mode].mintCollection(alice);
+ await collection.setTokenPropertyPermissions(alice, [{key: 'key', permission: {mutable: true, tokenOwner: true, collectionAdmin: true}}]);
+ await expect(collection.deleteTokenProperties(alice, 1, ['key'])).to.be.rejectedWith('common.TokenNotFound');
+ expect(await collection.getTokenProperties(1, ['key'])).to.be.empty;
+ });
+ }));
\ No newline at end of file
tests/src/nesting/tokenProperties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/tokenProperties.test.ts
+++ b/tests/src/nesting/tokenProperties.test.ts
@@ -448,6 +448,29 @@
expectedConsumedSpaceDiff = sizeOfProperty(biggerProp) - sizeOfProperty(smallerProp);
expect(consumedSpace).to.be.equal(sizeOfProperty(biggerProp) - expectedConsumedSpaceDiff);
}));
+
+ itSub('Set sponsored properties', async({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {tokenPropertyPermissions: [{key: 'k', permission: {tokenOwner: true}}]});
+
+ await collection.setSponsor(alice, alice.address);
+ await collection.confirmSponsorship(alice);
+ await collection.setPermissions(alice, {access: 'AllowList', mintMode: true});
+ await collection.addToAllowList(alice, {Substrate: bob.address});
+ await collection.setLimits(alice, {sponsoredDataRateLimit: {blocks: 30}});
+
+ const token = await collection.mintToken(alice, {Substrate: bob.address});
+
+ const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
+ const bobBalanceBefore = await helper.balance.getSubstrate(bob.address);
+
+ await token.setProperties(bob, [{key: 'k', value: 'val'}]);
+
+ const aliceBalanceAfter = await helper.balance.getSubstrate(alice.address);
+ const bobBalanceAfter = await helper.balance.getSubstrate(bob.address);
+
+ expect(bobBalanceAfter).to.be.equal(bobBalanceBefore);
+ expect(aliceBalanceBefore > aliceBalanceAfter).to.be.true;
+ });
});
describe('Negative Integration Test: Token Properties', () => {
@@ -475,6 +498,27 @@
});
});
+ [
+ {mode: 'nft' as const, requiredPallets: [Pallets.NFT]},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testCase =>
+ itSub.ifWithPallets(`Forbids adding/deleting properties of a token if token doesn't exist (${testCase.mode.toLocaleUpperCase})`, testCase.requiredPallets, async({helper}) => {
+ const collection = await helper[testCase.mode].mintCollection(alice, {
+ tokenPropertyPermissions: constitution.slice(0, 1).map(({permission}) => ({key: '1', permission})),
+ });
+ const nonExistentToken = collection.getTokenObject(1);
+
+ await expect(
+ nonExistentToken.setProperties(alice, [{key: '1', value: 'Serotonin increase'}]),
+ 'on expecting failure whilst adding a property by alice',
+ ).to.be.rejectedWith(/common\.TokenNotFound/);
+
+ await expect(
+ nonExistentToken.deleteProperties(alice, ['1']),
+ 'on expecting failure whilst deleting a property by alice',
+ ).to.be.rejectedWith(/common\.TokenNotFound/);
+ }));
+
async function mintCollectionWithAllPermissionsAndToken(helper: UniqueHelper, mode: 'NFT' | 'RFT'): Promise<[UniqueNFToken | UniqueRFToken, bigint]> {
const collection = await (mode == 'NFT' ? helper.nft : helper.rft).mintCollection(alice, {
tokenPropertyPermissions: constitution.map(({permission}, i) => ({key: `${i+1}`, permission})),