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.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//! The module contains a number of functions for converting and checking ethereum identifiers.1819use alloc::format;20use sp_std::{vec, vec::Vec};21use evm_coder::{22 AbiCoder,23 types::{Address, String},24};25pub use pallet_evm::{Config, account::CrossAccountId};26use sp_core::{H160, U256};27use up_data_structs::CollectionId;2829// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 130// TODO: Unhardcode prefix31const ETH_COLLECTION_PREFIX: [u8; 16] = [32 0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,33];3435/// Maps the ethereum address of the collection in substrate.36pub fn map_eth_to_id(eth: &Address) -> Option<CollectionId> {37 if eth[0..16] != ETH_COLLECTION_PREFIX {38 return None;39 }40 let mut id_bytes = [0; 4];41 id_bytes.copy_from_slice(ð[16..20]);42 Some(CollectionId(u32::from_be_bytes(id_bytes)))43}4445/// Maps the substrate collection id in ethereum.46pub fn collection_id_to_address(id: CollectionId) -> Address {47 let mut out = [0; 20];48 out[0..16].copy_from_slice(Ð_COLLECTION_PREFIX);49 out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));50 H160(out)51}5253/// Check if the ethereum address is a collection.54pub fn is_collection(address: &Address) -> bool {55 address[0..16] == ETH_COLLECTION_PREFIX56}5758/// Convert `U256` to `CrossAccountId`.59pub fn convert_uint256_to_cross_account<T: Config>(from: U256) -> T::CrossAccountId60where61 T::AccountId: From<[u8; 32]>,62{63 let mut new_admin_arr = [0_u8; 32];64 from.to_big_endian(&mut new_admin_arr);65 let account_id = T::AccountId::from(new_admin_arr);66 T::CrossAccountId::from_sub(account_id)67}6869/// Cross account struct70#[derive(Debug, Default, AbiCoder)]71pub struct CrossAddress {72 pub(crate) eth: Address,73 pub(crate) sub: U256,74}7576impl CrossAddress {77 /// Converts `CrossAccountId` to [`CrossAddress`] to be correctly usable with Ethereum.78 pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self79 where80 T: pallet_evm::Config,81 T::AccountId: AsRef<[u8; 32]>,82 {83 if cross_account_id.is_canonical_substrate() {84 Self::from_sub::<T>(cross_account_id.as_sub())85 } else {86 Self::from_eth(*cross_account_id.as_eth())87 }88 }89 /// Creates [`CrossAddress`] from Substrate account.90 pub fn from_sub<T>(account_id: &T::AccountId) -> Self91 where92 T: pallet_evm::Config,93 T::AccountId: AsRef<[u8; 32]>,94 {95 Self {96 eth: Default::default(),97 sub: U256::from_big_endian(account_id.as_ref()),98 }99 }100 /// Creates [`CrossAddress`] from Ethereum account.101 pub fn from_eth(address: Address) -> Self {102 Self {103 eth: address,104 sub: Default::default(),105 }106 }107 /// Converts [`CrossAddress`] to `CrossAccountId`.108 pub fn into_sub_cross_account<T>(109 &self,110 ) -> pallet_evm_coder_substrate::execution::Result<T::CrossAccountId>111 where112 T: pallet_evm::Config,113 T::AccountId: From<[u8; 32]>,114 {115 if self.eth == Default::default() && self.sub == Default::default() {116 Err("All fields of cross account is zeroed".into())117 } else if self.eth == Default::default() {118 Ok(convert_uint256_to_cross_account::<T>(self.sub))119 } else if self.sub == Default::default() {120 Ok(T::CrossAccountId::from_eth(self.eth))121 } else {122 Err("All fields of cross account is non zeroed".into())123 }124 }125}126127/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).128#[derive(Debug, Default, AbiCoder)]129pub struct Property {130 key: evm_coder::types::String,131 value: evm_coder::types::Bytes,132}133134impl TryFrom<up_data_structs::Property> for Property {135 type Error = pallet_evm_coder_substrate::execution::Error;136137 fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {138 let key = evm_coder::types::String::from_utf8(from.key.into())139 .map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {e}")))?;140 let value = evm_coder::types::Bytes(from.value.to_vec());141 Ok(Property { key, value })142 }143}144145impl TryInto<up_data_structs::Property> for Property {146 type Error = pallet_evm_coder_substrate::execution::Error;147148 fn try_into(self) -> Result<up_data_structs::Property, Self::Error> {149 let key = <Vec<u8>>::from(self.key)150 .try_into()151 .map_err(|_| "key too large")?;152153 let value = self.value.0.try_into().map_err(|_| "value too large")?;154155 Ok(up_data_structs::Property { key, value })156 }157}158159/// [`CollectionLimits`](up_data_structs::CollectionLimits) fields representation for EVM.160#[derive(Debug, Default, Clone, Copy, AbiCoder)]161#[repr(u8)]162pub enum CollectionLimitField {163 /// How many tokens can a user have on one account.164 #[default]165 AccountTokenOwnership,166167 /// How many bytes of data are available for sponsorship.168 SponsoredDataSize,169170 /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]171 SponsoredDataRateLimit,172173 /// How many tokens can be mined into this collection.174 TokenLimit,175176 /// Timeouts for transfer sponsoring.177 SponsorTransferTimeout,178179 /// Timeout for sponsoring an approval in passed blocks.180 SponsorApproveTimeout,181182 /// Whether the collection owner of the collection can send tokens (which belong to other users).183 OwnerCanTransfer,184185 /// Can the collection owner burn other people's tokens.186 OwnerCanDestroy,187188 /// Is it possible to send tokens from this collection between users.189 TransferEnabled,190}191192/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.193#[derive(Debug, Default, AbiCoder)]194pub struct CollectionLimit {195 field: CollectionLimitField,196 value: Option<U256>,197}198199impl CollectionLimit {200 /// Create [`CollectionLimit`] from field and value.201 pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {202 Self {203 field,204 value: value.map(|value| value.into()),205 }206 }207 /// Whether the field contains a value.208 pub fn has_value(&self) -> bool {209 self.value.is_some()210 }211}212213impl TryInto<up_data_structs::CollectionLimits> for CollectionLimit {214 type Error = pallet_evm_coder_substrate::execution::Error;215216 fn try_into(self) -> Result<up_data_structs::CollectionLimits, Self::Error> {217 let value = self218 .value219 .ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;220 let value = Some(value.try_into().map_err(|error| {221 Self::Error::Revert(format!(222 "can't convert value to u32 \"{value}\" because: \"{error}\""223 ))224 })?);225226 let convert_value_to_bool = || match value {227 Some(value) => match value {228 0 => Ok(Some(false)),229 1 => Ok(Some(true)),230 _ => {231 return Err(Self::Error::Revert(format!(232 "can't convert value to boolean \"{value}\""233 )))234 }235 },236 None => Ok(None),237 };238239 let mut limits = up_data_structs::CollectionLimits::default();240 match self.field {241 CollectionLimitField::AccountTokenOwnership => {242 limits.account_token_ownership_limit = value;243 }244 CollectionLimitField::SponsoredDataSize => {245 limits.sponsored_data_size = value;246 }247 CollectionLimitField::SponsoredDataRateLimit => {248 limits.sponsored_data_rate_limit =249 value.map(up_data_structs::SponsoringRateLimit::Blocks);250 }251 CollectionLimitField::TokenLimit => {252 limits.token_limit = value;253 }254 CollectionLimitField::SponsorTransferTimeout => {255 limits.sponsor_transfer_timeout = value;256 }257 CollectionLimitField::SponsorApproveTimeout => {258 limits.sponsor_approve_timeout = value;259 }260 CollectionLimitField::OwnerCanTransfer => {261 limits.owner_can_transfer = convert_value_to_bool()?;262 }263 CollectionLimitField::OwnerCanDestroy => {264 limits.owner_can_destroy = convert_value_to_bool()?;265 }266 CollectionLimitField::TransferEnabled => {267 limits.transfers_enabled = convert_value_to_bool()?;268 }269 };270 Ok(limits)271 }272}273274/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) fields as an enumeration.275#[derive(Default, Debug, Clone, Copy, AbiCoder)]276#[repr(u8)]277pub enum CollectionPermissionField {278 /// Owner of token can nest tokens under it.279 #[default]280 TokenOwner,281282 /// Admin of token collection can nest tokens under token.283 CollectionAdmin,284}285286/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.287#[derive(AbiCoder, Copy, Clone, Default, Debug)]288#[repr(u8)]289pub enum TokenPermissionField {290 /// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]291 #[default]292 Mutable,293294 /// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]295 TokenOwner,296297 /// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]298 CollectionAdmin,299}300301/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) as an key and value.302#[derive(Debug, Default, AbiCoder)]303pub struct PropertyPermission {304 /// TokenPermission field.305 code: TokenPermissionField,306 /// TokenPermission value.307 value: bool,308}309310impl PropertyPermission {311 /// Make vector of [`PropertyPermission`] from [`up_data_structs::PropertyPermission`].312 pub fn into_vec(pp: up_data_structs::PropertyPermission) -> Vec<Self> {313 vec![314 PropertyPermission {315 code: TokenPermissionField::Mutable,316 value: pp.mutable,317 },318 PropertyPermission {319 code: TokenPermissionField::TokenOwner,320 value: pp.token_owner,321 },322 PropertyPermission {323 code: TokenPermissionField::CollectionAdmin,324 value: pp.collection_admin,325 },326 ]327 }328329 /// Make [`up_data_structs::PropertyPermission`] from vector of [`PropertyPermission`].330 pub fn from_vec(permission: Vec<Self>) -> up_data_structs::PropertyPermission {331 let mut token_permission = up_data_structs::PropertyPermission::default();332333 for PropertyPermission { code, value } in permission {334 match code {335 TokenPermissionField::Mutable => token_permission.mutable = value,336 TokenPermissionField::TokenOwner => token_permission.token_owner = value,337 TokenPermissionField::CollectionAdmin => token_permission.collection_admin = value,338 }339 }340 token_permission341 }342}343344/// Ethereum representation of Token Property Permissions.345#[derive(Debug, Default, AbiCoder)]346pub struct TokenPropertyPermission {347 /// Token property key.348 key: evm_coder::types::String,349 /// Token property permissions.350 permissions: Vec<PropertyPermission>,351}352353impl354 From<(355 up_data_structs::PropertyKey,356 up_data_structs::PropertyPermission,357 )> for TokenPropertyPermission358{359 fn from(360 value: (361 up_data_structs::PropertyKey,362 up_data_structs::PropertyPermission,363 ),364 ) -> Self {365 let (key, permission) = value;366 let key = evm_coder::types::String::from_utf8(key.into_inner())367 .expect("Stored key must be valid");368 let permissions = PropertyPermission::into_vec(permission);369 Self { key, permissions }370 }371}372373impl TokenPropertyPermission {374 /// Convert vector of [`TokenPropertyPermission`] into vector of [`up_data_structs::PropertyKeyPermission`].375 pub fn into_property_key_permissions(376 permissions: Vec<TokenPropertyPermission>,377 ) -> pallet_evm_coder_substrate::execution::Result<Vec<up_data_structs::PropertyKeyPermission>>378 {379 let mut perms = Vec::new();380381 for TokenPropertyPermission { key, permissions } in permissions {382 let token_permission = PropertyPermission::from_vec(permissions);383384 perms.push(up_data_structs::PropertyKeyPermission {385 key: key.into_bytes().try_into().map_err(|_| "too long key")?,386 permission: token_permission,387 });388 }389 Ok(perms)390 }391}392393/// Data for creation token with uri.394#[derive(Debug, AbiCoder)]395pub struct TokenUri {396 /// Id of new token.397 pub id: U256,398399 /// Uri of new token.400 pub uri: String,401}402403/// Nested collections.404#[derive(Debug, Default, AbiCoder)]405pub struct CollectionNesting {406 token_owner: bool,407 ids: Vec<U256>,408}409410impl CollectionNesting {411 /// Create [`CollectionNesting`].412 pub fn new(token_owner: bool, ids: Vec<U256>) -> Self {413 Self { token_owner, ids }414 }415}416417/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) field.418#[derive(Debug, Default, AbiCoder)]419pub struct CollectionNestingPermission {420 field: CollectionPermissionField,421 value: bool,422}423424impl CollectionNestingPermission {425 /// Create [`CollectionNestingPermission`].426 pub fn new(field: CollectionPermissionField, value: bool) -> Self {427 Self { field, value }428 }429}430431/// Ethereum representation of `AccessMode` (see [`up_data_structs::AccessMode`]).432#[derive(AbiCoder, Copy, Clone, Default, Debug)]433#[repr(u8)]434pub enum AccessMode {435 /// Access grant for owner and admins. Used as default.436 #[default]437 Normal,438 /// Like a [`Normal`](AccessMode::Normal) but also users in allow list.439 AllowList,440}441442impl From<up_data_structs::AccessMode> for AccessMode {443 fn from(value: up_data_structs::AccessMode) -> Self {444 match value {445 up_data_structs::AccessMode::Normal => AccessMode::Normal,446 up_data_structs::AccessMode::AllowList => AccessMode::AllowList,447 }448 }449}450451impl From<AccessMode> for up_data_structs::AccessMode {452 fn from(value: AccessMode) -> Self {453 match value {454 AccessMode::Normal => up_data_structs::AccessMode::Normal,455 AccessMode::AllowList => up_data_structs::AccessMode::AllowList,456 }457 }458}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//! The module contains a number of functions for converting and checking ethereum identifiers.1819use alloc::format;20use sp_std::{vec, vec::Vec};21use evm_coder::{22 AbiCoder,23 types::{Address, String},24};25pub use pallet_evm::{Config, account::CrossAccountId};26use sp_core::{H160, U256};27use up_data_structs::CollectionId;2829// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 130// TODO: Unhardcode prefix31const ETH_COLLECTION_PREFIX: [u8; 16] = [32 0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,33];3435/// Maps the ethereum address of the collection in substrate.36pub fn map_eth_to_id(eth: &Address) -> Option<CollectionId> {37 if eth[0..16] != ETH_COLLECTION_PREFIX {38 return None;39 }40 let mut id_bytes = [0; 4];41 id_bytes.copy_from_slice(ð[16..20]);42 Some(CollectionId(u32::from_be_bytes(id_bytes)))43}4445/// Maps the substrate collection id in ethereum.46pub fn collection_id_to_address(id: CollectionId) -> Address {47 let mut out = [0; 20];48 out[0..16].copy_from_slice(Ð_COLLECTION_PREFIX);49 out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));50 H160(out)51}5253/// Check if the ethereum address is a collection.54pub fn is_collection(address: &Address) -> bool {55 address[0..16] == ETH_COLLECTION_PREFIX56}5758/// Convert `U256` to `CrossAccountId`.59pub fn convert_uint256_to_cross_account<T: Config>(from: U256) -> T::CrossAccountId60where61 T::AccountId: From<[u8; 32]>,62{63 let mut new_admin_arr = [0_u8; 32];64 from.to_big_endian(&mut new_admin_arr);65 let account_id = T::AccountId::from(new_admin_arr);66 T::CrossAccountId::from_sub(account_id)67}6869/// Cross account struct70#[derive(Debug, Default, AbiCoder)]71pub struct CrossAddress {72 pub(crate) eth: Address,73 pub(crate) sub: U256,74}7576impl CrossAddress {77 /// Converts `CrossAccountId` to [`CrossAddress`] to be correctly usable with Ethereum.78 pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self79 where80 T: pallet_evm::Config,81 T::AccountId: AsRef<[u8; 32]>,82 {83 if cross_account_id.is_canonical_substrate() {84 Self::from_sub::<T>(cross_account_id.as_sub())85 } else {86 Self::from_eth(*cross_account_id.as_eth())87 }88 }89 /// Creates [`CrossAddress`] from Substrate account.90 pub fn from_sub<T>(account_id: &T::AccountId) -> Self91 where92 T: pallet_evm::Config,93 T::AccountId: AsRef<[u8; 32]>,94 {95 Self {96 eth: Default::default(),97 sub: U256::from_big_endian(account_id.as_ref()),98 }99 }100 /// Creates [`CrossAddress`] from Ethereum account.101 pub fn from_eth(address: Address) -> Self {102 Self {103 eth: address,104 sub: Default::default(),105 }106 }107 /// Converts [`CrossAddress`] to `CrossAccountId`.108 pub fn into_sub_cross_account<T>(109 &self,110 ) -> pallet_evm_coder_substrate::execution::Result<T::CrossAccountId>111 where112 T: pallet_evm::Config,113 T::AccountId: From<[u8; 32]>,114 {115 if self.eth == Default::default() && self.sub == Default::default() {116 Err("All fields of cross account is zeroed".into())117 } else if self.eth == Default::default() {118 Ok(convert_uint256_to_cross_account::<T>(self.sub))119 } else if self.sub == Default::default() {120 Ok(T::CrossAccountId::from_eth(self.eth))121 } else {122 Err("All fields of cross account is non zeroed".into())123 }124 }125}126127/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).128#[derive(Debug, Default, AbiCoder)]129pub struct Property {130 key: evm_coder::types::String,131 value: evm_coder::types::Bytes,132}133134impl Property {135 /// Property key.136 pub fn key(&self) -> &str {137 self.key.as_str()138 }139140 /// Property value.141 pub fn value(&self) -> &[u8] {142 self.value.0.as_slice()143 }144}145146impl TryFrom<up_data_structs::Property> for Property {147 type Error = pallet_evm_coder_substrate::execution::Error;148149 fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {150 let key = evm_coder::types::String::from_utf8(from.key.into())151 .map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {e}")))?;152 let value = evm_coder::types::Bytes(from.value.to_vec());153 Ok(Property { key, value })154 }155}156157impl TryInto<up_data_structs::Property> for Property {158 type Error = pallet_evm_coder_substrate::execution::Error;159160 fn try_into(self) -> Result<up_data_structs::Property, Self::Error> {161 let key = <Vec<u8>>::from(self.key)162 .try_into()163 .map_err(|_| "key too large")?;164165 let value = self.value.0.try_into().map_err(|_| "value too large")?;166167 Ok(up_data_structs::Property { key, value })168 }169}170171/// [`CollectionLimits`](up_data_structs::CollectionLimits) fields representation for EVM.172#[derive(Debug, Default, Clone, Copy, AbiCoder)]173#[repr(u8)]174pub enum CollectionLimitField {175 /// How many tokens can a user have on one account.176 #[default]177 AccountTokenOwnership,178179 /// How many bytes of data are available for sponsorship.180 SponsoredDataSize,181182 /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]183 SponsoredDataRateLimit,184185 /// How many tokens can be mined into this collection.186 TokenLimit,187188 /// Timeouts for transfer sponsoring.189 SponsorTransferTimeout,190191 /// Timeout for sponsoring an approval in passed blocks.192 SponsorApproveTimeout,193194 /// Whether the collection owner of the collection can send tokens (which belong to other users).195 OwnerCanTransfer,196197 /// Can the collection owner burn other people's tokens.198 OwnerCanDestroy,199200 /// Is it possible to send tokens from this collection between users.201 TransferEnabled,202}203204/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.205#[derive(Debug, Default, AbiCoder)]206pub struct CollectionLimit {207 field: CollectionLimitField,208 value: Option<U256>,209}210211impl CollectionLimit {212 /// Create [`CollectionLimit`] from field and value.213 pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {214 Self {215 field,216 value: value.map(|value| value.into()),217 }218 }219 /// Whether the field contains a value.220 pub fn has_value(&self) -> bool {221 self.value.is_some()222 }223}224225impl TryInto<up_data_structs::CollectionLimits> for CollectionLimit {226 type Error = pallet_evm_coder_substrate::execution::Error;227228 fn try_into(self) -> Result<up_data_structs::CollectionLimits, Self::Error> {229 let value = self230 .value231 .ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;232 let value = Some(value.try_into().map_err(|error| {233 Self::Error::Revert(format!(234 "can't convert value to u32 \"{value}\" because: \"{error}\""235 ))236 })?);237238 let convert_value_to_bool = || match value {239 Some(value) => match value {240 0 => Ok(Some(false)),241 1 => Ok(Some(true)),242 _ => Err(Self::Error::Revert(format!(243 "can't convert value to boolean \"{value}\""244 ))),245 },246 None => Ok(None),247 };248249 let mut limits = up_data_structs::CollectionLimits::default();250 match self.field {251 CollectionLimitField::AccountTokenOwnership => {252 limits.account_token_ownership_limit = value;253 }254 CollectionLimitField::SponsoredDataSize => {255 limits.sponsored_data_size = value;256 }257 CollectionLimitField::SponsoredDataRateLimit => {258 limits.sponsored_data_rate_limit =259 value.map(up_data_structs::SponsoringRateLimit::Blocks);260 }261 CollectionLimitField::TokenLimit => {262 limits.token_limit = value;263 }264 CollectionLimitField::SponsorTransferTimeout => {265 limits.sponsor_transfer_timeout = value;266 }267 CollectionLimitField::SponsorApproveTimeout => {268 limits.sponsor_approve_timeout = value;269 }270 CollectionLimitField::OwnerCanTransfer => {271 limits.owner_can_transfer = convert_value_to_bool()?;272 }273 CollectionLimitField::OwnerCanDestroy => {274 limits.owner_can_destroy = convert_value_to_bool()?;275 }276 CollectionLimitField::TransferEnabled => {277 limits.transfers_enabled = convert_value_to_bool()?;278 }279 };280 Ok(limits)281 }282}283284/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) fields as an enumeration.285#[derive(Default, Debug, Clone, Copy, AbiCoder)]286#[repr(u8)]287pub enum CollectionPermissionField {288 /// Owner of token can nest tokens under it.289 #[default]290 TokenOwner,291292 /// Admin of token collection can nest tokens under token.293 CollectionAdmin,294}295296/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) fields as an enumeration.297#[derive(AbiCoder, Copy, Clone, Default, Debug)]298#[repr(u8)]299pub enum TokenPermissionField {300 /// Permission to change the property and property permission. See [`up_data_structs::PropertyPermission::mutable`]301 #[default]302 Mutable,303304 /// Change permission for the collection administrator. See [`up_data_structs::PropertyPermission::token_owner`]305 TokenOwner,306307 /// Permission to change the property for the owner of the token. See [`up_data_structs::PropertyPermission::collection_admin`]308 CollectionAdmin,309}310311/// Ethereum representation of TokenPermissions (see [`up_data_structs::PropertyPermission`]) as an key and value.312#[derive(Debug, Default, AbiCoder)]313pub struct PropertyPermission {314 /// TokenPermission field.315 code: TokenPermissionField,316 /// TokenPermission value.317 value: bool,318}319320impl PropertyPermission {321 /// Make vector of [`PropertyPermission`] from [`up_data_structs::PropertyPermission`].322 pub fn into_vec(pp: up_data_structs::PropertyPermission) -> Vec<Self> {323 vec![324 PropertyPermission {325 code: TokenPermissionField::Mutable,326 value: pp.mutable,327 },328 PropertyPermission {329 code: TokenPermissionField::TokenOwner,330 value: pp.token_owner,331 },332 PropertyPermission {333 code: TokenPermissionField::CollectionAdmin,334 value: pp.collection_admin,335 },336 ]337 }338339 /// Make [`up_data_structs::PropertyPermission`] from vector of [`PropertyPermission`].340 pub fn from_vec(permission: Vec<Self>) -> up_data_structs::PropertyPermission {341 let mut token_permission = up_data_structs::PropertyPermission::default();342343 for PropertyPermission { code, value } in permission {344 match code {345 TokenPermissionField::Mutable => token_permission.mutable = value,346 TokenPermissionField::TokenOwner => token_permission.token_owner = value,347 TokenPermissionField::CollectionAdmin => token_permission.collection_admin = value,348 }349 }350 token_permission351 }352}353354/// Ethereum representation of Token Property Permissions.355#[derive(Debug, Default, AbiCoder)]356pub struct TokenPropertyPermission {357 /// Token property key.358 key: evm_coder::types::String,359 /// Token property permissions.360 permissions: Vec<PropertyPermission>,361}362363impl364 From<(365 up_data_structs::PropertyKey,366 up_data_structs::PropertyPermission,367 )> for TokenPropertyPermission368{369 fn from(370 value: (371 up_data_structs::PropertyKey,372 up_data_structs::PropertyPermission,373 ),374 ) -> Self {375 let (key, permission) = value;376 let key = evm_coder::types::String::from_utf8(key.into_inner())377 .expect("Stored key must be valid");378 let permissions = PropertyPermission::into_vec(permission);379 Self { key, permissions }380 }381}382383impl TokenPropertyPermission {384 /// Convert vector of [`TokenPropertyPermission`] into vector of [`up_data_structs::PropertyKeyPermission`].385 pub fn into_property_key_permissions(386 permissions: Vec<TokenPropertyPermission>,387 ) -> pallet_evm_coder_substrate::execution::Result<Vec<up_data_structs::PropertyKeyPermission>>388 {389 let mut perms = Vec::new();390391 for TokenPropertyPermission { key, permissions } in permissions {392 let token_permission = PropertyPermission::from_vec(permissions);393394 perms.push(up_data_structs::PropertyKeyPermission {395 key: key.into_bytes().try_into().map_err(|_| "too long key")?,396 permission: token_permission,397 });398 }399 Ok(perms)400 }401}402403/// Data for creation token with uri.404#[derive(Debug, AbiCoder)]405pub struct TokenUri {406 /// Id of new token.407 pub id: U256,408409 /// Uri of new token.410 pub uri: String,411}412413/// Nested collections.414#[derive(Debug, Default, AbiCoder)]415pub struct CollectionNesting {416 token_owner: bool,417 ids: Vec<U256>,418}419420impl CollectionNesting {421 /// Create [`CollectionNesting`].422 pub fn new(token_owner: bool, ids: Vec<U256>) -> Self {423 Self { token_owner, ids }424 }425}426427/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) field.428#[derive(Debug, Default, AbiCoder)]429pub struct CollectionNestingPermission {430 field: CollectionPermissionField,431 value: bool,432}433434impl CollectionNestingPermission {435 /// Create [`CollectionNestingPermission`].436 pub fn new(field: CollectionPermissionField, value: bool) -> Self {437 Self { field, value }438 }439}440441/// Ethereum representation of `AccessMode` (see [`up_data_structs::AccessMode`]).442#[derive(AbiCoder, Copy, Clone, Default, Debug)]443#[repr(u8)]444pub enum AccessMode {445 /// Access grant for owner and admins. Used as default.446 #[default]447 Normal,448 /// Like a [`Normal`](AccessMode::Normal) but also users in allow list.449 AllowList,450}451452impl From<up_data_structs::AccessMode> for AccessMode {453 fn from(value: up_data_structs::AccessMode) -> Self {454 match value {455 up_data_structs::AccessMode::Normal => AccessMode::Normal,456 up_data_structs::AccessMode::AllowList => AccessMode::AllowList,457 }458 }459}460461impl From<AccessMode> for up_data_structs::AccessMode {462 fn from(value: AccessMode) -> Self {463 match value {464 AccessMode::Normal => up_data_structs::AccessMode::Normal,465 AccessMode::AllowList => up_data_structs::AccessMode::AllowList,466 }467 }468}pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -216,7 +216,6 @@
///
/// # Arguments
///
- /// * `sender`: Caller's account.
/// * `sponsor`: ID of the account of the sponsor-to-be.
pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {
self.check_is_internal()?;
@@ -867,6 +866,74 @@
>;
}
+/// Represents the change mode for the token property.
+pub enum SetPropertyMode {
+ /// The token already exists.
+ ExistingToken,
+
+ /// New token.
+ NewToken {
+ /// The creator of the token is the recipient.
+ mint_target_is_sender: bool,
+ },
+}
+
+/// Value representation with delayed initialization time.
+pub struct LazyValue<T, F: FnOnce() -> T> {
+ value: Option<T>,
+ f: Option<F>,
+}
+
+impl<T, F: FnOnce() -> T> LazyValue<T, F> {
+ /// Create a new LazyValue.
+ pub fn new(f: F) -> Self {
+ Self {
+ value: None,
+ f: Some(f),
+ }
+ }
+
+ /// Get the value. If it call furst time the value will be initialized.
+ pub fn value(&mut self) -> &T {
+ if self.value.is_none() {
+ self.value = Some(self.f.take().unwrap()())
+ }
+
+ self.value.as_ref().unwrap()
+ }
+
+ /// Is value initialized.
+ pub fn has_value(&self) -> bool {
+ self.value.is_some()
+ }
+}
+
+fn check_token_permissions<T, FCA, FTO, FTE>(
+ collection_admin_permitted: bool,
+ token_owner_permitted: bool,
+ is_collection_admin: &mut LazyValue<bool, FCA>,
+ is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,
+ is_token_exist: &mut LazyValue<bool, FTE>,
+) -> DispatchResult
+where
+ T: Config,
+ FCA: FnOnce() -> bool,
+ FTO: FnOnce() -> Result<bool, DispatchError>,
+ FTE: FnOnce() -> bool,
+{
+ if !(collection_admin_permitted && *is_collection_admin.value()
+ || token_owner_permitted && (*is_token_owner.value())?)
+ {
+ fail!(<Error<T>>::NoPermission);
+ }
+
+ let token_certainly_exist = is_token_owner.has_value() && (*is_token_owner.value())?;
+ if !token_certainly_exist && !is_token_exist.value() {
+ fail!(<Error<T>>::TokenNotFound);
+ }
+ Ok(())
+}
+
impl<T: Config> Pallet<T> {
/// Enshure that receiver address is correct.
///
@@ -1218,10 +1285,6 @@
/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`
/// * removes a property under the <key> if the value is `None` `(<key>, None)`.
///
- /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
- /// - `is_token_create`: Indicates that method is called during token initialization.
- /// Allows to bypass ownership check.
- ///
/// All affected properties should have `mutable` permission
/// to be **deleted** or to be **set more than once**,
/// and the sender should have permission to edit those properties.
@@ -1229,35 +1292,36 @@
/// This function fires an event for each property change.
/// In case of an error, all the changes (including the events) will be reverted
/// since the function is transactional.
- pub fn modify_token_properties(
+ #[allow(clippy::too_many_arguments)]
+ pub fn modify_token_properties<FTO, FTE>(
collection: &CollectionHandle<T>,
sender: &T::CrossAccountId,
token_id: TokenId,
+ is_token_exist: &mut LazyValue<bool, FTE>,
properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
- is_token_create: bool,
mut stored_properties: TokenProperties,
- is_token_owner: impl Fn() -> Result<bool, DispatchError>,
+ is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,
set_token_properties: impl FnOnce(TokenProperties),
log: evm_coder::ethereum::Log,
- ) -> DispatchResult {
- let is_collection_admin = collection.is_owner_or_admin(sender);
+ ) -> DispatchResult
+ where
+ FTO: FnOnce() -> Result<bool, DispatchError>,
+ FTE: FnOnce() -> bool,
+ {
+ let mut is_collection_admin = LazyValue::new(|| collection.is_owner_or_admin(sender));
let permissions = Self::property_permissions(collection.id);
- let mut token_owner_result = None;
- let mut is_token_owner = || -> Result<bool, DispatchError> {
- *token_owner_result.get_or_insert_with(&is_token_owner)
- };
-
+ let mut changed = false;
for (key, value) in properties_updates {
let permission = permissions
.get(&key)
.cloned()
.unwrap_or_else(PropertyPermission::none);
- let is_property_exists = stored_properties.get(&key).is_some();
+ let property_exists = stored_properties.get(&key).is_some();
match permission {
- PropertyPermission { mutable: false, .. } if is_property_exists => {
+ PropertyPermission { mutable: false, .. } if property_exists => {
return Err(<Error<T>>::NoPermission.into());
}
@@ -1265,17 +1329,13 @@
collection_admin,
token_owner,
..
- } => {
- //TODO: investigate threats during public minting.
- let is_token_create =
- is_token_create && (collection_admin || token_owner) && value.is_some();
- if !(is_token_create
- || (collection_admin && is_collection_admin)
- || (token_owner && is_token_owner()?))
- {
- fail!(<Error<T>>::NoPermission);
- }
- }
+ } => check_token_permissions::<T, _, FTO, FTE>(
+ collection_admin,
+ token_owner,
+ &mut is_collection_admin,
+ is_token_owner,
+ is_token_exist,
+ )?,
}
match value {
@@ -1293,9 +1353,13 @@
}
}
- <PalletEvm<T>>::deposit_log(log.clone());
+ changed = true;
}
+ if changed {
+ <PalletEvm<T>>::deposit_log(log);
+ }
+
set_token_properties(stored_properties);
Ok(())
@@ -2322,3 +2386,86 @@
}
}
}
+
+#[cfg(feature = "tests")]
+pub mod tests {
+ use crate::{DispatchResult, DispatchError, LazyValue, Config};
+
+ const fn to_bool(u: u8) -> bool {
+ u != 0
+ }
+
+ #[derive(Debug)]
+ pub struct TestCase {
+ pub collection_admin: bool,
+ pub is_collection_admin: bool,
+ pub token_owner: bool,
+ pub is_token_owner: bool,
+ pub no_permission: bool,
+ }
+
+ impl TestCase {
+ const fn new(
+ collection_admin: u8,
+ is_collection_admin: u8,
+ token_owner: u8,
+ is_token_owner: u8,
+ no_permission: u8,
+ ) -> Self {
+ Self {
+ collection_admin: to_bool(collection_admin),
+ is_collection_admin: to_bool(is_collection_admin),
+ token_owner: to_bool(token_owner),
+ is_token_owner: to_bool(is_token_owner),
+ no_permission: to_bool(no_permission),
+ }
+ }
+ }
+
+ #[rustfmt::skip]
+ pub const table: [TestCase; 16] = [
+ // ┌╴collection_admin
+ // │ ┌╴is_collection_admin
+ // │ │ ┌╴token_owner
+ // │ │ │ ┌╴is_token_ownership
+ // │ │ │ │ ┌╴no_permission
+ /* 0*/ TestCase::new(0, 0, 0, 0, 1),
+ /* 1*/ TestCase::new(0, 0, 0, 1, 1),
+ /* 2*/ TestCase::new(0, 0, 1, 0, 1),
+ /* 3*/ TestCase::new(0, 0, 1, 1, 0),
+ /* 4*/ TestCase::new(0, 1, 0, 0, 1),
+ /* 5*/ TestCase::new(0, 1, 0, 1, 1),
+ /* 6*/ TestCase::new(0, 1, 1, 0, 1),
+ /* 7*/ TestCase::new(0, 1, 1, 1, 0),
+ /* 8*/ TestCase::new(1, 0, 0, 0, 1),
+ /* 9*/ TestCase::new(1, 0, 0, 1, 1),
+ /* 10*/ TestCase::new(1, 0, 1, 0, 1),
+ /* 11*/ TestCase::new(1, 0, 1, 1, 0),
+ /* 12*/ TestCase::new(1, 1, 0, 0, 0),
+ /* 13*/ TestCase::new(1, 1, 0, 1, 0),
+ /* 14*/ TestCase::new(1, 1, 1, 0, 0),
+ /* 15*/ TestCase::new(1, 1, 1, 1, 0),
+ ];
+
+ pub fn check_token_permissions<T, FCA, FTO, FTE>(
+ collection_admin_permitted: bool,
+ token_owner_permitted: bool,
+ is_collection_admin: &mut LazyValue<bool, FCA>,
+ check_token_ownership: &mut LazyValue<Result<bool, DispatchError>, FTO>,
+ check_token_existence: &mut LazyValue<bool, FTE>,
+ ) -> DispatchResult
+ where
+ T: Config,
+ FCA: FnOnce() -> bool,
+ FTO: FnOnce() -> Result<bool, DispatchError>,
+ FTE: FnOnce() -> bool,
+ {
+ crate::check_token_permissions::<T, FCA, FTO, FTE>(
+ collection_admin_permitted,
+ token_owner_permitted,
+ is_collection_admin,
+ check_token_ownership,
+ check_token_existence,
+ )
+ }
+}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -245,7 +245,7 @@
&sender,
token_id,
properties.into_iter(),
- false,
+ pallet_common::SetPropertyMode::ExistingToken,
nesting_budget,
),
weight,
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -194,7 +194,7 @@
&caller,
TokenId(token_id),
properties.into_iter(),
- false,
+ pallet_common::SetPropertyMode::ExistingToken,
&nesting_budget,
)
.map_err(dispatch_to_evm::<T>)
@@ -939,9 +939,8 @@
/// @notice Returns next free NFT ID.
fn next_token_id(&self) -> Result<U256> {
self.consume_store_reads(1)?;
- Ok(<TokensMinted<T>>::get(self.id)
- .checked_add(1)
- .ok_or("item id overflow")?
+ Ok(<Pallet<T>>::next_token_id(self)
+ .map_err(dispatch_to_evm::<T>)?
.into())
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -109,7 +109,7 @@
use pallet_common::{
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,
- weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,
+ weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info, SetPropertyMode,
};
use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
@@ -585,8 +585,6 @@
/// A batch operation to add, edit or remove properties for a token.
///
/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
- /// - `is_token_create`: Indicates that method is called during token initialization.
- /// Allows to bypass ownership check.
///
/// All affected properties should have `mutable` permission
/// to be **deleted** or to be **set more than once**,
@@ -601,10 +599,17 @@
sender: &T::CrossAccountId,
token_id: TokenId,
properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
- is_token_create: bool,
+ mode: SetPropertyMode,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- let is_token_owner = || {
+ let mut is_token_owner = pallet_common::LazyValue::new(|| {
+ if let SetPropertyMode::NewToken {
+ mint_target_is_sender,
+ } = mode
+ {
+ return Ok(mint_target_is_sender);
+ }
+
let is_owned = <PalletStructure<T>>::check_indirectly_owned(
sender.clone(),
collection.id,
@@ -614,18 +619,21 @@
)?;
Ok(is_owned)
- };
+ });
+ let mut is_token_exist =
+ pallet_common::LazyValue::new(|| Self::token_exists(collection, token_id));
+
let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));
<PalletCommon<T>>::modify_token_properties(
collection,
sender,
token_id,
+ &mut is_token_exist,
properties_updates,
- is_token_create,
stored_properties,
- is_token_owner,
+ &mut is_token_owner,
|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),
erc::ERC721TokenEvent::TokenChanged {
token_id: token_id.into(),
@@ -634,6 +642,19 @@
)
}
+ pub fn next_token_id(collection: &NonfungibleHandle<T>) -> Result<TokenId, DispatchError> {
+ let next_token_id = <TokensMinted<T>>::get(collection.id)
+ .checked_add(1)
+ .ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;
+
+ ensure!(
+ collection.limits.token_limit() >= next_token_id,
+ <CommonError<T>>::CollectionTokenLimitExceeded
+ );
+
+ Ok(TokenId(next_token_id))
+ }
+
/// Batch operation to add or edit properties for the token
///
/// Same as [`modify_token_properties`] but doesn't allow to remove properties
@@ -644,7 +665,7 @@
sender: &T::CrossAccountId,
token_id: TokenId,
properties: impl Iterator<Item = Property>,
- is_token_create: bool,
+ mode: SetPropertyMode,
nesting_budget: &dyn Budget,
) -> DispatchResult {
Self::modify_token_properties(
@@ -652,7 +673,7 @@
sender,
token_id,
properties.map(|p| (p.key, Some(p.value))),
- is_token_create,
+ mode,
nesting_budget,
)
}
@@ -669,14 +690,12 @@
property: Property,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- let is_token_create = false;
-
Self::set_token_properties(
collection,
sender,
token_id,
[property].into_iter(),
- is_token_create,
+ SetPropertyMode::ExistingToken,
nesting_budget,
)
}
@@ -693,14 +712,12 @@
property_keys: impl Iterator<Item = PropertyKey>,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- let is_token_create = false;
-
Self::modify_token_properties(
collection,
sender,
token_id,
property_keys.into_iter().map(|key| (key, None)),
- is_token_create,
+ SetPropertyMode::ExistingToken,
nesting_budget,
)
}
@@ -985,7 +1002,9 @@
sender,
TokenId(token),
data.properties.clone().into_iter(),
- true,
+ SetPropertyMode::NewToken {
+ mint_target_is_sender: sender.conv_eq(&data.owner),
+ },
nesting_budget,
) {
return TransactionOutcome::Rollback(Err(e));
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -399,7 +399,7 @@
&sender,
token_id,
properties.into_iter(),
- false,
+ pallet_common::SetPropertyMode::ExistingToken,
nesting_budget,
),
weight,
pallets/refungible/src/erc.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})),