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.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//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible 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::BoundedVec;31use up_data_structs::{32 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,33 CollectionPropertiesVec,34};35use pallet_evm_coder_substrate::{36 dispatch_to_evm, frontier_contract,37 execution::{Result, PreDispatch, Error},38};39use sp_std::{vec::Vec, vec};40use pallet_common::{41 CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,42 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},43 eth::{self, TokenUri},44 CommonWeightInfo,45};46use pallet_evm::{account::CrossAccountId, PrecompileHandle};47use pallet_evm_coder_substrate::call;48use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};49use sp_core::{U256, Get};5051use crate::{52 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,53 TokenProperties, SelfWeightOf, weights::WeightInfo, common::CommonWeights,54};5556/// Nft events.57#[derive(ToLog)]58pub enum ERC721TokenEvent {59 /// The token has been changed.60 TokenChanged {61 /// Token ID.62 #[indexed]63 token_id: U256,64 },65}6667frontier_contract! {68 macro_rules! NonfungibleHandle_result {...}69 impl<T: Config> Contract for NonfungibleHandle<T> {...}70}7172/// @title A contract that allows to set and delete token properties and change token property permissions.73#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]74impl<T: Config> NonfungibleHandle<T> {75 /// @notice Set permissions for token property.76 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.77 /// @param key Property key.78 /// @param isMutable Permission to mutate property.79 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.80 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.81 #[solidity(hide)]82 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]83 fn set_token_property_permission(84 &mut self,85 caller: Caller,86 key: String,87 is_mutable: bool,88 collection_admin: bool,89 token_owner: bool,90 ) -> Result<()> {91 let caller = T::CrossAccountId::from_eth(caller);92 <Pallet<T>>::set_token_property_permissions(93 self,94 &caller,95 vec![PropertyKeyPermission {96 key: <Vec<u8>>::from(key)97 .try_into()98 .map_err(|_| "too long key")?,99 permission: PropertyPermission {100 mutable: is_mutable,101 collection_admin,102 token_owner,103 },104 }],105 )106 .map_err(dispatch_to_evm::<T>)107 }108109 /// @notice Set permissions for token property.110 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.111 /// @param permissions Permissions for keys.112 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]113 fn set_token_property_permissions(114 &mut self,115 caller: Caller,116 permissions: Vec<eth::TokenPropertyPermission>,117 ) -> Result<()> {118 let caller = T::CrossAccountId::from_eth(caller);119 let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;120121 <Pallet<T>>::set_token_property_permissions(self, &caller, perms)122 .map_err(dispatch_to_evm::<T>)123 }124125 /// @notice Get permissions for token properties.126 fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {127 let perms = <Pallet<T>>::token_property_permission(self.id);128 Ok(perms129 .into_iter()130 .map(eth::TokenPropertyPermission::from)131 .collect())132 }133134 /// @notice Set token property value.135 /// @dev Throws error if `msg.sender` has no permission to edit the property.136 /// @param tokenId ID of the token.137 /// @param key Property key.138 /// @param value Property value.139 #[solidity(hide)]140 #[weight(<SelfWeightOf<T>>::set_token_properties(1))]141 fn set_property(142 &mut self,143 caller: Caller,144 token_id: U256,145 key: String,146 value: Bytes,147 ) -> Result<()> {148 let caller = T::CrossAccountId::from_eth(caller);149 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;150 let key = <Vec<u8>>::from(key)151 .try_into()152 .map_err(|_| "key too long")?;153 let value = value.0.try_into().map_err(|_| "value too long")?;154155 let nesting_budget = self156 .recorder157 .weight_calls_budget(<StructureWeight<T>>::find_parent());158159 <Pallet<T>>::set_token_property(160 self,161 &caller,162 TokenId(token_id),163 Property { key, value },164 &nesting_budget,165 )166 .map_err(dispatch_to_evm::<T>)167 }168169 /// @notice Set token properties value.170 /// @dev Throws error if `msg.sender` has no permission to edit the property.171 /// @param tokenId ID of the token.172 /// @param properties settable properties173 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]174 fn set_properties(175 &mut self,176 caller: Caller,177 token_id: U256,178 properties: Vec<eth::Property>,179 ) -> Result<()> {180 let caller = T::CrossAccountId::from_eth(caller);181 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;182183 let nesting_budget = self184 .recorder185 .weight_calls_budget(<StructureWeight<T>>::find_parent());186187 let properties = properties188 .into_iter()189 .map(eth::Property::try_into)190 .collect::<Result<Vec<_>>>()?;191192 <Pallet<T>>::set_token_properties(193 self,194 &caller,195 TokenId(token_id),196 properties.into_iter(),197 false,198 &nesting_budget,199 )200 .map_err(dispatch_to_evm::<T>)201 }202203 /// @notice Delete token property value.204 /// @dev Throws error if `msg.sender` has no permission to edit the property.205 /// @param tokenId ID of the token.206 /// @param key Property key.207 #[solidity(hide)]208 #[weight(<SelfWeightOf<T>>::delete_token_properties(1))]209 fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {210 let caller = T::CrossAccountId::from_eth(caller);211 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;212 let key = <Vec<u8>>::from(key)213 .try_into()214 .map_err(|_| "key too long")?;215216 let nesting_budget = self217 .recorder218 .weight_calls_budget(<StructureWeight<T>>::find_parent());219220 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)221 .map_err(dispatch_to_evm::<T>)222 }223224 /// @notice Delete token properties value.225 /// @dev Throws error if `msg.sender` has no permission to edit the property.226 /// @param tokenId ID of the token.227 /// @param keys Properties key.228 #[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]229 fn delete_properties(230 &mut self,231 token_id: U256,232 caller: Caller,233 keys: Vec<String>,234 ) -> Result<()> {235 let caller = T::CrossAccountId::from_eth(caller);236 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;237 let keys = keys238 .into_iter()239 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))240 .collect::<Result<Vec<_>>>()?;241242 let nesting_budget = self243 .recorder244 .weight_calls_budget(<StructureWeight<T>>::find_parent());245246 <Pallet<T>>::delete_token_properties(247 self,248 &caller,249 TokenId(token_id),250 keys.into_iter(),251 &nesting_budget,252 )253 .map_err(dispatch_to_evm::<T>)254 }255256 /// @notice Get token property value.257 /// @dev Throws error if key not found258 /// @param tokenId ID of the token.259 /// @param key Property key.260 /// @return Property value bytes261 fn property(&self, token_id: U256, key: String) -> Result<Bytes> {262 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;263 let key = <Vec<u8>>::from(key)264 .try_into()265 .map_err(|_| "key too long")?;266267 let props = <TokenProperties<T>>::get((self.id, token_id));268 let prop = props.get(&key).ok_or("key not found")?;269270 Ok(prop.to_vec().into())271 }272}273274#[derive(ToLog)]275pub enum ERC721Events {276 /// @dev This emits when ownership of any NFT changes by any mechanism.277 /// This event emits when NFTs are created (`from` == 0) and destroyed278 /// (`to` == 0). Exception: during contract creation, any number of NFTs279 /// may be created and assigned without emitting Transfer. At the time of280 /// any transfer, the approved address for that NFT (if any) is reset to none.281 Transfer {282 #[indexed]283 from: Address,284 #[indexed]285 to: Address,286 #[indexed]287 token_id: U256,288 },289 /// @dev This emits when the approved address for an NFT is changed or290 /// reaffirmed. The zero address indicates there is no approved address.291 /// When a Transfer event emits, this also indicates that the approved292 /// address for that NFT (if any) is reset to none.293 Approval {294 #[indexed]295 owner: Address,296 #[indexed]297 approved: Address,298 #[indexed]299 token_id: U256,300 },301 /// @dev This emits when an operator is enabled or disabled for an owner.302 /// The operator can manage all NFTs of the owner.303 #[allow(dead_code)]304 ApprovalForAll {305 #[indexed]306 owner: Address,307 #[indexed]308 operator: Address,309 approved: bool,310 },311}312313/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension314/// @dev See https://eips.ethereum.org/EIPS/eip-721315#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f, enum(derive(PreDispatch)), enum_attr(weight))]316impl<T: Config> NonfungibleHandle<T>317where318 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,319{320 /// @notice A descriptive name for a collection of NFTs in this contract321 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`322 #[solidity(hide, rename_selector = "name")]323 fn name_proxy(&self) -> String {324 self.name()325 }326327 /// @notice An abbreviated name for NFTs in this contract328 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`329 #[solidity(hide, rename_selector = "symbol")]330 fn symbol_proxy(&self) -> String {331 self.symbol()332 }333334 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.335 ///336 /// @dev If the token has a `url` property and it is not empty, it is returned.337 /// 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`.338 /// If the collection property `baseURI` is empty or absent, return "" (empty string)339 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix340 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).341 ///342 /// @return token's const_metadata343 #[solidity(rename_selector = "tokenURI")]344 fn token_uri(&self, token_id: U256) -> Result<String> {345 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;346347 match get_token_property(self, token_id_u32, &key::url()).as_deref() {348 Err(_) | Ok("") => (),349 Ok(url) => {350 return Ok(url.into());351 }352 };353354 let base_uri =355 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())356 .map(BoundedVec::into_inner)357 .map(String::from_utf8)358 .transpose()359 .map_err(|e| {360 Error::Revert(alloc::format!(361 "Can not convert value \"baseURI\" to string with error \"{e}\""362 ))363 })?;364365 let base_uri = match base_uri.as_deref() {366 None | Some("") => {367 return Ok("".into());368 }369 Some(base_uri) => base_uri.into(),370 };371372 Ok(373 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {374 Err(_) | Ok("") => base_uri,375 Ok(suffix) => base_uri + suffix,376 },377 )378 }379}380381/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension382/// @dev See https://eips.ethereum.org/EIPS/eip-721383#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63, enum(derive(PreDispatch)), enum_attr(weight))]384impl<T: Config> NonfungibleHandle<T> {385 /// @notice Enumerate valid NFTs386 /// @param index A counter less than `totalSupply()`387 /// @return The token identifier for the `index`th NFT,388 /// (sort order not specified)389 fn token_by_index(&self, index: U256) -> U256 {390 index391 }392393 /// @dev Not implemented394 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {395 // TODO: Not implemetable396 Err("not implemented".into())397 }398399 /// @notice Count NFTs tracked by this contract400 /// @return A count of valid NFTs tracked by this contract, where each one of401 /// them has an assigned and queryable owner not equal to the zero address402 fn total_supply(&self) -> Result<U256> {403 self.consume_store_reads(1)?;404 Ok(<Pallet<T>>::total_supply(self).into())405 }406}407408/// @title ERC-721 Non-Fungible Token Standard409/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md410#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]411impl<T: Config> NonfungibleHandle<T> {412 /// @notice Count all NFTs assigned to an owner413 /// @dev NFTs assigned to the zero address are considered invalid, and this414 /// function throws for queries about the zero address.415 /// @param owner An address for whom to query the balance416 /// @return The number of NFTs owned by `owner`, possibly zero417 fn balance_of(&self, owner: Address) -> Result<U256> {418 self.consume_store_reads(1)?;419 let owner = T::CrossAccountId::from_eth(owner);420 let balance = <AccountBalance<T>>::get((self.id, owner));421 Ok(balance.into())422 }423 /// @notice Find the owner of an NFT424 /// @dev NFTs assigned to zero address are considered invalid, and queries425 /// about them do throw.426 /// @param tokenId The identifier for an NFT427 /// @return The address of the owner of the NFT428 fn owner_of(&self, token_id: U256) -> Result<Address> {429 self.consume_store_reads(1)?;430 let token: TokenId = token_id.try_into()?;431 Ok(*<TokenData<T>>::get((self.id, token))432 .ok_or("token not found")?433 .owner434 .as_eth())435 }436 /// @dev Not implemented437 #[solidity(rename_selector = "safeTransferFrom")]438 fn safe_transfer_from_with_data(439 &mut self,440 _from: Address,441 _to: Address,442 _token_id: U256,443 _data: Bytes,444 ) -> Result<()> {445 // TODO: Not implemetable446 Err("not implemented".into())447 }448 /// @dev Not implemented449 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {450 // TODO: Not implemetable451 Err("not implemented".into())452 }453454 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE455 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE456 /// THEY MAY BE PERMANENTLY LOST457 /// @dev Throws unless `msg.sender` is the current owner or an authorized458 /// operator for this NFT. Throws if `from` is not the current owner. Throws459 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.460 /// @param from The current owner of the NFT461 /// @param to The new owner462 /// @param tokenId The NFT to transfer463 #[weight(<CommonWeights<T>>::transfer_from())]464 fn transfer_from(465 &mut self,466 caller: Caller,467 from: Address,468 to: Address,469 token_id: U256,470 ) -> Result<()> {471 let caller = T::CrossAccountId::from_eth(caller);472 let from = T::CrossAccountId::from_eth(from);473 let to = T::CrossAccountId::from_eth(to);474 let token = token_id.try_into()?;475 let budget = self476 .recorder477 .weight_calls_budget(<StructureWeight<T>>::find_parent());478479 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)480 .map_err(|e| dispatch_to_evm::<T>(e.error))?;481 Ok(())482 }483484 /// @notice Set or reaffirm the approved address for an NFT485 /// @dev The zero address indicates there is no approved address.486 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized487 /// operator of the current owner.488 /// @param approved The new approved NFT controller489 /// @param tokenId The NFT to approve490 #[weight(<SelfWeightOf<T>>::approve())]491 fn approve(&mut self, caller: Caller, approved: Address, token_id: U256) -> Result<()> {492 let caller = T::CrossAccountId::from_eth(caller);493 let approved = T::CrossAccountId::from_eth(approved);494 let token = token_id.try_into()?;495496 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))497 .map_err(dispatch_to_evm::<T>)?;498 Ok(())499 }500501 /// @notice Sets or unsets the approval of a given operator.502 /// The `operator` is allowed to transfer all tokens of the `caller` on their behalf.503 /// @param operator Operator504 /// @param approved Should operator status be granted or revoked?505 #[weight(<SelfWeightOf<T>>::set_allowance_for_all())]506 fn set_approval_for_all(507 &mut self,508 caller: Caller,509 operator: Address,510 approved: bool,511 ) -> Result<()> {512 let caller = T::CrossAccountId::from_eth(caller);513 let operator = T::CrossAccountId::from_eth(operator);514515 <Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)516 .map_err(dispatch_to_evm::<T>)?;517 Ok(())518 }519520 /// @notice Get the approved address for a single NFT521 /// @dev Throws if `tokenId` is not a valid NFT522 /// @param tokenId The NFT to find the approved address for523 /// @return The approved address for this NFT, or the zero address if there is none524 fn get_approved(&self, token_id: U256) -> Result<Address> {525 let token_id = token_id.try_into()?;526 let operator = <Pallet<T>>::get_allowance(self, token_id).map_err(dispatch_to_evm::<T>)?;527 Ok(if let Some(operator) = operator {528 *operator.as_eth()529 } else {530 Address::zero()531 })532 }533534 /// @notice Tells whether the given `owner` approves the `operator`.535 #[weight(<SelfWeightOf<T>>::allowance_for_all())]536 fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {537 let owner = T::CrossAccountId::from_eth(owner);538 let operator = T::CrossAccountId::from_eth(operator);539540 Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))541 }542}543544/// @title ERC721 Token that can be irreversibly burned (destroyed).545#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]546impl<T: Config> NonfungibleHandle<T> {547 /// @notice Burns a specific ERC721 token.548 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized549 /// operator of the current owner.550 /// @param tokenId The NFT to approve551 #[weight(<SelfWeightOf<T>>::burn_item())]552 fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {553 let caller = T::CrossAccountId::from_eth(caller);554 let token = token_id.try_into()?;555556 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;557 Ok(())558 }559}560561/// @title ERC721 minting logic.562#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]563impl<T: Config> NonfungibleHandle<T> {564 /// @notice Function to mint a token.565 /// @param to The new owner566 /// @return uint256 The id of the newly minted token567 #[weight(<SelfWeightOf<T>>::create_item())]568 fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {569 let token_id: U256 = <TokensMinted<T>>::get(self.id)570 .checked_add(1)571 .ok_or("item id overflow")?572 .into();573 self.mint_check_id(caller, to, token_id)?;574 Ok(token_id)575 }576577 /// @notice Function to mint a token.578 /// @dev `tokenId` should be obtained with `nextTokenId` method,579 /// unlike standard, you can't specify it manually580 /// @param to The new owner581 /// @param tokenId ID of the minted NFT582 #[solidity(hide, rename_selector = "mint")]583 #[weight(<SelfWeightOf<T>>::create_item())]584 fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {585 let caller = T::CrossAccountId::from_eth(caller);586 let to = T::CrossAccountId::from_eth(to);587 let token_id: u32 = token_id.try_into()?;588 let budget = self589 .recorder590 .weight_calls_budget(<StructureWeight<T>>::find_parent());591592 if <TokensMinted<T>>::get(self.id)593 .checked_add(1)594 .ok_or("item id overflow")?595 != token_id596 {597 return Err("item id should be next".into());598 }599600 <Pallet<T>>::create_item(601 self,602 &caller,603 CreateItemData::<T> {604 properties: BoundedVec::default(),605 owner: to,606 },607 &budget,608 )609 .map_err(dispatch_to_evm::<T>)?;610611 Ok(true)612 }613614 /// @notice Function to mint token with the given tokenUri.615 /// @param to The new owner616 /// @param tokenUri Token URI that would be stored in the NFT properties617 /// @return uint256 The id of the newly minted token618 #[solidity(rename_selector = "mintWithTokenURI")]619 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]620 fn mint_with_token_uri(621 &mut self,622 caller: Caller,623 to: Address,624 token_uri: String,625 ) -> Result<U256> {626 let token_id: U256 = <TokensMinted<T>>::get(self.id)627 .checked_add(1)628 .ok_or("item id overflow")?629 .into();630 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;631 Ok(token_id)632 }633634 /// @notice Function to mint token with the given tokenUri.635 /// @dev `tokenId` should be obtained with `nextTokenId` method,636 /// unlike standard, you can't specify it manually637 /// @param to The new owner638 /// @param tokenId ID of the minted NFT639 /// @param tokenUri Token URI that would be stored in the NFT properties640 #[solidity(hide, rename_selector = "mintWithTokenURI")]641 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]642 fn mint_with_token_uri_check_id(643 &mut self,644 caller: Caller,645 to: Address,646 token_id: U256,647 token_uri: String,648 ) -> Result<bool> {649 let key = key::url();650 let permission = get_token_permission::<T>(self.id, &key)?;651 if !permission.collection_admin {652 return Err("Operation is not allowed".into());653 }654655 let caller = T::CrossAccountId::from_eth(caller);656 let to = T::CrossAccountId::from_eth(to);657 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;658 let budget = self659 .recorder660 .weight_calls_budget(<StructureWeight<T>>::find_parent());661662 if <TokensMinted<T>>::get(self.id)663 .checked_add(1)664 .ok_or("item id overflow")?665 != token_id666 {667 return Err("item id should be next".into());668 }669670 let mut properties = CollectionPropertiesVec::default();671 properties672 .try_push(Property {673 key,674 value: token_uri675 .into_bytes()676 .try_into()677 .map_err(|_| "token uri is too long")?,678 })679 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;680681 <Pallet<T>>::create_item(682 self,683 &caller,684 CreateItemData::<T> {685 properties,686 owner: to,687 },688 &budget,689 )690 .map_err(dispatch_to_evm::<T>)?;691 Ok(true)692 }693}694695fn get_token_property<T: Config>(696 collection: &CollectionHandle<T>,697 token_id: u32,698 key: &up_data_structs::PropertyKey,699) -> Result<String> {700 collection.consume_store_reads(1)?;701 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))702 .map_err(|_| Error::Revert("Token properties not found".into()))?;703 if let Some(property) = properties.get(key) {704 return Ok(String::from_utf8_lossy(property).into());705 }706707 Err("Property tokenURI not found".into())708}709710fn get_token_permission<T: Config>(711 collection_id: CollectionId,712 key: &PropertyKey,713) -> Result<PropertyPermission> {714 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)715 .map_err(|_| Error::Revert("No permissions for collection".into()))?;716 let a = token_property_permissions717 .get(key)718 .map(Clone::clone)719 .ok_or_else(|| {720 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();721 Error::Revert(alloc::format!("No permission for key {key}"))722 })?;723 Ok(a)724}725726/// @title Unique extensions for ERC721.727#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]728impl<T: Config> NonfungibleHandle<T>729where730 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,731{732 /// @notice A descriptive name for a collection of NFTs in this contract733 fn name(&self) -> String {734 decode_utf16(self.name.iter().copied())735 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))736 .collect::<String>()737 }738739 /// @notice An abbreviated name for NFTs in this contract740 fn symbol(&self) -> String {741 String::from_utf8_lossy(&self.token_prefix).into()742 }743744 /// @notice A description for the collection.745 fn description(&self) -> String {746 decode_utf16(self.description.iter().copied())747 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))748 .collect::<String>()749 }750751 /// Returns the owner (in cross format) of the token.752 ///753 /// @param tokenId Id for the token.754 #[solidity(hide)]755 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {756 Self::owner_of_cross(self, token_id)757 }758759 /// Returns the owner (in cross format) of the token.760 ///761 /// @param tokenId Id for the token.762 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {763 Self::token_owner(self, token_id.try_into()?)764 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))765 .map_err(|_| Error::Revert("token not found".into()))766 }767768 /// @notice Count all NFTs assigned to an owner769 /// @param owner An cross address for whom to query the balance770 /// @return The number of NFTs owned by `owner`, possibly zero771 fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {772 self.consume_store_reads(1)?;773 let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));774 Ok(balance.into())775 }776777 /// Returns the token properties.778 ///779 /// @param tokenId Id for the token.780 /// @param keys Properties keys. Empty keys for all propertyes.781 /// @return Vector of properties key/value pairs.782 fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {783 let keys = keys784 .into_iter()785 .map(|key| {786 <Vec<u8>>::from(key)787 .try_into()788 .map_err(|_| Error::Revert("key too large".into()))789 })790 .collect::<Result<Vec<_>>>()?;791792 <Self as CommonCollectionOperations<T>>::token_properties(793 self,794 token_id.try_into()?,795 if keys.is_empty() { None } else { Some(keys) },796 )797 .into_iter()798 .map(eth::Property::try_from)799 .collect::<Result<Vec<_>>>()800 }801802 /// @notice Set or reaffirm the approved address for an NFT803 /// @dev The zero address indicates there is no approved address.804 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized805 /// operator of the current owner.806 /// @param approved The new substrate address approved NFT controller807 /// @param tokenId The NFT to approve808 #[weight(<SelfWeightOf<T>>::approve())]809 fn approve_cross(810 &mut self,811 caller: Caller,812 approved: eth::CrossAddress,813 token_id: U256,814 ) -> Result<()> {815 let caller = T::CrossAccountId::from_eth(caller);816 let approved = approved.into_sub_cross_account::<T>()?;817 let token = token_id.try_into()?;818819 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))820 .map_err(dispatch_to_evm::<T>)?;821 Ok(())822 }823824 /// @notice Transfer ownership of an NFT825 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`826 /// is the zero address. Throws if `tokenId` is not a valid NFT.827 /// @param to The new owner828 /// @param tokenId The NFT to transfer829 #[weight(<CommonWeights<T>>::transfer())]830 fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {831 let caller = T::CrossAccountId::from_eth(caller);832 let to = T::CrossAccountId::from_eth(to);833 let token = token_id.try_into()?;834 let budget = self835 .recorder836 .weight_calls_budget(<StructureWeight<T>>::find_parent());837838 <Pallet<T>>::transfer(self, &caller, &to, token, &budget)839 .map_err(|e| dispatch_to_evm::<T>(e.error))?;840 Ok(())841 }842843 /// @notice Transfer ownership of an NFT844 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`845 /// is the zero address. Throws if `tokenId` is not a valid NFT.846 /// @param to The new owner847 /// @param tokenId The NFT to transfer848 #[weight(<CommonWeights<T>>::transfer())]849 fn transfer_cross(850 &mut self,851 caller: Caller,852 to: eth::CrossAddress,853 token_id: U256,854 ) -> Result<()> {855 let caller = T::CrossAccountId::from_eth(caller);856 let to = to.into_sub_cross_account::<T>()?;857 let token = token_id.try_into()?;858 let budget = self859 .recorder860 .weight_calls_budget(<StructureWeight<T>>::find_parent());861862 <Pallet<T>>::transfer(self, &caller, &to, token, &budget)863 .map_err(|e| dispatch_to_evm::<T>(e.error))?;864 Ok(())865 }866867 /// @notice Transfer ownership of an NFT from cross account address to cross account address868 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`869 /// is the zero address. Throws if `tokenId` is not a valid NFT.870 /// @param from Cross acccount address of current owner871 /// @param to Cross acccount address of new owner872 /// @param tokenId The NFT to transfer873 #[weight(<CommonWeights<T>>::transfer_from())]874 fn transfer_from_cross(875 &mut self,876 caller: Caller,877 from: eth::CrossAddress,878 to: eth::CrossAddress,879 token_id: U256,880 ) -> Result<()> {881 let caller = T::CrossAccountId::from_eth(caller);882 let from = from.into_sub_cross_account::<T>()?;883 let to = to.into_sub_cross_account::<T>()?;884 let token_id = token_id.try_into()?;885 let budget = self886 .recorder887 .weight_calls_budget(<StructureWeight<T>>::find_parent());888 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)889 .map_err(|e| dispatch_to_evm::<T>(e.error))?;890 Ok(())891 }892893 /// @notice Burns a specific ERC721 token.894 /// @dev Throws unless `msg.sender` is the current owner or an authorized895 /// operator for this NFT. Throws if `from` is not the current owner. Throws896 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.897 /// @param from The current owner of the NFT898 /// @param tokenId The NFT to transfer899 #[solidity(hide)]900 #[weight(<SelfWeightOf<T>>::burn_from())]901 fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {902 let caller = T::CrossAccountId::from_eth(caller);903 let from = T::CrossAccountId::from_eth(from);904 let token = token_id.try_into()?;905 let budget = self906 .recorder907 .weight_calls_budget(<StructureWeight<T>>::find_parent());908909 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)910 .map_err(dispatch_to_evm::<T>)?;911 Ok(())912 }913914 /// @notice Burns a specific ERC721 token.915 /// @dev Throws unless `msg.sender` is the current owner or an authorized916 /// operator for this NFT. Throws if `from` is not the current owner. Throws917 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.918 /// @param from The current owner of the NFT919 /// @param tokenId The NFT to transfer920 #[weight(<SelfWeightOf<T>>::burn_from())]921 fn burn_from_cross(922 &mut self,923 caller: Caller,924 from: eth::CrossAddress,925 token_id: U256,926 ) -> Result<()> {927 let caller = T::CrossAccountId::from_eth(caller);928 let from = from.into_sub_cross_account::<T>()?;929 let token = token_id.try_into()?;930 let budget = self931 .recorder932 .weight_calls_budget(<StructureWeight<T>>::find_parent());933934 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)935 .map_err(dispatch_to_evm::<T>)?;936 Ok(())937 }938939 /// @notice Returns next free NFT ID.940 fn next_token_id(&self) -> Result<U256> {941 self.consume_store_reads(1)?;942 Ok(<TokensMinted<T>>::get(self.id)943 .checked_add(1)944 .ok_or("item id overflow")?945 .into())946 }947948 /// @notice Function to mint multiple tokens.949 /// @dev `tokenIds` should be an array of consecutive numbers and first number950 /// should be obtained with `nextTokenId` method951 /// @param to The new owner952 /// @param tokenIds IDs of the minted NFTs953 #[solidity(hide)]954 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]955 fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {956 let caller = T::CrossAccountId::from_eth(caller);957 let to = T::CrossAccountId::from_eth(to);958 let mut expected_index = <TokensMinted<T>>::get(self.id)959 .checked_add(1)960 .ok_or("item id overflow")?;961 let budget = self962 .recorder963 .weight_calls_budget(<StructureWeight<T>>::find_parent());964965 let total_tokens = token_ids.len();966 for id in token_ids.into_iter() {967 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;968 if id != expected_index {969 return Err("item id should be next".into());970 }971 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;972 }973 let data = (0..total_tokens)974 .map(|_| CreateItemData::<T> {975 properties: BoundedVec::default(),976 owner: to.clone(),977 })978 .collect();979980 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)981 .map_err(dispatch_to_evm::<T>)?;982 Ok(true)983 }984985 /// @notice Function to mint multiple tokens with the given tokenUris.986 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive987 /// numbers and first number should be obtained with `nextTokenId` method988 /// @param to The new owner989 /// @param tokens array of pairs of token ID and token URI for minted tokens990 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]991 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]992 fn mint_bulk_with_token_uri(993 &mut self,994 caller: Caller,995 to: Address,996 tokens: Vec<TokenUri>,997 ) -> Result<bool> {998 let key = key::url();999 let caller = T::CrossAccountId::from_eth(caller);1000 let to = T::CrossAccountId::from_eth(to);1001 let mut expected_index = <TokensMinted<T>>::get(self.id)1002 .checked_add(1)1003 .ok_or("item id overflow")?;1004 let budget = self1005 .recorder1006 .weight_calls_budget(<StructureWeight<T>>::find_parent());10071008 let mut data = Vec::with_capacity(tokens.len());1009 for TokenUri { id, uri } in tokens {1010 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1011 if id != expected_index {1012 return Err("item id should be next".into());1013 }1014 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10151016 let mut properties = CollectionPropertiesVec::default();1017 properties1018 .try_push(Property {1019 key: key.clone(),1020 value: uri1021 .into_bytes()1022 .try_into()1023 .map_err(|_| "token uri is too long")?,1024 })1025 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;10261027 data.push(CreateItemData::<T> {1028 properties,1029 owner: to.clone(),1030 });1031 }10321033 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1034 .map_err(dispatch_to_evm::<T>)?;1035 Ok(true)1036 }10371038 /// @notice Function to mint a token.1039 /// @param to The new owner crossAccountId1040 /// @param properties Properties of minted token1041 /// @return uint256 The id of the newly minted token1042 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1043 fn mint_cross(1044 &mut self,1045 caller: Caller,1046 to: eth::CrossAddress,1047 properties: Vec<eth::Property>,1048 ) -> Result<U256> {1049 let token_id = <TokensMinted<T>>::get(self.id)1050 .checked_add(1)1051 .ok_or("item id overflow")?;10521053 let to = to.into_sub_cross_account::<T>()?;10541055 let properties = properties1056 .into_iter()1057 .map(eth::Property::try_into)1058 .collect::<Result<Vec<_>>>()?1059 .try_into()1060 .map_err(|_| Error::Revert("too many properties".to_string()))?;10611062 let caller = T::CrossAccountId::from_eth(caller);10631064 let budget = self1065 .recorder1066 .weight_calls_budget(<StructureWeight<T>>::find_parent());10671068 <Pallet<T>>::create_item(1069 self,1070 &caller,1071 CreateItemData::<T> {1072 properties,1073 owner: to,1074 },1075 &budget,1076 )1077 .map_err(dispatch_to_evm::<T>)?;10781079 Ok(token_id.into())1080 }10811082 /// @notice Returns collection helper contract address1083 fn collection_helper_address(&self) -> Address {1084 T::ContractAddress::get()1085 }1086}10871088#[solidity_interface(1089 name = UniqueNFT,1090 is(1091 ERC721,1092 ERC721Enumerable,1093 ERC721UniqueExtensions,1094 ERC721UniqueMintable,1095 ERC721Burnable,1096 ERC721Metadata(if(this.flags.erc721metadata)),1097 Collection(via(common_mut returns CollectionHandle<T>)),1098 TokenProperties,1099 ),1100 enum(derive(PreDispatch)),1101)]1102impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}11031104// Not a tests, but code generators1105generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);1106generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);11071108impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>1109where1110 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1111{1112 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");11131114 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {1115 call::<T, UniqueNFTCall<T>, _, _>(handle, self)1116 }1117}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible 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::BoundedVec;31use up_data_structs::{32 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,33 CollectionPropertiesVec,34};35use pallet_evm_coder_substrate::{36 dispatch_to_evm, frontier_contract,37 execution::{Result, PreDispatch, Error},38};39use sp_std::{vec::Vec, vec};40use pallet_common::{41 CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,42 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},43 eth::{self, TokenUri},44 CommonWeightInfo,45};46use pallet_evm::{account::CrossAccountId, PrecompileHandle};47use pallet_evm_coder_substrate::call;48use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};49use sp_core::{U256, Get};5051use crate::{52 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,53 TokenProperties, SelfWeightOf, weights::WeightInfo, common::CommonWeights,54};5556/// Nft events.57#[derive(ToLog)]58pub enum ERC721TokenEvent {59 /// The token has been changed.60 TokenChanged {61 /// Token ID.62 #[indexed]63 token_id: U256,64 },65}6667frontier_contract! {68 macro_rules! NonfungibleHandle_result {...}69 impl<T: Config> Contract for NonfungibleHandle<T> {...}70}7172/// @title A contract that allows to set and delete token properties and change token property permissions.73#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]74impl<T: Config> NonfungibleHandle<T> {75 /// @notice Set permissions for token property.76 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.77 /// @param key Property key.78 /// @param isMutable Permission to mutate property.79 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.80 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.81 #[solidity(hide)]82 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]83 fn set_token_property_permission(84 &mut self,85 caller: Caller,86 key: String,87 is_mutable: bool,88 collection_admin: bool,89 token_owner: bool,90 ) -> Result<()> {91 let caller = T::CrossAccountId::from_eth(caller);92 <Pallet<T>>::set_token_property_permissions(93 self,94 &caller,95 vec![PropertyKeyPermission {96 key: <Vec<u8>>::from(key)97 .try_into()98 .map_err(|_| "too long key")?,99 permission: PropertyPermission {100 mutable: is_mutable,101 collection_admin,102 token_owner,103 },104 }],105 )106 .map_err(dispatch_to_evm::<T>)107 }108109 /// @notice Set permissions for token property.110 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.111 /// @param permissions Permissions for keys.112 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]113 fn set_token_property_permissions(114 &mut self,115 caller: Caller,116 permissions: Vec<eth::TokenPropertyPermission>,117 ) -> Result<()> {118 let caller = T::CrossAccountId::from_eth(caller);119 let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;120121 <Pallet<T>>::set_token_property_permissions(self, &caller, perms)122 .map_err(dispatch_to_evm::<T>)123 }124125 /// @notice Get permissions for token properties.126 fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {127 let perms = <Pallet<T>>::token_property_permission(self.id);128 Ok(perms129 .into_iter()130 .map(eth::TokenPropertyPermission::from)131 .collect())132 }133134 /// @notice Set token property value.135 /// @dev Throws error if `msg.sender` has no permission to edit the property.136 /// @param tokenId ID of the token.137 /// @param key Property key.138 /// @param value Property value.139 #[solidity(hide)]140 #[weight(<SelfWeightOf<T>>::set_token_properties(1))]141 fn set_property(142 &mut self,143 caller: Caller,144 token_id: U256,145 key: String,146 value: Bytes,147 ) -> Result<()> {148 let caller = T::CrossAccountId::from_eth(caller);149 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;150 let key = <Vec<u8>>::from(key)151 .try_into()152 .map_err(|_| "key too long")?;153 let value = value.0.try_into().map_err(|_| "value too long")?;154155 let nesting_budget = self156 .recorder157 .weight_calls_budget(<StructureWeight<T>>::find_parent());158159 <Pallet<T>>::set_token_property(160 self,161 &caller,162 TokenId(token_id),163 Property { key, value },164 &nesting_budget,165 )166 .map_err(dispatch_to_evm::<T>)167 }168169 /// @notice Set token properties value.170 /// @dev Throws error if `msg.sender` has no permission to edit the property.171 /// @param tokenId ID of the token.172 /// @param properties settable properties173 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]174 fn set_properties(175 &mut self,176 caller: Caller,177 token_id: U256,178 properties: Vec<eth::Property>,179 ) -> Result<()> {180 let caller = T::CrossAccountId::from_eth(caller);181 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;182183 let nesting_budget = self184 .recorder185 .weight_calls_budget(<StructureWeight<T>>::find_parent());186187 let properties = properties188 .into_iter()189 .map(eth::Property::try_into)190 .collect::<Result<Vec<_>>>()?;191192 <Pallet<T>>::set_token_properties(193 self,194 &caller,195 TokenId(token_id),196 properties.into_iter(),197 pallet_common::SetPropertyMode::ExistingToken,198 &nesting_budget,199 )200 .map_err(dispatch_to_evm::<T>)201 }202203 /// @notice Delete token property value.204 /// @dev Throws error if `msg.sender` has no permission to edit the property.205 /// @param tokenId ID of the token.206 /// @param key Property key.207 #[solidity(hide)]208 #[weight(<SelfWeightOf<T>>::delete_token_properties(1))]209 fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {210 let caller = T::CrossAccountId::from_eth(caller);211 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;212 let key = <Vec<u8>>::from(key)213 .try_into()214 .map_err(|_| "key too long")?;215216 let nesting_budget = self217 .recorder218 .weight_calls_budget(<StructureWeight<T>>::find_parent());219220 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)221 .map_err(dispatch_to_evm::<T>)222 }223224 /// @notice Delete token properties value.225 /// @dev Throws error if `msg.sender` has no permission to edit the property.226 /// @param tokenId ID of the token.227 /// @param keys Properties key.228 #[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]229 fn delete_properties(230 &mut self,231 token_id: U256,232 caller: Caller,233 keys: Vec<String>,234 ) -> Result<()> {235 let caller = T::CrossAccountId::from_eth(caller);236 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;237 let keys = keys238 .into_iter()239 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))240 .collect::<Result<Vec<_>>>()?;241242 let nesting_budget = self243 .recorder244 .weight_calls_budget(<StructureWeight<T>>::find_parent());245246 <Pallet<T>>::delete_token_properties(247 self,248 &caller,249 TokenId(token_id),250 keys.into_iter(),251 &nesting_budget,252 )253 .map_err(dispatch_to_evm::<T>)254 }255256 /// @notice Get token property value.257 /// @dev Throws error if key not found258 /// @param tokenId ID of the token.259 /// @param key Property key.260 /// @return Property value bytes261 fn property(&self, token_id: U256, key: String) -> Result<Bytes> {262 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;263 let key = <Vec<u8>>::from(key)264 .try_into()265 .map_err(|_| "key too long")?;266267 let props = <TokenProperties<T>>::get((self.id, token_id));268 let prop = props.get(&key).ok_or("key not found")?;269270 Ok(prop.to_vec().into())271 }272}273274#[derive(ToLog)]275pub enum ERC721Events {276 /// @dev This emits when ownership of any NFT changes by any mechanism.277 /// This event emits when NFTs are created (`from` == 0) and destroyed278 /// (`to` == 0). Exception: during contract creation, any number of NFTs279 /// may be created and assigned without emitting Transfer. At the time of280 /// any transfer, the approved address for that NFT (if any) is reset to none.281 Transfer {282 #[indexed]283 from: Address,284 #[indexed]285 to: Address,286 #[indexed]287 token_id: U256,288 },289 /// @dev This emits when the approved address for an NFT is changed or290 /// reaffirmed. The zero address indicates there is no approved address.291 /// When a Transfer event emits, this also indicates that the approved292 /// address for that NFT (if any) is reset to none.293 Approval {294 #[indexed]295 owner: Address,296 #[indexed]297 approved: Address,298 #[indexed]299 token_id: U256,300 },301 /// @dev This emits when an operator is enabled or disabled for an owner.302 /// The operator can manage all NFTs of the owner.303 #[allow(dead_code)]304 ApprovalForAll {305 #[indexed]306 owner: Address,307 #[indexed]308 operator: Address,309 approved: bool,310 },311}312313/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension314/// @dev See https://eips.ethereum.org/EIPS/eip-721315#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f, enum(derive(PreDispatch)), enum_attr(weight))]316impl<T: Config> NonfungibleHandle<T>317where318 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,319{320 /// @notice A descriptive name for a collection of NFTs in this contract321 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`322 #[solidity(hide, rename_selector = "name")]323 fn name_proxy(&self) -> String {324 self.name()325 }326327 /// @notice An abbreviated name for NFTs in this contract328 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`329 #[solidity(hide, rename_selector = "symbol")]330 fn symbol_proxy(&self) -> String {331 self.symbol()332 }333334 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.335 ///336 /// @dev If the token has a `url` property and it is not empty, it is returned.337 /// 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`.338 /// If the collection property `baseURI` is empty or absent, return "" (empty string)339 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix340 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).341 ///342 /// @return token's const_metadata343 #[solidity(rename_selector = "tokenURI")]344 fn token_uri(&self, token_id: U256) -> Result<String> {345 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;346347 match get_token_property(self, token_id_u32, &key::url()).as_deref() {348 Err(_) | Ok("") => (),349 Ok(url) => {350 return Ok(url.into());351 }352 };353354 let base_uri =355 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())356 .map(BoundedVec::into_inner)357 .map(String::from_utf8)358 .transpose()359 .map_err(|e| {360 Error::Revert(alloc::format!(361 "Can not convert value \"baseURI\" to string with error \"{e}\""362 ))363 })?;364365 let base_uri = match base_uri.as_deref() {366 None | Some("") => {367 return Ok("".into());368 }369 Some(base_uri) => base_uri.into(),370 };371372 Ok(373 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {374 Err(_) | Ok("") => base_uri,375 Ok(suffix) => base_uri + suffix,376 },377 )378 }379}380381/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension382/// @dev See https://eips.ethereum.org/EIPS/eip-721383#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63, enum(derive(PreDispatch)), enum_attr(weight))]384impl<T: Config> NonfungibleHandle<T> {385 /// @notice Enumerate valid NFTs386 /// @param index A counter less than `totalSupply()`387 /// @return The token identifier for the `index`th NFT,388 /// (sort order not specified)389 fn token_by_index(&self, index: U256) -> U256 {390 index391 }392393 /// @dev Not implemented394 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {395 // TODO: Not implemetable396 Err("not implemented".into())397 }398399 /// @notice Count NFTs tracked by this contract400 /// @return A count of valid NFTs tracked by this contract, where each one of401 /// them has an assigned and queryable owner not equal to the zero address402 fn total_supply(&self) -> Result<U256> {403 self.consume_store_reads(1)?;404 Ok(<Pallet<T>>::total_supply(self).into())405 }406}407408/// @title ERC-721 Non-Fungible Token Standard409/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md410#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]411impl<T: Config> NonfungibleHandle<T> {412 /// @notice Count all NFTs assigned to an owner413 /// @dev NFTs assigned to the zero address are considered invalid, and this414 /// function throws for queries about the zero address.415 /// @param owner An address for whom to query the balance416 /// @return The number of NFTs owned by `owner`, possibly zero417 fn balance_of(&self, owner: Address) -> Result<U256> {418 self.consume_store_reads(1)?;419 let owner = T::CrossAccountId::from_eth(owner);420 let balance = <AccountBalance<T>>::get((self.id, owner));421 Ok(balance.into())422 }423 /// @notice Find the owner of an NFT424 /// @dev NFTs assigned to zero address are considered invalid, and queries425 /// about them do throw.426 /// @param tokenId The identifier for an NFT427 /// @return The address of the owner of the NFT428 fn owner_of(&self, token_id: U256) -> Result<Address> {429 self.consume_store_reads(1)?;430 let token: TokenId = token_id.try_into()?;431 Ok(*<TokenData<T>>::get((self.id, token))432 .ok_or("token not found")?433 .owner434 .as_eth())435 }436 /// @dev Not implemented437 #[solidity(rename_selector = "safeTransferFrom")]438 fn safe_transfer_from_with_data(439 &mut self,440 _from: Address,441 _to: Address,442 _token_id: U256,443 _data: Bytes,444 ) -> Result<()> {445 // TODO: Not implemetable446 Err("not implemented".into())447 }448 /// @dev Not implemented449 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {450 // TODO: Not implemetable451 Err("not implemented".into())452 }453454 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE455 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE456 /// THEY MAY BE PERMANENTLY LOST457 /// @dev Throws unless `msg.sender` is the current owner or an authorized458 /// operator for this NFT. Throws if `from` is not the current owner. Throws459 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.460 /// @param from The current owner of the NFT461 /// @param to The new owner462 /// @param tokenId The NFT to transfer463 #[weight(<CommonWeights<T>>::transfer_from())]464 fn transfer_from(465 &mut self,466 caller: Caller,467 from: Address,468 to: Address,469 token_id: U256,470 ) -> Result<()> {471 let caller = T::CrossAccountId::from_eth(caller);472 let from = T::CrossAccountId::from_eth(from);473 let to = T::CrossAccountId::from_eth(to);474 let token = token_id.try_into()?;475 let budget = self476 .recorder477 .weight_calls_budget(<StructureWeight<T>>::find_parent());478479 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)480 .map_err(|e| dispatch_to_evm::<T>(e.error))?;481 Ok(())482 }483484 /// @notice Set or reaffirm the approved address for an NFT485 /// @dev The zero address indicates there is no approved address.486 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized487 /// operator of the current owner.488 /// @param approved The new approved NFT controller489 /// @param tokenId The NFT to approve490 #[weight(<SelfWeightOf<T>>::approve())]491 fn approve(&mut self, caller: Caller, approved: Address, token_id: U256) -> Result<()> {492 let caller = T::CrossAccountId::from_eth(caller);493 let approved = T::CrossAccountId::from_eth(approved);494 let token = token_id.try_into()?;495496 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))497 .map_err(dispatch_to_evm::<T>)?;498 Ok(())499 }500501 /// @notice Sets or unsets the approval of a given operator.502 /// The `operator` is allowed to transfer all tokens of the `caller` on their behalf.503 /// @param operator Operator504 /// @param approved Should operator status be granted or revoked?505 #[weight(<SelfWeightOf<T>>::set_allowance_for_all())]506 fn set_approval_for_all(507 &mut self,508 caller: Caller,509 operator: Address,510 approved: bool,511 ) -> Result<()> {512 let caller = T::CrossAccountId::from_eth(caller);513 let operator = T::CrossAccountId::from_eth(operator);514515 <Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)516 .map_err(dispatch_to_evm::<T>)?;517 Ok(())518 }519520 /// @notice Get the approved address for a single NFT521 /// @dev Throws if `tokenId` is not a valid NFT522 /// @param tokenId The NFT to find the approved address for523 /// @return The approved address for this NFT, or the zero address if there is none524 fn get_approved(&self, token_id: U256) -> Result<Address> {525 let token_id = token_id.try_into()?;526 let operator = <Pallet<T>>::get_allowance(self, token_id).map_err(dispatch_to_evm::<T>)?;527 Ok(if let Some(operator) = operator {528 *operator.as_eth()529 } else {530 Address::zero()531 })532 }533534 /// @notice Tells whether the given `owner` approves the `operator`.535 #[weight(<SelfWeightOf<T>>::allowance_for_all())]536 fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {537 let owner = T::CrossAccountId::from_eth(owner);538 let operator = T::CrossAccountId::from_eth(operator);539540 Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))541 }542}543544/// @title ERC721 Token that can be irreversibly burned (destroyed).545#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]546impl<T: Config> NonfungibleHandle<T> {547 /// @notice Burns a specific ERC721 token.548 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized549 /// operator of the current owner.550 /// @param tokenId The NFT to approve551 #[weight(<SelfWeightOf<T>>::burn_item())]552 fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {553 let caller = T::CrossAccountId::from_eth(caller);554 let token = token_id.try_into()?;555556 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;557 Ok(())558 }559}560561/// @title ERC721 minting logic.562#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]563impl<T: Config> NonfungibleHandle<T> {564 /// @notice Function to mint a token.565 /// @param to The new owner566 /// @return uint256 The id of the newly minted token567 #[weight(<SelfWeightOf<T>>::create_item())]568 fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {569 let token_id: U256 = <TokensMinted<T>>::get(self.id)570 .checked_add(1)571 .ok_or("item id overflow")?572 .into();573 self.mint_check_id(caller, to, token_id)?;574 Ok(token_id)575 }576577 /// @notice Function to mint a token.578 /// @dev `tokenId` should be obtained with `nextTokenId` method,579 /// unlike standard, you can't specify it manually580 /// @param to The new owner581 /// @param tokenId ID of the minted NFT582 #[solidity(hide, rename_selector = "mint")]583 #[weight(<SelfWeightOf<T>>::create_item())]584 fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {585 let caller = T::CrossAccountId::from_eth(caller);586 let to = T::CrossAccountId::from_eth(to);587 let token_id: u32 = token_id.try_into()?;588 let budget = self589 .recorder590 .weight_calls_budget(<StructureWeight<T>>::find_parent());591592 if <TokensMinted<T>>::get(self.id)593 .checked_add(1)594 .ok_or("item id overflow")?595 != token_id596 {597 return Err("item id should be next".into());598 }599600 <Pallet<T>>::create_item(601 self,602 &caller,603 CreateItemData::<T> {604 properties: BoundedVec::default(),605 owner: to,606 },607 &budget,608 )609 .map_err(dispatch_to_evm::<T>)?;610611 Ok(true)612 }613614 /// @notice Function to mint token with the given tokenUri.615 /// @param to The new owner616 /// @param tokenUri Token URI that would be stored in the NFT properties617 /// @return uint256 The id of the newly minted token618 #[solidity(rename_selector = "mintWithTokenURI")]619 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]620 fn mint_with_token_uri(621 &mut self,622 caller: Caller,623 to: Address,624 token_uri: String,625 ) -> Result<U256> {626 let token_id: U256 = <TokensMinted<T>>::get(self.id)627 .checked_add(1)628 .ok_or("item id overflow")?629 .into();630 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;631 Ok(token_id)632 }633634 /// @notice Function to mint token with the given tokenUri.635 /// @dev `tokenId` should be obtained with `nextTokenId` method,636 /// unlike standard, you can't specify it manually637 /// @param to The new owner638 /// @param tokenId ID of the minted NFT639 /// @param tokenUri Token URI that would be stored in the NFT properties640 #[solidity(hide, rename_selector = "mintWithTokenURI")]641 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]642 fn mint_with_token_uri_check_id(643 &mut self,644 caller: Caller,645 to: Address,646 token_id: U256,647 token_uri: String,648 ) -> Result<bool> {649 let key = key::url();650 let permission = get_token_permission::<T>(self.id, &key)?;651 if !permission.collection_admin {652 return Err("Operation is not allowed".into());653 }654655 let caller = T::CrossAccountId::from_eth(caller);656 let to = T::CrossAccountId::from_eth(to);657 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;658 let budget = self659 .recorder660 .weight_calls_budget(<StructureWeight<T>>::find_parent());661662 if <TokensMinted<T>>::get(self.id)663 .checked_add(1)664 .ok_or("item id overflow")?665 != token_id666 {667 return Err("item id should be next".into());668 }669670 let mut properties = CollectionPropertiesVec::default();671 properties672 .try_push(Property {673 key,674 value: token_uri675 .into_bytes()676 .try_into()677 .map_err(|_| "token uri is too long")?,678 })679 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;680681 <Pallet<T>>::create_item(682 self,683 &caller,684 CreateItemData::<T> {685 properties,686 owner: to,687 },688 &budget,689 )690 .map_err(dispatch_to_evm::<T>)?;691 Ok(true)692 }693}694695fn get_token_property<T: Config>(696 collection: &CollectionHandle<T>,697 token_id: u32,698 key: &up_data_structs::PropertyKey,699) -> Result<String> {700 collection.consume_store_reads(1)?;701 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))702 .map_err(|_| Error::Revert("Token properties not found".into()))?;703 if let Some(property) = properties.get(key) {704 return Ok(String::from_utf8_lossy(property).into());705 }706707 Err("Property tokenURI not found".into())708}709710fn get_token_permission<T: Config>(711 collection_id: CollectionId,712 key: &PropertyKey,713) -> Result<PropertyPermission> {714 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)715 .map_err(|_| Error::Revert("No permissions for collection".into()))?;716 let a = token_property_permissions717 .get(key)718 .map(Clone::clone)719 .ok_or_else(|| {720 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();721 Error::Revert(alloc::format!("No permission for key {key}"))722 })?;723 Ok(a)724}725726/// @title Unique extensions for ERC721.727#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]728impl<T: Config> NonfungibleHandle<T>729where730 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,731{732 /// @notice A descriptive name for a collection of NFTs in this contract733 fn name(&self) -> String {734 decode_utf16(self.name.iter().copied())735 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))736 .collect::<String>()737 }738739 /// @notice An abbreviated name for NFTs in this contract740 fn symbol(&self) -> String {741 String::from_utf8_lossy(&self.token_prefix).into()742 }743744 /// @notice A description for the collection.745 fn description(&self) -> String {746 decode_utf16(self.description.iter().copied())747 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))748 .collect::<String>()749 }750751 /// Returns the owner (in cross format) of the token.752 ///753 /// @param tokenId Id for the token.754 #[solidity(hide)]755 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {756 Self::owner_of_cross(self, token_id)757 }758759 /// Returns the owner (in cross format) of the token.760 ///761 /// @param tokenId Id for the token.762 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {763 Self::token_owner(self, token_id.try_into()?)764 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))765 .map_err(|_| Error::Revert("token not found".into()))766 }767768 /// @notice Count all NFTs assigned to an owner769 /// @param owner An cross address for whom to query the balance770 /// @return The number of NFTs owned by `owner`, possibly zero771 fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {772 self.consume_store_reads(1)?;773 let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));774 Ok(balance.into())775 }776777 /// Returns the token properties.778 ///779 /// @param tokenId Id for the token.780 /// @param keys Properties keys. Empty keys for all propertyes.781 /// @return Vector of properties key/value pairs.782 fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {783 let keys = keys784 .into_iter()785 .map(|key| {786 <Vec<u8>>::from(key)787 .try_into()788 .map_err(|_| Error::Revert("key too large".into()))789 })790 .collect::<Result<Vec<_>>>()?;791792 <Self as CommonCollectionOperations<T>>::token_properties(793 self,794 token_id.try_into()?,795 if keys.is_empty() { None } else { Some(keys) },796 )797 .into_iter()798 .map(eth::Property::try_from)799 .collect::<Result<Vec<_>>>()800 }801802 /// @notice Set or reaffirm the approved address for an NFT803 /// @dev The zero address indicates there is no approved address.804 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized805 /// operator of the current owner.806 /// @param approved The new substrate address approved NFT controller807 /// @param tokenId The NFT to approve808 #[weight(<SelfWeightOf<T>>::approve())]809 fn approve_cross(810 &mut self,811 caller: Caller,812 approved: eth::CrossAddress,813 token_id: U256,814 ) -> Result<()> {815 let caller = T::CrossAccountId::from_eth(caller);816 let approved = approved.into_sub_cross_account::<T>()?;817 let token = token_id.try_into()?;818819 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))820 .map_err(dispatch_to_evm::<T>)?;821 Ok(())822 }823824 /// @notice Transfer ownership of an NFT825 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`826 /// is the zero address. Throws if `tokenId` is not a valid NFT.827 /// @param to The new owner828 /// @param tokenId The NFT to transfer829 #[weight(<CommonWeights<T>>::transfer())]830 fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {831 let caller = T::CrossAccountId::from_eth(caller);832 let to = T::CrossAccountId::from_eth(to);833 let token = token_id.try_into()?;834 let budget = self835 .recorder836 .weight_calls_budget(<StructureWeight<T>>::find_parent());837838 <Pallet<T>>::transfer(self, &caller, &to, token, &budget)839 .map_err(|e| dispatch_to_evm::<T>(e.error))?;840 Ok(())841 }842843 /// @notice Transfer ownership of an NFT844 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`845 /// is the zero address. Throws if `tokenId` is not a valid NFT.846 /// @param to The new owner847 /// @param tokenId The NFT to transfer848 #[weight(<CommonWeights<T>>::transfer())]849 fn transfer_cross(850 &mut self,851 caller: Caller,852 to: eth::CrossAddress,853 token_id: U256,854 ) -> Result<()> {855 let caller = T::CrossAccountId::from_eth(caller);856 let to = to.into_sub_cross_account::<T>()?;857 let token = token_id.try_into()?;858 let budget = self859 .recorder860 .weight_calls_budget(<StructureWeight<T>>::find_parent());861862 <Pallet<T>>::transfer(self, &caller, &to, token, &budget)863 .map_err(|e| dispatch_to_evm::<T>(e.error))?;864 Ok(())865 }866867 /// @notice Transfer ownership of an NFT from cross account address to cross account address868 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`869 /// is the zero address. Throws if `tokenId` is not a valid NFT.870 /// @param from Cross acccount address of current owner871 /// @param to Cross acccount address of new owner872 /// @param tokenId The NFT to transfer873 #[weight(<CommonWeights<T>>::transfer_from())]874 fn transfer_from_cross(875 &mut self,876 caller: Caller,877 from: eth::CrossAddress,878 to: eth::CrossAddress,879 token_id: U256,880 ) -> Result<()> {881 let caller = T::CrossAccountId::from_eth(caller);882 let from = from.into_sub_cross_account::<T>()?;883 let to = to.into_sub_cross_account::<T>()?;884 let token_id = token_id.try_into()?;885 let budget = self886 .recorder887 .weight_calls_budget(<StructureWeight<T>>::find_parent());888 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)889 .map_err(|e| dispatch_to_evm::<T>(e.error))?;890 Ok(())891 }892893 /// @notice Burns a specific ERC721 token.894 /// @dev Throws unless `msg.sender` is the current owner or an authorized895 /// operator for this NFT. Throws if `from` is not the current owner. Throws896 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.897 /// @param from The current owner of the NFT898 /// @param tokenId The NFT to transfer899 #[solidity(hide)]900 #[weight(<SelfWeightOf<T>>::burn_from())]901 fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {902 let caller = T::CrossAccountId::from_eth(caller);903 let from = T::CrossAccountId::from_eth(from);904 let token = token_id.try_into()?;905 let budget = self906 .recorder907 .weight_calls_budget(<StructureWeight<T>>::find_parent());908909 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)910 .map_err(dispatch_to_evm::<T>)?;911 Ok(())912 }913914 /// @notice Burns a specific ERC721 token.915 /// @dev Throws unless `msg.sender` is the current owner or an authorized916 /// operator for this NFT. Throws if `from` is not the current owner. Throws917 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.918 /// @param from The current owner of the NFT919 /// @param tokenId The NFT to transfer920 #[weight(<SelfWeightOf<T>>::burn_from())]921 fn burn_from_cross(922 &mut self,923 caller: Caller,924 from: eth::CrossAddress,925 token_id: U256,926 ) -> Result<()> {927 let caller = T::CrossAccountId::from_eth(caller);928 let from = from.into_sub_cross_account::<T>()?;929 let token = token_id.try_into()?;930 let budget = self931 .recorder932 .weight_calls_budget(<StructureWeight<T>>::find_parent());933934 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)935 .map_err(dispatch_to_evm::<T>)?;936 Ok(())937 }938939 /// @notice Returns next free NFT ID.940 fn next_token_id(&self) -> Result<U256> {941 self.consume_store_reads(1)?;942 Ok(<Pallet<T>>::next_token_id(self)943 .map_err(dispatch_to_evm::<T>)?944 .into())945 }946947 /// @notice Function to mint multiple tokens.948 /// @dev `tokenIds` should be an array of consecutive numbers and first number949 /// should be obtained with `nextTokenId` method950 /// @param to The new owner951 /// @param tokenIds IDs of the minted NFTs952 #[solidity(hide)]953 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]954 fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {955 let caller = T::CrossAccountId::from_eth(caller);956 let to = T::CrossAccountId::from_eth(to);957 let mut expected_index = <TokensMinted<T>>::get(self.id)958 .checked_add(1)959 .ok_or("item id overflow")?;960 let budget = self961 .recorder962 .weight_calls_budget(<StructureWeight<T>>::find_parent());963964 let total_tokens = token_ids.len();965 for id in token_ids.into_iter() {966 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;967 if id != expected_index {968 return Err("item id should be next".into());969 }970 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;971 }972 let data = (0..total_tokens)973 .map(|_| CreateItemData::<T> {974 properties: BoundedVec::default(),975 owner: to.clone(),976 })977 .collect();978979 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)980 .map_err(dispatch_to_evm::<T>)?;981 Ok(true)982 }983984 /// @notice Function to mint multiple tokens with the given tokenUris.985 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive986 /// numbers and first number should be obtained with `nextTokenId` method987 /// @param to The new owner988 /// @param tokens array of pairs of token ID and token URI for minted tokens989 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]990 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]991 fn mint_bulk_with_token_uri(992 &mut self,993 caller: Caller,994 to: Address,995 tokens: Vec<TokenUri>,996 ) -> Result<bool> {997 let key = key::url();998 let caller = T::CrossAccountId::from_eth(caller);999 let to = T::CrossAccountId::from_eth(to);1000 let mut expected_index = <TokensMinted<T>>::get(self.id)1001 .checked_add(1)1002 .ok_or("item id overflow")?;1003 let budget = self1004 .recorder1005 .weight_calls_budget(<StructureWeight<T>>::find_parent());10061007 let mut data = Vec::with_capacity(tokens.len());1008 for TokenUri { id, uri } in tokens {1009 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1010 if id != expected_index {1011 return Err("item id should be next".into());1012 }1013 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10141015 let mut properties = CollectionPropertiesVec::default();1016 properties1017 .try_push(Property {1018 key: key.clone(),1019 value: uri1020 .into_bytes()1021 .try_into()1022 .map_err(|_| "token uri is too long")?,1023 })1024 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;10251026 data.push(CreateItemData::<T> {1027 properties,1028 owner: to.clone(),1029 });1030 }10311032 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1033 .map_err(dispatch_to_evm::<T>)?;1034 Ok(true)1035 }10361037 /// @notice Function to mint a token.1038 /// @param to The new owner crossAccountId1039 /// @param properties Properties of minted token1040 /// @return uint256 The id of the newly minted token1041 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1042 fn mint_cross(1043 &mut self,1044 caller: Caller,1045 to: eth::CrossAddress,1046 properties: Vec<eth::Property>,1047 ) -> Result<U256> {1048 let token_id = <TokensMinted<T>>::get(self.id)1049 .checked_add(1)1050 .ok_or("item id overflow")?;10511052 let to = to.into_sub_cross_account::<T>()?;10531054 let properties = properties1055 .into_iter()1056 .map(eth::Property::try_into)1057 .collect::<Result<Vec<_>>>()?1058 .try_into()1059 .map_err(|_| Error::Revert("too many properties".to_string()))?;10601061 let caller = T::CrossAccountId::from_eth(caller);10621063 let budget = self1064 .recorder1065 .weight_calls_budget(<StructureWeight<T>>::find_parent());10661067 <Pallet<T>>::create_item(1068 self,1069 &caller,1070 CreateItemData::<T> {1071 properties,1072 owner: to,1073 },1074 &budget,1075 )1076 .map_err(dispatch_to_evm::<T>)?;10771078 Ok(token_id.into())1079 }10801081 /// @notice Returns collection helper contract address1082 fn collection_helper_address(&self) -> Address {1083 T::ContractAddress::get()1084 }1085}10861087#[solidity_interface(1088 name = UniqueNFT,1089 is(1090 ERC721,1091 ERC721Enumerable,1092 ERC721UniqueExtensions,1093 ERC721UniqueMintable,1094 ERC721Burnable,1095 ERC721Metadata(if(this.flags.erc721metadata)),1096 Collection(via(common_mut returns CollectionHandle<T>)),1097 TokenProperties,1098 ),1099 enum(derive(PreDispatch)),1100)]1101impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}11021103// Not a tests, but code generators1104generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);1105generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);11061107impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>1108where1109 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1110{1111 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");11121113 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {1114 call::<T, UniqueNFTCall<T>, _, _>(handle, self)1115 }1116}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.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -196,7 +196,7 @@
&caller,
TokenId(token_id),
properties.into_iter(),
- false,
+ pallet_common::SetPropertyMode::ExistingToken,
&nesting_budget,
)
.map_err(dispatch_to_evm::<T>)
@@ -973,9 +973,8 @@
/// @notice Returns next free RFT 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/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})),