difftreelog
fix EVM mint with properties, minor improvements
in: master
9 files changed
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -29,9 +29,8 @@
use sp_std::{vec, vec::Vec};
use up_data_structs::{
AccessMode, CollectionId, CollectionMode, CollectionPermissions, CreateCollectionData,
- NestingPermissions, PropertiesPermissionMap, Property, PropertyKey, PropertyValue,
- MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_COLLECTION_NAME_LENGTH, MAX_PROPERTIES_PER_ITEM,
- MAX_TOKEN_PREFIX_LENGTH,
+ NestingPermissions, Property, PropertyKey, PropertyValue, MAX_COLLECTION_DESCRIPTION_LENGTH,
+ MAX_COLLECTION_NAME_LENGTH, MAX_PROPERTIES_PER_ITEM, MAX_TOKEN_PREFIX_LENGTH,
};
use crate::{BenchmarkPropertyWriter, CollectionHandle, Config, Pallet};
@@ -190,31 +189,6 @@
#[block]
{
<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;
- }
-
- Ok(())
- }
-
- #[benchmark]
- fn delete_collection_properties(
- b: Linear<0, MAX_PROPERTIES_PER_ITEM>,
- ) -> Result<(), BenchmarkError> {
- bench_init! {
- owner: sub; collection: collection(owner);
- owner: cross_from_sub;
- };
- let props = (0..b)
- .map(|p| Property {
- key: property_key(p as usize),
- value: property_value(),
- })
- .collect::<Vec<_>>();
- <Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;
- let to_delete = (0..b).map(|p| property_key(p as usize)).collect::<Vec<_>>();
-
- #[block]
- {
- <Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete.into_iter())?;
}
Ok(())
@@ -253,7 +227,7 @@
}
#[benchmark]
- fn init_token_properties_common() -> Result<(), BenchmarkError> {
+ fn property_writer_load_collection_info() -> Result<(), BenchmarkError> {
bench_init! {
owner: sub; collection: collection(owner);
sender: sub;
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -126,7 +126,7 @@
///
/// @param key Property key.
#[solidity(hide)]
- #[weight(<SelfWeightOf<T>>::delete_collection_properties(1))]
+ #[weight(<SelfWeightOf<T>>::set_collection_properties(1))]
fn delete_collection_property(&mut self, caller: Caller, key: String) -> Result<()> {
let caller = T::CrossAccountId::from_eth(caller);
let key = <Vec<u8>>::from(key)
@@ -139,7 +139,7 @@
/// Delete collection properties.
///
/// @param keys Properties keys.
- #[weight(<SelfWeightOf<T>>::delete_collection_properties(keys.len() as u32))]
+ #[weight(<SelfWeightOf<T>>::set_collection_properties(keys.len() as u32))]
fn delete_collection_properties(&mut self, caller: Caller, keys: Vec<String>) -> Result<()> {
let caller = T::CrossAccountId::from_eth(caller);
let keys = keys
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -2626,8 +2626,8 @@
impl<T: Config> BenchmarkPropertyWriter<T> {
/// Creates a [`PropertyWriter`] for benchmarking tokens properties writing.
pub fn new<'a, Handle>(
- collection: &Handle,
- collection_lazy_info: PropertyWriterLazyCollectionInfo,
+ collection: &'a Handle,
+ collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,
) -> PropertyWriter<'a, Self, T, Handle>
where
Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -18,7 +18,6 @@
use pallet_common::{
bench_init,
benchmarking::{create_collection_raw, property_key, property_value},
- CommonCollectionOperations,
};
use sp_std::prelude::*;
use up_data_structs::{
@@ -131,53 +130,12 @@
#[block]
{
<Pallet<T>>::burn(&collection, &burner, item)?;
- }
-
- Ok(())
- }
-
- #[benchmark]
- fn burn_recursively_self_raw() -> Result<(), BenchmarkError> {
- bench_init! {
- owner: sub; collection: collection(owner);
- sender: cross_from_sub(owner); burner: cross_sub;
- };
- let item = create_max_item(&collection, &sender, burner.clone())?;
-
- #[block]
- {
- <Pallet<T>>::burn_recursively(&collection, &burner, item, &Unlimited, &Unlimited)?;
}
Ok(())
}
#[benchmark]
- fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(
- b: Linear<0, 200>,
- ) -> Result<(), BenchmarkError> {
- bench_init! {
- owner: sub; collection: collection(owner);
- sender: cross_from_sub(owner); burner: cross_sub;
- };
- let item = create_max_item(&collection, &sender, burner.clone())?;
- for _ in 0..b {
- create_max_item(
- &collection,
- &sender,
- T::CrossTokenAddressMapping::token_to_address(collection.id, item),
- )?;
- }
-
- #[block]
- {
- <Pallet<T>>::burn_recursively(&collection, &burner, item, &Unlimited, &Unlimited)?;
- }
-
- Ok(())
- }
-
- #[benchmark]
fn transfer_raw() -> Result<(), BenchmarkError> {
bench_init! {
owner: sub; collection: collection(owner);
@@ -262,116 +220,34 @@
{
<Pallet<T>>::burn_from(&collection, &burner, &sender, item, &Unlimited)?;
}
- }
- // set_token_properties {
- // let b in 0..MAX_PROPERTIES_PER_ITEM;
- // bench_init!{
- // owner: sub; collection: collection(owner);
- // owner: cross_from_sub;
- // };
- // let perms = (0..b).map(|k| PropertyKeyPermission {
- // key: property_key(k as usize),
- // permission: PropertyPermission {
- // mutable: false,
- // collection_admin: true,
- // token_owner: true,
- // },
- // }).collect::<Vec<_>>();
- // <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
- // let props = (0..b).map(|k| Property {
- // key: property_key(k as usize),
- // value: property_value(),
- // }).collect::<Vec<_>>();
- // let item = create_max_item(&collection, &owner, owner.clone())?;
- // }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), &Unlimited)?}
-
- // load_token_properties {
- // bench_init!{
- // owner: sub; collection: collection(owner);
- // owner: cross_from_sub;
- // };
-
- // let item = create_max_item(&collection, &owner, owner.clone())?;
- // }: {
- // pallet_common::BenchmarkPropertyWriter::<T>::load_token_properties(
- // &collection,
- // item,
- // )
- // }
-
- // write_token_properties {
- // let b in 0..MAX_PROPERTIES_PER_ITEM;
- // bench_init!{
- // owner: sub; collection: collection(owner);
- // owner: cross_from_sub;
- // };
+ Ok(())
+ }
- // let perms = (0..b).map(|k| PropertyKeyPermission {
- // key: property_key(k as usize),
- // permission: PropertyPermission {
- // mutable: false,
- // collection_admin: true,
- // token_owner: true,
- // },
- // }).collect::<Vec<_>>();
- // <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
- // let props = (0..b).map(|k| Property {
- // key: property_key(k as usize),
- // value: property_value(),
- // }).collect::<Vec<_>>();
- // let item = create_max_item(&collection, &owner, owner.clone())?;
-
- // let lazy_collection_info = pallet_common::BenchmarkPropertyWriter::<T>::load_collection_info(
- // &collection,
- // &owner,
- // );
- // }: {
- // let mut property_writer = pallet_common::BenchmarkPropertyWriter::new(&collection, lazy_collection_info);
-
- // property_writer.write_token_properties(
- // item,
- // props.into_iter(),
- // crate::erc::ERC721TokenEvent::TokenChanged {
- // token_id: item.into(),
- // }
- // .to_log(T::ContractAddress::get()),
- // )?
- // }
-
#[benchmark]
- fn set_token_property_permissions(
- b: Linear<0, MAX_PROPERTIES_PER_ITEM>,
- ) -> Result<(), BenchmarkError> {
+ fn load_token_properties() -> Result<(), BenchmarkError> {
bench_init! {
owner: sub; collection: collection(owner);
owner: cross_from_sub;
};
- let perms = (0..b)
- .map(|k| PropertyKeyPermission {
- key: property_key(k as usize),
- permission: PropertyPermission {
- mutable: false,
- collection_admin: false,
- token_owner: false,
- },
- })
- .collect::<Vec<_>>();
+ let item = create_max_item(&collection, &owner, owner.clone())?;
+
#[block]
{
- <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
+ pallet_common::BenchmarkPropertyWriter::<T>::load_token_properties(&collection, item);
}
Ok(())
}
#[benchmark]
- fn set_token_properties(b: Linear<0, MAX_PROPERTIES_PER_ITEM>) -> Result<(), BenchmarkError> {
+ fn write_token_properties(b: Linear<0, MAX_PROPERTIES_PER_ITEM>) -> Result<(), BenchmarkError> {
bench_init! {
owner: sub; collection: collection(owner);
owner: cross_from_sub;
};
+
let perms = (0..b)
.map(|k| PropertyKeyPermission {
key: property_key(k as usize),
@@ -391,71 +267,29 @@
.collect::<Vec<_>>();
let item = create_max_item(&collection, &owner, owner.clone())?;
+ let lazy_collection_info =
+ pallet_common::BenchmarkPropertyWriter::<T>::load_collection_info(&collection, &owner);
+
#[block]
{
- <Pallet<T>>::set_token_properties(
- &collection,
- &owner,
+ let mut property_writer =
+ pallet_common::BenchmarkPropertyWriter::new(&collection, lazy_collection_info);
+
+ property_writer.write_token_properties(
item,
props.into_iter(),
- &Unlimited,
+ crate::erc::ERC721TokenEvent::TokenChanged {
+ token_id: item.into(),
+ }
+ .to_log(T::ContractAddress::get()),
)?;
}
Ok(())
}
- // TODO:
#[benchmark]
- fn init_token_properties(b: Linear<0, MAX_PROPERTIES_PER_ITEM>) -> Result<(), BenchmarkError> {
- // bench_init! {
- // owner: sub; collection: collection(owner);
- // owner: cross_from_sub;
- // };
-
- // let perms = (0..b)
- // .map(|k| PropertyKeyPermission {
- // key: property_key(k as usize),
- // permission: PropertyPermission {
- // mutable: false,
- // collection_admin: true,
- // token_owner: true,
- // },
- // })
- // .collect::<Vec<_>>();
- // <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
- #[block]
- {}
- // let props = (0..b)
- // .map(|k| Property {
- // key: property_key(k as usize),
- // value: property_value(),
- // })
- // .collect::<Vec<_>>();
- // let item = create_max_item(&collection, &owner, owner.clone())?;
-
- // let (is_collection_admin, property_permissions) =
- // load_is_admin_and_property_permissions(&collection, &owner);
- // #[block]
- // {
- // let mut property_writer =
- // pallet_common::BenchmarkPropertyWriter::new(&collection, lazy_collection_info);
-
- // property_writer.write_token_properties(
- // item,
- // props.into_iter(),
- // crate::erc::ERC721TokenEvent::TokenChanged {
- // token_id: item.into(),
- // }
- // .to_log(T::ContractAddress::get()),
- // )?;
- // }
-
- Ok(())
- }
-
- #[benchmark]
- fn delete_token_properties(
+ fn set_token_property_permissions(
b: Linear<0, MAX_PROPERTIES_PER_ITEM>,
) -> Result<(), BenchmarkError> {
bench_init! {
@@ -466,54 +300,16 @@
.map(|k| PropertyKeyPermission {
key: property_key(k as usize),
permission: PropertyPermission {
- mutable: true,
- collection_admin: true,
- token_owner: true,
+ mutable: false,
+ collection_admin: false,
+ token_owner: false,
},
- })
- .collect::<Vec<_>>();
- <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
- let props = (0..b)
- .map(|k| Property {
- key: property_key(k as usize),
- value: property_value(),
})
.collect::<Vec<_>>();
- let item = create_max_item(&collection, &owner, owner.clone())?;
- <Pallet<T>>::set_token_properties(
- &collection,
- &owner,
- item,
- props.into_iter(),
- &Unlimited,
- )?;
- let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
#[block]
{
- <Pallet<T>>::delete_token_properties(
- &collection,
- &owner,
- item,
- to_delete.into_iter(),
- &Unlimited,
- )?;
- }
-
- Ok(())
- }
-
- #[benchmark]
- fn token_owner() -> Result<(), BenchmarkError> {
- bench_init! {
- owner: sub; collection: collection(owner);
- owner: cross_from_sub;
- };
- let item = create_max_item(&collection, &owner, owner.clone())?;
-
- #[block]
- {
- collection.token_owner(item).unwrap();
+ <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
}
Ok(())
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -39,24 +39,21 @@
impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {
match data {
- CreateItemExData::NFT(t) => <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32)
- .saturating_add(write_token_properties_total_weight::<T, _>(
- t.iter().map(|t| t.properties.len() as u32),
- <SelfWeightOf<T>>::write_token_properties,
- )),
+ CreateItemExData::NFT(t) => mint_with_props_weight::<T>(
+ <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32),
+ t.iter().map(|t| t.properties.len() as u32),
+ ),
_ => Weight::zero(),
}
}
fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {
- <SelfWeightOf<T>>::create_multiple_items(data.len() as u32).saturating_add(
- write_token_properties_total_weight::<T, _>(
- data.iter().map(|t| match t {
- up_data_structs::CreateItemData::NFT(n) => n.properties.len() as u32,
- _ => 0,
- }),
- <SelfWeightOf<T>>::write_token_properties,
- ),
+ mint_with_props_weight::<T>(
+ <SelfWeightOf<T>>::create_multiple_items(data.len() as u32),
+ data.iter().map(|t| match t {
+ up_data_structs::CreateItemData::NFT(n) => n.properties.len() as u32,
+ _ => 0,
+ }),
)
}
@@ -113,6 +110,16 @@
}
}
+pub(crate) fn mint_with_props_weight<T: Config>(
+ create_no_data_weight: Weight,
+ tokens: impl Iterator<Item = u32> + Clone,
+) -> Weight {
+ create_no_data_weight.saturating_add(write_token_properties_total_weight::<T, _>(
+ tokens,
+ <SelfWeightOf<T>>::write_token_properties,
+ ))
+}
+
fn map_create_data<T: Config>(
data: up_data_structs::CreateItemData,
to: &T::CrossAccountId,
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -49,8 +49,10 @@
};
use crate::{
- common::CommonWeights, weights::WeightInfo, AccountBalance, Config, CreateItemData,
- NonfungibleHandle, Pallet, SelfWeightOf, TokenData, TokenProperties, TokensMinted,
+ common::{mint_with_props_weight, CommonWeights},
+ weights::WeightInfo,
+ AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, SelfWeightOf, TokenData,
+ TokenProperties, TokensMinted,
};
/// Nft events.
@@ -620,7 +622,7 @@
/// @param tokenUri Token URI that would be stored in the NFT properties
/// @return uint256 The id of the newly minted token
#[solidity(rename_selector = "mintWithTokenURI")]
- #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]
+ #[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [1].into_iter()))]
fn mint_with_token_uri(
&mut self,
caller: Caller,
@@ -642,7 +644,7 @@
/// @param tokenId ID of the minted NFT
/// @param tokenUri Token URI that would be stored in the NFT properties
#[solidity(hide, rename_selector = "mintWithTokenURI")]
- #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]
+ #[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [1].into_iter()))]
fn mint_with_token_uri_check_id(
&mut self,
caller: Caller,
@@ -974,7 +976,12 @@
/// @notice Function to mint a token.
/// @param data Array of pairs of token owner and token's properties for minted token
- #[weight(<SelfWeightOf<T>>::create_multiple_items(data.len() as u32) + <SelfWeightOf<T>>::set_token_properties(data.len() as u32))]
+ #[weight(
+ mint_with_props_weight::<T>(
+ <SelfWeightOf<T>>::create_multiple_items_ex(data.len() as u32),
+ data.iter().map(|d| d.properties.len() as u32),
+ )
+ )]
fn mint_bulk_cross(&mut self, caller: Caller, data: Vec<MintTokenData>) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -1008,7 +1015,12 @@
/// @param to The new owner
/// @param tokens array of pairs of token ID and token URI for minted tokens
#[solidity(hide, rename_selector = "mintBulkWithTokenURI")]
- #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]
+ #[weight(
+ mint_with_props_weight::<T>(
+ <SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32),
+ tokens.iter().map(|_| 1),
+ )
+ )]
fn mint_bulk_with_token_uri(
&mut self,
caller: Caller,
@@ -1056,7 +1068,7 @@
/// @param to The new owner crossAccountId
/// @param properties Properties of minted token
/// @return uint256 The id of the newly minted token
- #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]
+ #[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [properties.len() as u32].into_iter()))]
fn mint_cross(
&mut self,
caller: Caller,
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -421,114 +421,30 @@
Ok(())
}
- // set_token_properties {
- // let b in 0..MAX_PROPERTIES_PER_ITEM;
- // bench_init!{
- // owner: sub; collection: collection(owner);
- // owner: cross_from_sub;
- // };
- // let perms = (0..b).map(|k| PropertyKeyPermission {
- // key: property_key(k as usize),
- // permission: PropertyPermission {
- // mutable: false,
- // collection_admin: true,
- // token_owner: true,
- // },
- // }).collect::<Vec<_>>();
- // <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
- // let props = (0..b).map(|k| Property {
- // key: property_key(k as usize),
- // value: property_value(),
- // }).collect::<Vec<_>>();
- // let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
- // }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), &Unlimited)?}
-
- // load_token_properties {
- // bench_init!{
- // owner: sub; collection: collection(owner);
- // owner: cross_from_sub;
- // };
-
- // let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
- // }: {
- // pallet_common::BenchmarkPropertyWriter::<T>::load_token_properties(
- // &collection,
- // item,
- // )
- // }
-
- // write_token_properties {
- // let b in 0..MAX_PROPERTIES_PER_ITEM;
- // bench_init!{
- // owner: sub; collection: collection(owner);
- // owner: cross_from_sub;
- // };
-
- // let perms = (0..b).map(|k| PropertyKeyPermission {
- // key: property_key(k as usize),
- // permission: PropertyPermission {
- // mutable: false,
- // collection_admin: true,
- // token_owner: true,
- // },
- // }).collect::<Vec<_>>();
- // <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
- // let props = (0..b).map(|k| Property {
- // key: property_key(k as usize),
- // value: property_value(),
- // }).collect::<Vec<_>>();
- // let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
-
- // let lazy_collection_info = pallet_common::BenchmarkPropertyWriter::<T>::load_collection_info(
- // &collection,
- // &owner,
- // );
- // }: {
- // let mut property_writer = pallet_common::BenchmarkPropertyWriter::new(&collection, lazy_collection_info);
-
- // property_writer.write_token_properties(
- // item,
- // props.into_iter(),
- // crate::erc::ERC721TokenEvent::TokenChanged {
- // token_id: item.into(),
- // }
- // .to_log(T::ContractAddress::get()),
- // )?
- // }
-
#[benchmark]
- fn set_token_property_permissions(
- b: Linear<0, MAX_PROPERTIES_PER_ITEM>,
- ) -> Result<(), BenchmarkError> {
+ fn load_token_properties() -> Result<(), BenchmarkError> {
bench_init! {
owner: sub; collection: collection(owner);
owner: cross_from_sub;
};
- let perms = (0..b)
- .map(|k| PropertyKeyPermission {
- key: property_key(k as usize),
- permission: PropertyPermission {
- mutable: false,
- collection_admin: false,
- token_owner: false,
- },
- })
- .collect::<Vec<_>>();
+ let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
+
#[block]
{
- <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
+ pallet_common::BenchmarkPropertyWriter::<T>::load_token_properties(&collection, item);
}
Ok(())
}
#[benchmark]
- fn set_token_properties(b: Linear<0, MAX_PROPERTIES_PER_ITEM>) -> Result<(), BenchmarkError> {
+ fn write_token_properties(b: Linear<0, MAX_PROPERTIES_PER_ITEM>) -> Result<(), BenchmarkError> {
bench_init! {
owner: sub; collection: collection(owner);
owner: cross_from_sub;
};
+
let perms = (0..b)
.map(|k| PropertyKeyPermission {
key: property_key(k as usize),
@@ -548,73 +464,29 @@
.collect::<Vec<_>>();
let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
+ let lazy_collection_info =
+ pallet_common::BenchmarkPropertyWriter::<T>::load_collection_info(&collection, &owner);
+
#[block]
{
- <Pallet<T>>::set_token_properties(
- &collection,
- &owner,
+ let mut property_writer =
+ pallet_common::BenchmarkPropertyWriter::new(&collection, lazy_collection_info);
+
+ property_writer.write_token_properties(
item,
props.into_iter(),
- &Unlimited,
+ crate::erc::ERC721TokenEvent::TokenChanged {
+ token_id: item.into(),
+ }
+ .to_log(T::ContractAddress::get()),
)?;
}
Ok(())
}
- // TODO:
#[benchmark]
- fn init_token_properties(b: Linear<0, MAX_PROPERTIES_PER_ITEM>) -> Result<(), BenchmarkError> {
- // bench_init! {
- // owner: sub; collection: collection(owner);
- // owner: cross_from_sub;
- // };
-
- // let perms = (0..b)
- // .map(|k| PropertyKeyPermission {
- // key: property_key(k as usize),
- // permission: PropertyPermission {
- // mutable: false,
- // collection_admin: true,
- // token_owner: true,
- // },
- // })
- // .collect::<Vec<_>>();
- // <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
-
- #[block]
- {}
- // let props = (0..b).map(|k| Property {
- // key: property_key(k as usize),
- // value: property_value(),
- // }).collect::<Vec<_>>();
- // let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
-
- // let (is_collection_admin, property_permissions) = load_is_admin_and_property_permissions(&collection, &owner)
- // let mut property_writer = pallet_common::collection_info_loaded_property_writer(
- // &collection,
- // is_collection_admin,
- // property_permissions,
- // );
-
- // #[block]
- // {
- // property_writer.write_token_properties(
- // true,
- // item,
- // props.into_iter(),
- // crate::erc::ERC721TokenEvent::TokenChanged {
- // token_id: item.into(),
- // }
- // .to_log(T::ContractAddress::get()),
- // )?;
- // }
-
- Ok(())
- }
-
- #[benchmark]
- fn delete_token_properties(
+ fn set_token_property_permissions(
b: Linear<0, MAX_PROPERTIES_PER_ITEM>,
) -> Result<(), BenchmarkError> {
bench_init! {
@@ -625,38 +497,16 @@
.map(|k| PropertyKeyPermission {
key: property_key(k as usize),
permission: PropertyPermission {
- mutable: true,
- collection_admin: true,
- token_owner: true,
+ mutable: false,
+ collection_admin: false,
+ token_owner: false,
},
- })
- .collect::<Vec<_>>();
- <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
- let props = (0..b)
- .map(|k| Property {
- key: property_key(k as usize),
- value: property_value(),
})
.collect::<Vec<_>>();
- let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
- <Pallet<T>>::set_token_properties(
- &collection,
- &owner,
- item,
- props.into_iter(),
- &Unlimited,
- )?;
- let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
#[block]
{
- <Pallet<T>>::delete_token_properties(
- &collection,
- &owner,
- item,
- to_delete.into_iter(),
- &Unlimited,
- )?;
+ <Pallet<T>>::set_token_property_permissions(&collection, &owner, perms)?;
}
Ok(())
@@ -673,22 +523,6 @@
#[block]
{
<Pallet<T>>::repartition(&collection, &owner, item, 200)?;
- }
-
- Ok(())
- }
-
- #[benchmark]
- fn token_owner() -> Result<(), BenchmarkError> {
- bench_init! {
- owner: sub; collection: collection(owner);
- sender: cross_from_sub(owner); owner: cross_sub;
- };
- let item = create_max_item(&collection, &sender, [(owner, 100)])?;
-
- #[block]
- {
- <Pallet<T>>::token_owner(collection.id, item).unwrap();
}
Ok(())
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -47,35 +47,27 @@
pub struct CommonWeights<T: Config>(PhantomData<T>);
impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {
- <SelfWeightOf<T>>::create_multiple_items(data.len() as u32).saturating_add(
- write_token_properties_total_weight::<T, _>(
- data.iter().map(|data| match data {
- up_data_structs::CreateItemData::ReFungible(rft_data) => {
- rft_data.properties.len() as u32
- }
- _ => 0,
- }),
- <SelfWeightOf<T>>::write_token_properties,
- ),
+ mint_with_props_weight::<T>(
+ <SelfWeightOf<T>>::create_multiple_items(data.len() as u32),
+ data.iter().map(|data| match data {
+ up_data_structs::CreateItemData::ReFungible(rft_data) => {
+ rft_data.properties.len() as u32
+ }
+ _ => 0,
+ }),
)
}
fn create_multiple_items_ex(call: &CreateItemExData<T::CrossAccountId>) -> Weight {
match call {
- CreateItemExData::RefungibleMultipleOwners(i) => {
- <SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32)
- .saturating_add(write_token_properties_total_weight::<T, _>(
- [i.properties.len() as u32].into_iter(),
- <SelfWeightOf<T>>::write_token_properties,
- ))
- }
- CreateItemExData::RefungibleMultipleItems(i) => {
- <SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32)
- .saturating_add(write_token_properties_total_weight::<T, _>(
- i.iter().map(|d| d.properties.len() as u32),
- <SelfWeightOf<T>>::write_token_properties,
- ))
- }
+ CreateItemExData::RefungibleMultipleOwners(i) => mint_with_props_weight::<T>(
+ <SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32),
+ [i.properties.len() as u32].into_iter(),
+ ),
+ CreateItemExData::RefungibleMultipleItems(i) => mint_with_props_weight::<T>(
+ <SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32),
+ i.iter().map(|d| d.properties.len() as u32),
+ ),
_ => Weight::zero(),
}
}
@@ -138,6 +130,16 @@
}
}
+pub(crate) fn mint_with_props_weight<T: Config>(
+ create_no_data_weight: Weight,
+ tokens: impl Iterator<Item = u32> + Clone,
+) -> Weight {
+ create_no_data_weight.saturating_add(write_token_properties_total_weight::<T, _>(
+ tokens,
+ <SelfWeightOf<T>>::write_token_properties,
+ ))
+}
+
fn map_create_data<T: Config>(
data: up_data_structs::CreateItemData,
to: &T::CrossAccountId,
pallets/refungible/src/erc.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use alloc::string::ToString;25use core::{26 char::{decode_utf16, REPLACEMENT_CHARACTER},27 convert::TryInto,28};2930use evm_coder::{abi::AbiType, generate_stubgen, solidity_interface, types::*, AbiCoder, ToLog};31use frame_support::{BoundedBTreeMap, BoundedVec};32use pallet_common::{33 erc::{static_property::key, CollectionCall, CommonEvmHandler},34 eth::{self, TokenUri},35 CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations, CommonWeightInfo,36 Error as CommonError,37};38use pallet_evm::{account::CrossAccountId, PrecompileHandle};39use pallet_evm_coder_substrate::{40 call, dispatch_to_evm,41 execution::{Error, PreDispatch, Result},42 frontier_contract, SubstrateRecorder,43};44use pallet_structure::{weights::WeightInfo as _, SelfWeightOf as StructureWeight};45use sp_core::{Get, H160, U256};46use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};47use up_data_structs::{48 budget::Budget, mapping::TokenAddressMapping, CollectionId, CollectionPropertiesVec, Property,49 PropertyKey, PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,50};5152use crate::{53 common::CommonWeights, weights::WeightInfo, AccountBalance, Balance, Config, CreateItemData,54 Pallet, RefungibleHandle, SelfWeightOf, TokenProperties, TokensMinted, TotalSupply,55};5657frontier_contract! {58 macro_rules! RefungibleHandle_result {...}59 impl<T: Config> Contract for RefungibleHandle<T> {...}60}6162pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);6364/// Rft events.65#[derive(ToLog)]66pub enum ERC721TokenEvent {67 /// The token has been changed.68 TokenChanged {69 /// Token ID.70 #[indexed]71 token_id: U256,72 },73}7475/// Token minting parameters76#[derive(AbiCoder, Default, Debug)]77pub struct OwnerPieces {78 /// Minted token owner79 pub owner: eth::CrossAddress,80 /// Number of token pieces81 pub pieces: u128,82}8384/// Token minting parameters85#[derive(AbiCoder, Default, Debug)]86pub struct MintTokenData {87 /// Minted token owner and number of pieces88 pub owners: Vec<OwnerPieces>,89 /// Minted token properties90 pub properties: Vec<eth::Property>,91}9293pub fn nesting_budget<T: Config>(recorder: &SubstrateRecorder<T>) -> impl Budget + '_ {94 recorder.weight_calls_budget(<StructureWeight<T>>::find_parent())95}9697/// @title A contract that allows to set and delete token properties and change token property permissions.98#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]99impl<T: Config> RefungibleHandle<T> {100 /// @notice Set permissions for token property.101 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.102 /// @param key Property key.103 /// @param isMutable Permission to mutate property.104 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.105 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.106 #[solidity(hide)]107 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]108 fn set_token_property_permission(109 &mut self,110 caller: Caller,111 key: String,112 is_mutable: bool,113 collection_admin: bool,114 token_owner: bool,115 ) -> Result<()> {116 let caller = T::CrossAccountId::from_eth(caller);117 <Pallet<T>>::set_token_property_permissions(118 self,119 &caller,120 vec![PropertyKeyPermission {121 key: <Vec<u8>>::from(key)122 .try_into()123 .map_err(|_| "too long key")?,124 permission: PropertyPermission {125 mutable: is_mutable,126 collection_admin,127 token_owner,128 },129 }],130 )131 .map_err(dispatch_to_evm::<T>)132 }133134 /// @notice Set permissions for token property.135 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.136 /// @param permissions Permissions for keys.137 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]138 fn set_token_property_permissions(139 &mut self,140 caller: Caller,141 permissions: Vec<eth::TokenPropertyPermission>,142 ) -> Result<()> {143 let caller = T::CrossAccountId::from_eth(caller);144 let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;145146 <Pallet<T>>::set_token_property_permissions(self, &caller, perms)147 .map_err(dispatch_to_evm::<T>)148 }149150 /// @notice Get permissions for token properties.151 fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {152 let perms = <Pallet<T>>::token_property_permission(self.id);153 Ok(perms154 .into_iter()155 .map(eth::TokenPropertyPermission::from)156 .collect())157 }158159 /// @notice Set token property value.160 /// @dev Throws error if `msg.sender` has no permission to edit the property.161 /// @param tokenId ID of the token.162 /// @param key Property key.163 /// @param value Property value.164 #[solidity(hide)]165 #[weight(<CommonWeights<T>>::set_token_properties(1))]166 fn set_property(167 &mut self,168 caller: Caller,169 token_id: U256,170 key: String,171 value: Bytes,172 ) -> Result<()> {173 let caller = T::CrossAccountId::from_eth(caller);174 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;175 let key = <Vec<u8>>::from(key)176 .try_into()177 .map_err(|_| "key too long")?;178 let value = value.0.try_into().map_err(|_| "value too long")?;179180 <Pallet<T>>::set_token_property(181 self,182 &caller,183 TokenId(token_id),184 Property { key, value },185 &nesting_budget(&self.recorder),186 )187 .map_err(dispatch_to_evm::<T>)188 }189190 /// @notice Set token properties value.191 /// @dev Throws error if `msg.sender` has no permission to edit the property.192 /// @param tokenId ID of the token.193 /// @param properties settable properties194 #[weight(<CommonWeights<T>>::set_token_properties(properties.len() as u32))]195 fn set_properties(196 &mut self,197 caller: Caller,198 token_id: U256,199 properties: Vec<eth::Property>,200 ) -> Result<()> {201 let caller = T::CrossAccountId::from_eth(caller);202 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;203204 let properties = properties205 .into_iter()206 .map(eth::Property::try_into)207 .collect::<Result<Vec<_>>>()?;208209 <Pallet<T>>::set_token_properties(210 self,211 &caller,212 TokenId(token_id),213 properties.into_iter(),214 &nesting_budget(&self.recorder),215 )216 .map_err(dispatch_to_evm::<T>)217 }218219 /// @notice Delete token property value.220 /// @dev Throws error if `msg.sender` has no permission to edit the property.221 /// @param tokenId ID of the token.222 /// @param key Property key.223 #[solidity(hide)]224 #[weight(<CommonWeights<T>>::delete_token_properties(1))]225 fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {226 let caller = T::CrossAccountId::from_eth(caller);227 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;228 let key = <Vec<u8>>::from(key)229 .try_into()230 .map_err(|_| "key too long")?;231232 <Pallet<T>>::delete_token_property(233 self,234 &caller,235 TokenId(token_id),236 key,237 &nesting_budget(&self.recorder),238 )239 .map_err(dispatch_to_evm::<T>)240 }241242 /// @notice Delete token properties value.243 /// @dev Throws error if `msg.sender` has no permission to edit the property.244 /// @param tokenId ID of the token.245 /// @param keys Properties key.246 #[weight(<CommonWeights<T>>::delete_token_properties(keys.len() as u32))]247 fn delete_properties(248 &mut self,249 token_id: U256,250 caller: Caller,251 keys: Vec<String>,252 ) -> Result<()> {253 let caller = T::CrossAccountId::from_eth(caller);254 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;255 let keys = keys256 .into_iter()257 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))258 .collect::<Result<Vec<_>>>()?;259260 <Pallet<T>>::delete_token_properties(261 self,262 &caller,263 TokenId(token_id),264 keys.into_iter(),265 &nesting_budget(&self.recorder),266 )267 .map_err(dispatch_to_evm::<T>)268 }269270 /// @notice Get token property value.271 /// @dev Throws error if key not found272 /// @param tokenId ID of the token.273 /// @param key Property key.274 /// @return Property value bytes275 fn property(&self, token_id: U256, key: String) -> Result<Bytes> {276 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;277 let key = <Vec<u8>>::from(key)278 .try_into()279 .map_err(|_| "key too long")?;280281 let props =282 <TokenProperties<T>>::get((self.id, token_id)).ok_or("token properties not found")?;283 let prop = props.get(&key).ok_or("key not found")?;284285 Ok(prop.to_vec().into())286 }287}288289#[derive(ToLog)]290pub enum ERC721Events {291 /// @dev This event emits when NFTs are created (`from` == 0) and destroyed292 /// (`to` == 0). Exception: during contract creation, any number of RFTs293 /// may be created and assigned without emitting Transfer.294 Transfer {295 #[indexed]296 from: Address,297 #[indexed]298 to: Address,299 #[indexed]300 token_id: U256,301 },302 /// @dev Not supported303 Approval {304 #[indexed]305 owner: Address,306 #[indexed]307 approved: Address,308 #[indexed]309 token_id: U256,310 },311 /// @dev Not supported312 #[allow(dead_code)]313 ApprovalForAll {314 #[indexed]315 owner: Address,316 #[indexed]317 operator: Address,318 approved: bool,319 },320}321322/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension323/// @dev See https://eips.ethereum.org/EIPS/eip-721324#[solidity_interface(name = ERC721Metadata, enum(derive(PreDispatch)), expect_selector = 0x5b5e139f)]325impl<T: Config> RefungibleHandle<T>326where327 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,328{329 /// @notice A descriptive name for a collection of NFTs in this contract330 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`331 #[solidity(hide, rename_selector = "name")]332 fn name_proxy(&self) -> Result<String> {333 self.name()334 }335336 /// @notice An abbreviated name for NFTs in this contract337 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`338 #[solidity(hide, rename_selector = "symbol")]339 fn symbol_proxy(&self) -> Result<String> {340 self.symbol()341 }342343 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.344 ///345 /// @dev If the token has a `url` property and it is not empty, it is returned.346 /// 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`.347 /// If the collection property `baseURI` is empty or absent, return "" (empty string)348 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix349 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).350 ///351 /// @return token's const_metadata352 #[solidity(rename_selector = "tokenURI")]353 fn token_uri(&self, token_id: U256) -> Result<String> {354 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;355356 match get_token_property(self, token_id_u32, &key::url()).as_deref() {357 Err(_) | Ok("") => (),358 Ok(url) => {359 return Ok(url.into());360 }361 };362363 let base_uri =364 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())365 .map(BoundedVec::into_inner)366 .map(String::from_utf8)367 .transpose()368 .map_err(|e| {369 Error::Revert(alloc::format!(370 "can not convert value \"baseURI\" to string with error \"{e}\""371 ))372 })?;373374 let base_uri = match base_uri.as_deref() {375 None | Some("") => {376 return Ok("".into());377 }378 Some(base_uri) => base_uri.into(),379 };380381 Ok(382 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {383 Err(_) | Ok("") => base_uri,384 Ok(suffix) => base_uri + suffix,385 },386 )387 }388}389390/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension391/// @dev See https://eips.ethereum.org/EIPS/eip-721392#[solidity_interface(name = ERC721Enumerable, enum(derive(PreDispatch)), expect_selector = 0x780e9d63)]393impl<T: Config> RefungibleHandle<T> {394 /// @notice Enumerate valid RFTs395 /// @param index A counter less than `totalSupply()`396 /// @return The token identifier for the `index`th NFT,397 /// (sort order not specified)398 fn token_by_index(&self, index: U256) -> U256 {399 index400 }401402 /// Not implemented403 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {404 // TODO: Not implemetable405 Err("not implemented".into())406 }407408 /// @notice Count RFTs tracked by this contract409 /// @return A count of valid RFTs tracked by this contract, where each one of410 /// them has an assigned and queryable owner not equal to the zero address411 fn total_supply(&self) -> Result<U256> {412 self.consume_store_reads(1)?;413 Ok(<Pallet<T>>::total_supply(self).into())414 }415}416417/// @title ERC-721 Non-Fungible Token Standard418/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md419#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]420impl<T: Config> RefungibleHandle<T> {421 /// @notice Count all RFTs assigned to an owner422 /// @dev RFTs assigned to the zero address are considered invalid, and this423 /// function throws for queries about the zero address.424 /// @param owner An address for whom to query the balance425 /// @return The number of RFTs owned by `owner`, possibly zero426 fn balance_of(&self, owner: Address) -> Result<U256> {427 self.consume_store_reads(1)?;428 let owner = T::CrossAccountId::from_eth(owner);429 let balance = <AccountBalance<T>>::get((self.id, owner));430 Ok(balance.into())431 }432433 /// @notice Find the owner of an RFT434 /// @dev RFTs assigned to zero address are considered invalid, and queries435 /// about them do throw.436 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for437 /// the tokens that are partially owned.438 /// @param tokenId The identifier for an RFT439 /// @return The address of the owner of the RFT440 fn owner_of(&self, token_id: U256) -> Result<Address> {441 self.consume_store_reads(2)?;442 let token = token_id.try_into()?;443 let owner = <Pallet<T>>::token_owner(self.id, token);444 owner445 .map(|address| *address.as_eth())446 .or_else(|err| match err {447 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),448 TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),449 })450 }451452 /// @dev Not implemented453 #[solidity(rename_selector = "safeTransferFrom")]454 fn safe_transfer_from_with_data(455 &mut self,456 _from: Address,457 _to: Address,458 _token_id: U256,459 _data: Bytes,460 ) -> Result<()> {461 // TODO: Not implemetable462 Err("not implemented".into())463 }464465 /// @dev Not implemented466 #[solidity(rename_selector = "safeTransferFrom")]467 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {468 // TODO: Not implemetable469 Err("not implemented".into())470 }471472 /// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE473 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE474 /// THEY MAY BE PERMANENTLY LOST475 /// @dev Throws unless `msg.sender` is the current owner or an authorized476 /// operator for this RFT. Throws if `from` is not the current owner. Throws477 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.478 /// Throws if RFT pieces have multiple owners.479 /// @param from The current owner of the NFT480 /// @param to The new owner481 /// @param tokenId The NFT to transfer482 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]483 fn transfer_from(484 &mut self,485 caller: Caller,486 from: Address,487 to: Address,488 token_id: U256,489 ) -> Result<()> {490 let caller = T::CrossAccountId::from_eth(caller);491 let from = T::CrossAccountId::from_eth(from);492 let to = T::CrossAccountId::from_eth(to);493 let token = token_id.try_into()?;494495 let balance = balance(self, token, &from)?;496 ensure_single_owner(self, token, balance)?;497498 <Pallet<T>>::transfer_from(499 self,500 &caller,501 &from,502 &to,503 token,504 balance,505 &nesting_budget(&self.recorder),506 )507 .map_err(dispatch_to_evm::<T>)?;508509 Ok(())510 }511512 /// @dev Not implemented513 fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {514 Err("not implemented".into())515 }516517 /// @notice Sets or unsets the approval of a given operator.518 /// The `operator` is allowed to transfer all token pieces of the `caller` on their behalf.519 /// @param operator Operator520 /// @param approved Should operator status be granted or revoked?521 #[weight(<SelfWeightOf<T>>::set_allowance_for_all())]522 fn set_approval_for_all(523 &mut self,524 caller: Caller,525 operator: Address,526 approved: bool,527 ) -> Result<()> {528 let caller = T::CrossAccountId::from_eth(caller);529 let operator = T::CrossAccountId::from_eth(operator);530531 <Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)532 .map_err(dispatch_to_evm::<T>)?;533 Ok(())534 }535536 /// @dev Not implemented537 fn get_approved(&self, _token_id: U256) -> Result<Address> {538 // TODO: Not implemetable539 Err("not implemented".into())540 }541542 /// @notice Tells whether the given `owner` approves the `operator`.543 #[weight(<SelfWeightOf<T>>::allowance_for_all())]544 fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {545 let owner = T::CrossAccountId::from_eth(owner);546 let operator = T::CrossAccountId::from_eth(operator);547548 Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))549 }550}551552/// Returns amount of pieces of `token` that `owner` have553pub fn balance<T: Config>(554 collection: &RefungibleHandle<T>,555 token: TokenId,556 owner: &T::CrossAccountId,557) -> Result<u128> {558 collection.consume_store_reads(1)?;559 let balance = <Balance<T>>::get((collection.id, token, &owner));560 Ok(balance)561}562563/// Throws if `owner_balance` is lower than total amount of `token` pieces564pub fn ensure_single_owner<T: Config>(565 collection: &RefungibleHandle<T>,566 token: TokenId,567 owner_balance: u128,568) -> Result<()> {569 collection.consume_store_reads(1)?;570 let total_supply = <TotalSupply<T>>::get((collection.id, token));571572 if owner_balance == 0 {573 return Err(dispatch_to_evm::<T>(574 <CommonError<T>>::MustBeTokenOwner.into(),575 ));576 }577578 if total_supply != owner_balance {579 return Err("token has multiple owners".into());580 }581 Ok(())582}583584/// @title ERC721 Token that can be irreversibly burned (destroyed).585#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]586impl<T: Config> RefungibleHandle<T> {587 /// @notice Burns a specific ERC721 token.588 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized589 /// operator of the current owner.590 /// @param tokenId The RFT to approve591 #[weight(<SelfWeightOf<T>>::burn_item_fully())]592 fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {593 let caller = T::CrossAccountId::from_eth(caller);594 let token = token_id.try_into()?;595596 let balance = balance(self, token, &caller)?;597 ensure_single_owner(self, token, balance)?;598599 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;600 Ok(())601 }602}603604/// @title ERC721 minting logic.605#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]606impl<T: Config> RefungibleHandle<T> {607 /// @notice Function to mint a token.608 /// @param to The new owner609 /// @return uint256 The id of the newly minted token610 #[weight(<SelfWeightOf<T>>::create_item())]611 fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {612 let token_id: U256 = <TokensMinted<T>>::get(self.id)613 .checked_add(1)614 .ok_or("item id overflow")?615 .into();616 self.mint_check_id(caller, to, token_id)?;617 Ok(token_id)618 }619620 /// @notice Function to mint a token.621 /// @dev `tokenId` should be obtained with `nextTokenId` method,622 /// unlike standard, you can't specify it manually623 /// @param to The new owner624 /// @param tokenId ID of the minted RFT625 #[solidity(hide, rename_selector = "mint")]626 #[weight(<SelfWeightOf<T>>::create_item())]627 fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {628 let caller = T::CrossAccountId::from_eth(caller);629 let to = T::CrossAccountId::from_eth(to);630 let token_id: u32 = token_id.try_into()?;631632 if <TokensMinted<T>>::get(self.id)633 .checked_add(1)634 .ok_or("item id overflow")?635 != token_id636 {637 return Err("item id should be next".into());638 }639640 let users = [(to, 1)]641 .into_iter()642 .collect::<BTreeMap<_, _>>()643 .try_into()644 .unwrap();645 <Pallet<T>>::create_item(646 self,647 &caller,648 CreateItemData::<T> {649 users,650 properties: CollectionPropertiesVec::default(),651 },652 &nesting_budget(&self.recorder),653 )654 .map_err(dispatch_to_evm::<T>)?;655656 Ok(true)657 }658659 /// @notice Function to mint token with the given tokenUri.660 /// @param to The new owner661 /// @param tokenUri Token URI that would be stored in the NFT properties662 /// @return uint256 The id of the newly minted token663 #[solidity(rename_selector = "mintWithTokenURI")]664 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]665 fn mint_with_token_uri(666 &mut self,667 caller: Caller,668 to: Address,669 token_uri: String,670 ) -> Result<U256> {671 let token_id: U256 = <TokensMinted<T>>::get(self.id)672 .checked_add(1)673 .ok_or("item id overflow")?674 .into();675 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;676 Ok(token_id)677 }678679 /// @notice Function to mint token with the given tokenUri.680 /// @dev `tokenId` should be obtained with `nextTokenId` method,681 /// unlike standard, you can't specify it manually682 /// @param to The new owner683 /// @param tokenId ID of the minted RFT684 /// @param tokenUri Token URI that would be stored in the RFT properties685 #[solidity(hide, rename_selector = "mintWithTokenURI")]686 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]687 fn mint_with_token_uri_check_id(688 &mut self,689 caller: Caller,690 to: Address,691 token_id: U256,692 token_uri: String,693 ) -> Result<bool> {694 let key = key::url();695 let permission = get_token_permission::<T>(self.id, &key)?;696 if !permission.collection_admin {697 return Err("operation is not allowed".into());698 }699700 let caller = T::CrossAccountId::from_eth(caller);701 let to = T::CrossAccountId::from_eth(to);702 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;703704 if <TokensMinted<T>>::get(self.id)705 .checked_add(1)706 .ok_or("item id overflow")?707 != token_id708 {709 return Err("item id should be next".into());710 }711712 let mut properties = CollectionPropertiesVec::default();713 properties714 .try_push(Property {715 key,716 value: token_uri717 .into_bytes()718 .try_into()719 .map_err(|_| "token uri is too long")?,720 })721 .map_err(|e| Error::Revert(alloc::format!("can't add property: {e:?}")))?;722723 let users = [(to, 1)]724 .into_iter()725 .collect::<BTreeMap<_, _>>()726 .try_into()727 .unwrap();728 <Pallet<T>>::create_item(729 self,730 &caller,731 CreateItemData::<T> { users, properties },732 &nesting_budget(&self.recorder),733 )734 .map_err(dispatch_to_evm::<T>)?;735 Ok(true)736 }737}738739fn get_token_property<T: Config>(740 collection: &CollectionHandle<T>,741 token_id: u32,742 key: &up_data_structs::PropertyKey,743) -> Result<String> {744 collection.consume_store_reads(1)?;745 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))746 .map_err(|_| Error::Revert("token properties not found".into()))?;747 if let Some(property) = properties.get(key) {748 return Ok(String::from_utf8_lossy(property).into());749 }750751 Err("property tokenURI not found".into())752}753754fn get_token_permission<T: Config>(755 collection_id: CollectionId,756 key: &PropertyKey,757) -> Result<PropertyPermission> {758 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)759 .map_err(|_| Error::Revert("no permissions for collection".into()))?;760 let a = token_property_permissions761 .get(key)762 .map(Clone::clone)763 .ok_or_else(|| {764 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();765 Error::Revert(alloc::format!("no permission for key {key}"))766 })?;767 Ok(a)768}769770/// @title Unique extensions for ERC721.771#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]772impl<T: Config> RefungibleHandle<T>773where774 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,775{776 /// @notice A descriptive name for a collection of NFTs in this contract777 fn name(&self) -> Result<String> {778 Ok(decode_utf16(self.name.iter().copied())779 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))780 .collect::<String>())781 }782783 /// @notice An abbreviated name for NFTs in this contract784 fn symbol(&self) -> Result<String> {785 Ok(String::from_utf8_lossy(&self.token_prefix).into())786 }787788 /// @notice A description for the collection.789 fn description(&self) -> Result<String> {790 Ok(decode_utf16(self.description.iter().copied())791 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))792 .collect::<String>())793 }794795 /// Returns the owner (in cross format) of the token.796 ///797 /// @param tokenId Id for the token.798 #[solidity(hide)]799 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {800 Self::owner_of_cross(self, token_id)801 }802803 /// Returns the owner (in cross format) of the token.804 ///805 /// @param tokenId Id for the token.806 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {807 Self::token_owner(self, token_id.try_into()?)808 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))809 .or_else(|err| match err {810 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),811 TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(812 ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,813 )),814 })815 }816817 /// @notice Count all RFTs assigned to an owner818 /// @param owner An cross address for whom to query the balance819 /// @return The number of RFTs owned by `owner`, possibly zero820 fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {821 self.consume_store_reads(1)?;822 let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));823 Ok(balance.into())824 }825826 /// Returns the token properties.827 ///828 /// @param tokenId Id for the token.829 /// @param keys Properties keys. Empty keys for all propertyes.830 /// @return Vector of properties key/value pairs.831 fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {832 let keys = keys833 .into_iter()834 .map(|key| {835 <Vec<u8>>::from(key)836 .try_into()837 .map_err(|_| Error::Revert("key too large".into()))838 })839 .collect::<Result<Vec<_>>>()?;840841 <Self as CommonCollectionOperations<T>>::token_properties(842 self,843 token_id.try_into()?,844 if keys.is_empty() { None } else { Some(keys) },845 )846 .into_iter()847 .map(eth::Property::try_from)848 .collect::<Result<Vec<_>>>()849 }850 /// @notice Transfer ownership of an RFT851 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`852 /// is the zero address. Throws if `tokenId` is not a valid RFT.853 /// Throws if RFT pieces have multiple owners.854 /// @param to The new owner855 /// @param tokenId The RFT to transfer856 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]857 fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {858 let caller = T::CrossAccountId::from_eth(caller);859 let to = T::CrossAccountId::from_eth(to);860 let token = token_id.try_into()?;861862 let balance = balance(self, token, &caller)?;863 ensure_single_owner(self, token, balance)?;864865 <Pallet<T>>::transfer(866 self,867 &caller,868 &to,869 token,870 balance,871 &nesting_budget(&self.recorder),872 )873 .map_err(dispatch_to_evm::<T>)?;874 Ok(())875 }876877 /// @notice Transfer ownership of an RFT878 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`879 /// is the zero address. Throws if `tokenId` is not a valid RFT.880 /// Throws if RFT pieces have multiple owners.881 /// @param to The new owner882 /// @param tokenId The RFT to transfer883 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]884 fn transfer_cross(885 &mut self,886 caller: Caller,887 to: eth::CrossAddress,888 token_id: U256,889 ) -> Result<()> {890 let caller = T::CrossAccountId::from_eth(caller);891 let to = to.into_sub_cross_account::<T>()?;892 let token = token_id.try_into()?;893894 let balance = balance(self, token, &caller)?;895 ensure_single_owner(self, token, balance)?;896897 <Pallet<T>>::transfer(898 self,899 &caller,900 &to,901 token,902 balance,903 &nesting_budget(&self.recorder),904 )905 .map_err(dispatch_to_evm::<T>)?;906 Ok(())907 }908909 /// @notice Transfer ownership of an RFT910 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`911 /// is the zero address. Throws if `tokenId` is not a valid RFT.912 /// Throws if RFT pieces have multiple owners.913 /// @param to The new owner914 /// @param tokenId The RFT to transfer915 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]916 fn transfer_from_cross(917 &mut self,918 caller: Caller,919 from: eth::CrossAddress,920 to: eth::CrossAddress,921 token_id: U256,922 ) -> Result<()> {923 let caller = T::CrossAccountId::from_eth(caller);924 let from = from.into_sub_cross_account::<T>()?;925 let to = to.into_sub_cross_account::<T>()?;926 let token_id = token_id.try_into()?;927928 let balance = balance(self, token_id, &from)?;929 ensure_single_owner(self, token_id, balance)?;930931 Pallet::<T>::transfer_from(932 self,933 &caller,934 &from,935 &to,936 token_id,937 balance,938 &nesting_budget(&self.recorder),939 )940 .map_err(dispatch_to_evm::<T>)?;941 Ok(())942 }943944 /// @notice Burns a specific ERC721 token.945 /// @dev Throws unless `msg.sender` is the current owner or an authorized946 /// operator for this RFT. Throws if `from` is not the current owner. Throws947 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.948 /// Throws if RFT pieces have multiple owners.949 /// @param from The current owner of the RFT950 /// @param tokenId The RFT to transfer951 #[solidity(hide)]952 #[weight(<SelfWeightOf<T>>::burn_from())]953 fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {954 let caller = T::CrossAccountId::from_eth(caller);955 let from = T::CrossAccountId::from_eth(from);956 let token = token_id.try_into()?;957958 let balance = balance(self, token, &from)?;959 ensure_single_owner(self, token, balance)?;960961 <Pallet<T>>::burn_from(962 self,963 &caller,964 &from,965 token,966 balance,967 &nesting_budget(&self.recorder),968 )969 .map_err(dispatch_to_evm::<T>)?;970 Ok(())971 }972973 /// @notice Burns a specific ERC721 token.974 /// @dev Throws unless `msg.sender` is the current owner or an authorized975 /// operator for this RFT. Throws if `from` is not the current owner. Throws976 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.977 /// Throws if RFT pieces have multiple owners.978 /// @param from The current owner of the RFT979 /// @param tokenId The RFT to transfer980 #[weight(<SelfWeightOf<T>>::burn_from())]981 fn burn_from_cross(982 &mut self,983 caller: Caller,984 from: eth::CrossAddress,985 token_id: U256,986 ) -> Result<()> {987 let caller = T::CrossAccountId::from_eth(caller);988 let from = from.into_sub_cross_account::<T>()?;989 let token = token_id.try_into()?;990991 let balance = balance(self, token, &from)?;992 ensure_single_owner(self, token, balance)?;993994 <Pallet<T>>::burn_from(995 self,996 &caller,997 &from,998 token,999 balance,1000 &nesting_budget(&self.recorder),1001 )1002 .map_err(dispatch_to_evm::<T>)?;1003 Ok(())1004 }10051006 /// @notice Returns next free RFT ID.1007 fn next_token_id(&self) -> Result<U256> {1008 self.consume_store_reads(1)?;1009 Ok(<Pallet<T>>::next_token_id(self)1010 .map_err(dispatch_to_evm::<T>)?1011 .into())1012 }10131014 /// @notice Function to mint multiple tokens.1015 /// @dev `tokenIds` should be an array of consecutive numbers and first number1016 /// should be obtained with `nextTokenId` method1017 /// @param to The new owner1018 /// @param tokenIds IDs of the minted RFTs1019 #[solidity(hide)]1020 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]1021 fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {1022 let caller = T::CrossAccountId::from_eth(caller);1023 let to = T::CrossAccountId::from_eth(to);1024 let mut expected_index = <TokensMinted<T>>::get(self.id)1025 .checked_add(1)1026 .ok_or("item id overflow")?;10271028 let total_tokens = token_ids.len();1029 for id in token_ids.into_iter() {1030 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1031 if id != expected_index {1032 return Err("item id should be next".into());1033 }1034 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;1035 }1036 let users = [(to, 1)]1037 .into_iter()1038 .collect::<BTreeMap<_, _>>()1039 .try_into()1040 .unwrap();1041 let create_item_data = CreateItemData::<T> {1042 users,1043 properties: CollectionPropertiesVec::default(),1044 };1045 let data = (0..total_tokens)1046 .map(|_| create_item_data.clone())1047 .collect();10481049 <Pallet<T>>::create_multiple_items(self, &caller, data, &nesting_budget(&self.recorder))1050 .map_err(dispatch_to_evm::<T>)?;1051 Ok(true)1052 }10531054 /// @notice Function to mint a token.1055 /// @param tokenProperties Properties of minted token1056 #[weight(if token_properties.len() == 1 {1057 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(token_properties.iter().next().unwrap().owners.len() as u32)1058 } else {1059 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(token_properties.len() as u32)1060 } + <SelfWeightOf<T>>::set_token_properties(token_properties.len() as u32))]1061 fn mint_bulk_cross(1062 &mut self,1063 caller: Caller,1064 token_properties: Vec<MintTokenData>,1065 ) -> Result<bool> {1066 let caller = T::CrossAccountId::from_eth(caller);1067 let has_multiple_tokens = token_properties.len() > 1;10681069 let mut create_rft_data = Vec::with_capacity(token_properties.len());1070 for MintTokenData { owners, properties } in token_properties {1071 let has_multiple_owners = owners.len() > 1;1072 if has_multiple_tokens & has_multiple_owners {1073 return Err(1074 "creation of multiple tokens supported only if they have single owner each"1075 .into(),1076 );1077 }1078 let users: BoundedBTreeMap<_, _, _> = owners1079 .into_iter()1080 .map(|data| Ok((data.owner.into_sub_cross_account::<T>()?, data.pieces)))1081 .collect::<Result<BTreeMap<_, _>>>()?1082 .try_into()1083 .map_err(|_| "too many users")?;1084 create_rft_data.push(CreateItemData::<T> {1085 properties: properties1086 .into_iter()1087 .map(|property| property.try_into())1088 .collect::<Result<Vec<_>>>()?1089 .try_into()1090 .map_err(|_| "too many properties")?,1091 users,1092 });1093 }10941095 <Pallet<T>>::create_multiple_items(1096 self,1097 &caller,1098 create_rft_data,1099 &nesting_budget(&self.recorder),1100 )1101 .map_err(dispatch_to_evm::<T>)?;1102 Ok(true)1103 }11041105 /// @notice Function to mint multiple tokens with the given tokenUris.1106 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive1107 /// numbers and first number should be obtained with `nextTokenId` method1108 /// @param to The new owner1109 /// @param tokens array of pairs of token ID and token URI for minted tokens1110 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1111 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]1112 fn mint_bulk_with_token_uri(1113 &mut self,1114 caller: Caller,1115 to: Address,1116 tokens: Vec<TokenUri>,1117 ) -> Result<bool> {1118 let key = key::url();1119 let caller = T::CrossAccountId::from_eth(caller);1120 let to = T::CrossAccountId::from_eth(to);1121 let mut expected_index = <TokensMinted<T>>::get(self.id)1122 .checked_add(1)1123 .ok_or("item id overflow")?;11241125 let mut data = Vec::with_capacity(tokens.len());1126 let users: BoundedBTreeMap<_, _, _> = [(to, 1)]1127 .into_iter()1128 .collect::<BTreeMap<_, _>>()1129 .try_into()1130 .unwrap();1131 for TokenUri { id, uri } in tokens {1132 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1133 if id != expected_index {1134 return Err("item id should be next".into());1135 }1136 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;11371138 let mut properties = CollectionPropertiesVec::default();1139 properties1140 .try_push(Property {1141 key: key.clone(),1142 value: uri1143 .into_bytes()1144 .try_into()1145 .map_err(|_| "token uri is too long")?,1146 })1147 .map_err(|e| Error::Revert(alloc::format!("can't add property: {e:?}")))?;11481149 let create_item_data = CreateItemData::<T> {1150 users: users.clone(),1151 properties,1152 };1153 data.push(create_item_data);1154 }11551156 <Pallet<T>>::create_multiple_items(self, &caller, data, &nesting_budget(&self.recorder))1157 .map_err(dispatch_to_evm::<T>)?;1158 Ok(true)1159 }11601161 /// @notice Function to mint a token.1162 /// @param to The new owner crossAccountId1163 /// @param properties Properties of minted token1164 /// @return uint256 The id of the newly minted token1165 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1166 fn mint_cross(1167 &mut self,1168 caller: Caller,1169 to: eth::CrossAddress,1170 properties: Vec<eth::Property>,1171 ) -> Result<U256> {1172 let token_id = <TokensMinted<T>>::get(self.id)1173 .checked_add(1)1174 .ok_or("item id overflow")?;11751176 let to = to.into_sub_cross_account::<T>()?;11771178 let properties = properties1179 .into_iter()1180 .map(eth::Property::try_into)1181 .collect::<Result<Vec<_>>>()?1182 .try_into()1183 .map_err(|_| Error::Revert("too many properties".to_string()))?;11841185 let caller = T::CrossAccountId::from_eth(caller);11861187 let users = [(to, 1)]1188 .into_iter()1189 .collect::<BTreeMap<_, _>>()1190 .try_into()1191 .unwrap();1192 <Pallet<T>>::create_item(1193 self,1194 &caller,1195 CreateItemData::<T> { users, properties },1196 &nesting_budget(&self.recorder),1197 )1198 .map_err(dispatch_to_evm::<T>)?;11991200 Ok(token_id.into())1201 }12021203 /// Returns EVM address for refungible token1204 ///1205 /// @param token ID of the token1206 fn token_contract_address(&self, token: U256) -> Result<Address> {1207 Ok(T::EvmTokenAddressMapping::token_to_address(1208 self.id,1209 token.try_into().map_err(|_| "token id overflow")?,1210 ))1211 }12121213 /// @notice Returns collection helper contract address1214 fn collection_helper_address(&self) -> Result<Address> {1215 Ok(T::ContractAddress::get())1216 }1217}12181219#[solidity_interface(1220 name = UniqueRefungible,1221 is(1222 ERC721,1223 ERC721Enumerable,1224 ERC721UniqueExtensions,1225 ERC721UniqueMintable,1226 ERC721Burnable,1227 ERC721Metadata(if(this.flags.erc721metadata)),1228 Collection(via(common_mut returns CollectionHandle<T>)),1229 TokenProperties,1230 ),1231 enum(derive(PreDispatch)),1232)]1233impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}12341235// Not a tests, but code generators1236generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1237generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);12381239impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1240where1241 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1242{1243 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1244 fn call(1245 self,1246 handle: &mut impl PrecompileHandle,1247 ) -> Option<pallet_common::erc::PrecompileResult> {1248 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1249 }1250}