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}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//! # 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::{mint_with_props_weight, CommonWeights},54 weights::WeightInfo,55 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,56 TokenProperties, TokensMinted, TotalSupply,57};5859frontier_contract! {60 macro_rules! RefungibleHandle_result {...}61 impl<T: Config> Contract for RefungibleHandle<T> {...}62}6364pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);6566/// Rft events.67#[derive(ToLog)]68pub enum ERC721TokenEvent {69 /// The token has been changed.70 TokenChanged {71 /// Token ID.72 #[indexed]73 token_id: U256,74 },75}7677/// Token minting parameters78#[derive(AbiCoder, Default, Debug)]79pub struct OwnerPieces {80 /// Minted token owner81 pub owner: eth::CrossAddress,82 /// Number of token pieces83 pub pieces: u128,84}8586/// Token minting parameters87#[derive(AbiCoder, Default, Debug)]88pub struct MintTokenData {89 /// Minted token owner and number of pieces90 pub owners: Vec<OwnerPieces>,91 /// Minted token properties92 pub properties: Vec<eth::Property>,93}9495pub fn nesting_budget<T: Config>(recorder: &SubstrateRecorder<T>) -> impl Budget + '_ {96 recorder.weight_calls_budget(<StructureWeight<T>>::find_parent())97}9899/// @title A contract that allows to set and delete token properties and change token property permissions.100#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]101impl<T: Config> RefungibleHandle<T> {102 /// @notice Set permissions for token property.103 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.104 /// @param key Property key.105 /// @param isMutable Permission to mutate property.106 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.107 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.108 #[solidity(hide)]109 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]110 fn set_token_property_permission(111 &mut self,112 caller: Caller,113 key: String,114 is_mutable: bool,115 collection_admin: bool,116 token_owner: bool,117 ) -> Result<()> {118 let caller = T::CrossAccountId::from_eth(caller);119 <Pallet<T>>::set_token_property_permissions(120 self,121 &caller,122 vec![PropertyKeyPermission {123 key: <Vec<u8>>::from(key)124 .try_into()125 .map_err(|_| "too long key")?,126 permission: PropertyPermission {127 mutable: is_mutable,128 collection_admin,129 token_owner,130 },131 }],132 )133 .map_err(dispatch_to_evm::<T>)134 }135136 /// @notice Set permissions for token property.137 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.138 /// @param permissions Permissions for keys.139 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]140 fn set_token_property_permissions(141 &mut self,142 caller: Caller,143 permissions: Vec<eth::TokenPropertyPermission>,144 ) -> Result<()> {145 let caller = T::CrossAccountId::from_eth(caller);146 let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;147148 <Pallet<T>>::set_token_property_permissions(self, &caller, perms)149 .map_err(dispatch_to_evm::<T>)150 }151152 /// @notice Get permissions for token properties.153 fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {154 let perms = <Pallet<T>>::token_property_permission(self.id);155 Ok(perms156 .into_iter()157 .map(eth::TokenPropertyPermission::from)158 .collect())159 }160161 /// @notice Set token property value.162 /// @dev Throws error if `msg.sender` has no permission to edit the property.163 /// @param tokenId ID of the token.164 /// @param key Property key.165 /// @param value Property value.166 #[solidity(hide)]167 #[weight(<CommonWeights<T>>::set_token_properties(1))]168 fn set_property(169 &mut self,170 caller: Caller,171 token_id: U256,172 key: String,173 value: Bytes,174 ) -> Result<()> {175 let caller = T::CrossAccountId::from_eth(caller);176 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;177 let key = <Vec<u8>>::from(key)178 .try_into()179 .map_err(|_| "key too long")?;180 let value = value.0.try_into().map_err(|_| "value too long")?;181182 <Pallet<T>>::set_token_property(183 self,184 &caller,185 TokenId(token_id),186 Property { key, value },187 &nesting_budget(&self.recorder),188 )189 .map_err(dispatch_to_evm::<T>)190 }191192 /// @notice Set token properties value.193 /// @dev Throws error if `msg.sender` has no permission to edit the property.194 /// @param tokenId ID of the token.195 /// @param properties settable properties196 #[weight(<CommonWeights<T>>::set_token_properties(properties.len() as u32))]197 fn set_properties(198 &mut self,199 caller: Caller,200 token_id: U256,201 properties: Vec<eth::Property>,202 ) -> Result<()> {203 let caller = T::CrossAccountId::from_eth(caller);204 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;205206 let properties = properties207 .into_iter()208 .map(eth::Property::try_into)209 .collect::<Result<Vec<_>>>()?;210211 <Pallet<T>>::set_token_properties(212 self,213 &caller,214 TokenId(token_id),215 properties.into_iter(),216 &nesting_budget(&self.recorder),217 )218 .map_err(dispatch_to_evm::<T>)219 }220221 /// @notice Delete token property value.222 /// @dev Throws error if `msg.sender` has no permission to edit the property.223 /// @param tokenId ID of the token.224 /// @param key Property key.225 #[solidity(hide)]226 #[weight(<CommonWeights<T>>::delete_token_properties(1))]227 fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {228 let caller = T::CrossAccountId::from_eth(caller);229 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;230 let key = <Vec<u8>>::from(key)231 .try_into()232 .map_err(|_| "key too long")?;233234 <Pallet<T>>::delete_token_property(235 self,236 &caller,237 TokenId(token_id),238 key,239 &nesting_budget(&self.recorder),240 )241 .map_err(dispatch_to_evm::<T>)242 }243244 /// @notice Delete token properties value.245 /// @dev Throws error if `msg.sender` has no permission to edit the property.246 /// @param tokenId ID of the token.247 /// @param keys Properties key.248 #[weight(<CommonWeights<T>>::delete_token_properties(keys.len() as u32))]249 fn delete_properties(250 &mut self,251 token_id: U256,252 caller: Caller,253 keys: Vec<String>,254 ) -> Result<()> {255 let caller = T::CrossAccountId::from_eth(caller);256 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;257 let keys = keys258 .into_iter()259 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))260 .collect::<Result<Vec<_>>>()?;261262 <Pallet<T>>::delete_token_properties(263 self,264 &caller,265 TokenId(token_id),266 keys.into_iter(),267 &nesting_budget(&self.recorder),268 )269 .map_err(dispatch_to_evm::<T>)270 }271272 /// @notice Get token property value.273 /// @dev Throws error if key not found274 /// @param tokenId ID of the token.275 /// @param key Property key.276 /// @return Property value bytes277 fn property(&self, token_id: U256, key: String) -> Result<Bytes> {278 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;279 let key = <Vec<u8>>::from(key)280 .try_into()281 .map_err(|_| "key too long")?;282283 let props =284 <TokenProperties<T>>::get((self.id, token_id)).ok_or("token properties not found")?;285 let prop = props.get(&key).ok_or("key not found")?;286287 Ok(prop.to_vec().into())288 }289}290291#[derive(ToLog)]292pub enum ERC721Events {293 /// @dev This event emits when NFTs are created (`from` == 0) and destroyed294 /// (`to` == 0). Exception: during contract creation, any number of RFTs295 /// may be created and assigned without emitting Transfer.296 Transfer {297 #[indexed]298 from: Address,299 #[indexed]300 to: Address,301 #[indexed]302 token_id: U256,303 },304 /// @dev Not supported305 Approval {306 #[indexed]307 owner: Address,308 #[indexed]309 approved: Address,310 #[indexed]311 token_id: U256,312 },313 /// @dev Not supported314 #[allow(dead_code)]315 ApprovalForAll {316 #[indexed]317 owner: Address,318 #[indexed]319 operator: Address,320 approved: bool,321 },322}323324/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension325/// @dev See https://eips.ethereum.org/EIPS/eip-721326#[solidity_interface(name = ERC721Metadata, enum(derive(PreDispatch)), expect_selector = 0x5b5e139f)]327impl<T: Config> RefungibleHandle<T>328where329 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,330{331 /// @notice A descriptive name for a collection of NFTs in this contract332 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`333 #[solidity(hide, rename_selector = "name")]334 fn name_proxy(&self) -> Result<String> {335 self.name()336 }337338 /// @notice An abbreviated name for NFTs in this contract339 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`340 #[solidity(hide, rename_selector = "symbol")]341 fn symbol_proxy(&self) -> Result<String> {342 self.symbol()343 }344345 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.346 ///347 /// @dev If the token has a `url` property and it is not empty, it is returned.348 /// 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`.349 /// If the collection property `baseURI` is empty or absent, return "" (empty string)350 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix351 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).352 ///353 /// @return token's const_metadata354 #[solidity(rename_selector = "tokenURI")]355 fn token_uri(&self, token_id: U256) -> Result<String> {356 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;357358 match get_token_property(self, token_id_u32, &key::url()).as_deref() {359 Err(_) | Ok("") => (),360 Ok(url) => {361 return Ok(url.into());362 }363 };364365 let base_uri =366 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())367 .map(BoundedVec::into_inner)368 .map(String::from_utf8)369 .transpose()370 .map_err(|e| {371 Error::Revert(alloc::format!(372 "can not convert value \"baseURI\" to string with error \"{e}\""373 ))374 })?;375376 let base_uri = match base_uri.as_deref() {377 None | Some("") => {378 return Ok("".into());379 }380 Some(base_uri) => base_uri.into(),381 };382383 Ok(384 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {385 Err(_) | Ok("") => base_uri,386 Ok(suffix) => base_uri + suffix,387 },388 )389 }390}391392/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension393/// @dev See https://eips.ethereum.org/EIPS/eip-721394#[solidity_interface(name = ERC721Enumerable, enum(derive(PreDispatch)), expect_selector = 0x780e9d63)]395impl<T: Config> RefungibleHandle<T> {396 /// @notice Enumerate valid RFTs397 /// @param index A counter less than `totalSupply()`398 /// @return The token identifier for the `index`th NFT,399 /// (sort order not specified)400 fn token_by_index(&self, index: U256) -> U256 {401 index402 }403404 /// Not implemented405 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {406 // TODO: Not implemetable407 Err("not implemented".into())408 }409410 /// @notice Count RFTs tracked by this contract411 /// @return A count of valid RFTs tracked by this contract, where each one of412 /// them has an assigned and queryable owner not equal to the zero address413 fn total_supply(&self) -> Result<U256> {414 self.consume_store_reads(1)?;415 Ok(<Pallet<T>>::total_supply(self).into())416 }417}418419/// @title ERC-721 Non-Fungible Token Standard420/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md421#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]422impl<T: Config> RefungibleHandle<T> {423 /// @notice Count all RFTs assigned to an owner424 /// @dev RFTs assigned to the zero address are considered invalid, and this425 /// function throws for queries about the zero address.426 /// @param owner An address for whom to query the balance427 /// @return The number of RFTs owned by `owner`, possibly zero428 fn balance_of(&self, owner: Address) -> Result<U256> {429 self.consume_store_reads(1)?;430 let owner = T::CrossAccountId::from_eth(owner);431 let balance = <AccountBalance<T>>::get((self.id, owner));432 Ok(balance.into())433 }434435 /// @notice Find the owner of an RFT436 /// @dev RFTs assigned to zero address are considered invalid, and queries437 /// about them do throw.438 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for439 /// the tokens that are partially owned.440 /// @param tokenId The identifier for an RFT441 /// @return The address of the owner of the RFT442 fn owner_of(&self, token_id: U256) -> Result<Address> {443 self.consume_store_reads(2)?;444 let token = token_id.try_into()?;445 let owner = <Pallet<T>>::token_owner(self.id, token);446 owner447 .map(|address| *address.as_eth())448 .or_else(|err| match err {449 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),450 TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),451 })452 }453454 /// @dev Not implemented455 #[solidity(rename_selector = "safeTransferFrom")]456 fn safe_transfer_from_with_data(457 &mut self,458 _from: Address,459 _to: Address,460 _token_id: U256,461 _data: Bytes,462 ) -> Result<()> {463 // TODO: Not implemetable464 Err("not implemented".into())465 }466467 /// @dev Not implemented468 #[solidity(rename_selector = "safeTransferFrom")]469 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {470 // TODO: Not implemetable471 Err("not implemented".into())472 }473474 /// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE475 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE476 /// THEY MAY BE PERMANENTLY LOST477 /// @dev Throws unless `msg.sender` is the current owner or an authorized478 /// operator for this RFT. Throws if `from` is not the current owner. Throws479 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.480 /// Throws if RFT pieces have multiple owners.481 /// @param from The current owner of the NFT482 /// @param to The new owner483 /// @param tokenId The NFT to transfer484 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]485 fn transfer_from(486 &mut self,487 caller: Caller,488 from: Address,489 to: Address,490 token_id: U256,491 ) -> Result<()> {492 let caller = T::CrossAccountId::from_eth(caller);493 let from = T::CrossAccountId::from_eth(from);494 let to = T::CrossAccountId::from_eth(to);495 let token = token_id.try_into()?;496497 let balance = balance(self, token, &from)?;498 ensure_single_owner(self, token, balance)?;499500 <Pallet<T>>::transfer_from(501 self,502 &caller,503 &from,504 &to,505 token,506 balance,507 &nesting_budget(&self.recorder),508 )509 .map_err(dispatch_to_evm::<T>)?;510511 Ok(())512 }513514 /// @dev Not implemented515 fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {516 Err("not implemented".into())517 }518519 /// @notice Sets or unsets the approval of a given operator.520 /// The `operator` is allowed to transfer all token pieces of the `caller` on their behalf.521 /// @param operator Operator522 /// @param approved Should operator status be granted or revoked?523 #[weight(<SelfWeightOf<T>>::set_allowance_for_all())]524 fn set_approval_for_all(525 &mut self,526 caller: Caller,527 operator: Address,528 approved: bool,529 ) -> Result<()> {530 let caller = T::CrossAccountId::from_eth(caller);531 let operator = T::CrossAccountId::from_eth(operator);532533 <Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)534 .map_err(dispatch_to_evm::<T>)?;535 Ok(())536 }537538 /// @dev Not implemented539 fn get_approved(&self, _token_id: U256) -> Result<Address> {540 // TODO: Not implemetable541 Err("not implemented".into())542 }543544 /// @notice Tells whether the given `owner` approves the `operator`.545 #[weight(<SelfWeightOf<T>>::allowance_for_all())]546 fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {547 let owner = T::CrossAccountId::from_eth(owner);548 let operator = T::CrossAccountId::from_eth(operator);549550 Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))551 }552}553554/// Returns amount of pieces of `token` that `owner` have555pub fn balance<T: Config>(556 collection: &RefungibleHandle<T>,557 token: TokenId,558 owner: &T::CrossAccountId,559) -> Result<u128> {560 collection.consume_store_reads(1)?;561 let balance = <Balance<T>>::get((collection.id, token, &owner));562 Ok(balance)563}564565/// Throws if `owner_balance` is lower than total amount of `token` pieces566pub fn ensure_single_owner<T: Config>(567 collection: &RefungibleHandle<T>,568 token: TokenId,569 owner_balance: u128,570) -> Result<()> {571 collection.consume_store_reads(1)?;572 let total_supply = <TotalSupply<T>>::get((collection.id, token));573574 if owner_balance == 0 {575 return Err(dispatch_to_evm::<T>(576 <CommonError<T>>::MustBeTokenOwner.into(),577 ));578 }579580 if total_supply != owner_balance {581 return Err("token has multiple owners".into());582 }583 Ok(())584}585586/// @title ERC721 Token that can be irreversibly burned (destroyed).587#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]588impl<T: Config> RefungibleHandle<T> {589 /// @notice Burns a specific ERC721 token.590 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized591 /// operator of the current owner.592 /// @param tokenId The RFT to approve593 #[weight(<SelfWeightOf<T>>::burn_item_fully())]594 fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {595 let caller = T::CrossAccountId::from_eth(caller);596 let token = token_id.try_into()?;597598 let balance = balance(self, token, &caller)?;599 ensure_single_owner(self, token, balance)?;600601 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;602 Ok(())603 }604}605606/// @title ERC721 minting logic.607#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]608impl<T: Config> RefungibleHandle<T> {609 /// @notice Function to mint a token.610 /// @param to The new owner611 /// @return uint256 The id of the newly minted token612 #[weight(<SelfWeightOf<T>>::create_item())]613 fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {614 let token_id: U256 = <TokensMinted<T>>::get(self.id)615 .checked_add(1)616 .ok_or("item id overflow")?617 .into();618 self.mint_check_id(caller, to, token_id)?;619 Ok(token_id)620 }621622 /// @notice Function to mint a token.623 /// @dev `tokenId` should be obtained with `nextTokenId` method,624 /// unlike standard, you can't specify it manually625 /// @param to The new owner626 /// @param tokenId ID of the minted RFT627 #[solidity(hide, rename_selector = "mint")]628 #[weight(<SelfWeightOf<T>>::create_item())]629 fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {630 let caller = T::CrossAccountId::from_eth(caller);631 let to = T::CrossAccountId::from_eth(to);632 let token_id: u32 = token_id.try_into()?;633634 if <TokensMinted<T>>::get(self.id)635 .checked_add(1)636 .ok_or("item id overflow")?637 != token_id638 {639 return Err("item id should be next".into());640 }641642 let users = [(to, 1)]643 .into_iter()644 .collect::<BTreeMap<_, _>>()645 .try_into()646 .unwrap();647 <Pallet<T>>::create_item(648 self,649 &caller,650 CreateItemData::<T> {651 users,652 properties: CollectionPropertiesVec::default(),653 },654 &nesting_budget(&self.recorder),655 )656 .map_err(dispatch_to_evm::<T>)?;657658 Ok(true)659 }660661 /// @notice Function to mint token with the given tokenUri.662 /// @param to The new owner663 /// @param tokenUri Token URI that would be stored in the NFT properties664 /// @return uint256 The id of the newly minted token665 #[solidity(rename_selector = "mintWithTokenURI")]666 #[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [1].into_iter()))]667 fn mint_with_token_uri(668 &mut self,669 caller: Caller,670 to: Address,671 token_uri: String,672 ) -> Result<U256> {673 let token_id: U256 = <TokensMinted<T>>::get(self.id)674 .checked_add(1)675 .ok_or("item id overflow")?676 .into();677 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;678 Ok(token_id)679 }680681 /// @notice Function to mint token with the given tokenUri.682 /// @dev `tokenId` should be obtained with `nextTokenId` method,683 /// unlike standard, you can't specify it manually684 /// @param to The new owner685 /// @param tokenId ID of the minted RFT686 /// @param tokenUri Token URI that would be stored in the RFT properties687 #[solidity(hide, rename_selector = "mintWithTokenURI")]688 #[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [1].into_iter()))]689 fn mint_with_token_uri_check_id(690 &mut self,691 caller: Caller,692 to: Address,693 token_id: U256,694 token_uri: String,695 ) -> Result<bool> {696 let key = key::url();697 let permission = get_token_permission::<T>(self.id, &key)?;698 if !permission.collection_admin {699 return Err("operation is not allowed".into());700 }701702 let caller = T::CrossAccountId::from_eth(caller);703 let to = T::CrossAccountId::from_eth(to);704 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;705706 if <TokensMinted<T>>::get(self.id)707 .checked_add(1)708 .ok_or("item id overflow")?709 != token_id710 {711 return Err("item id should be next".into());712 }713714 let mut properties = CollectionPropertiesVec::default();715 properties716 .try_push(Property {717 key,718 value: token_uri719 .into_bytes()720 .try_into()721 .map_err(|_| "token uri is too long")?,722 })723 .map_err(|e| Error::Revert(alloc::format!("can't add property: {e:?}")))?;724725 let users = [(to, 1)]726 .into_iter()727 .collect::<BTreeMap<_, _>>()728 .try_into()729 .unwrap();730 <Pallet<T>>::create_item(731 self,732 &caller,733 CreateItemData::<T> { users, properties },734 &nesting_budget(&self.recorder),735 )736 .map_err(dispatch_to_evm::<T>)?;737 Ok(true)738 }739}740741fn get_token_property<T: Config>(742 collection: &CollectionHandle<T>,743 token_id: u32,744 key: &up_data_structs::PropertyKey,745) -> Result<String> {746 collection.consume_store_reads(1)?;747 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))748 .map_err(|_| Error::Revert("token properties not found".into()))?;749 if let Some(property) = properties.get(key) {750 return Ok(String::from_utf8_lossy(property).into());751 }752753 Err("property tokenURI not found".into())754}755756fn get_token_permission<T: Config>(757 collection_id: CollectionId,758 key: &PropertyKey,759) -> Result<PropertyPermission> {760 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)761 .map_err(|_| Error::Revert("no permissions for collection".into()))?;762 let a = token_property_permissions763 .get(key)764 .map(Clone::clone)765 .ok_or_else(|| {766 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();767 Error::Revert(alloc::format!("no permission for key {key}"))768 })?;769 Ok(a)770}771772/// @title Unique extensions for ERC721.773#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]774impl<T: Config> RefungibleHandle<T>775where776 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,777{778 /// @notice A descriptive name for a collection of NFTs in this contract779 fn name(&self) -> Result<String> {780 Ok(decode_utf16(self.name.iter().copied())781 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))782 .collect::<String>())783 }784785 /// @notice An abbreviated name for NFTs in this contract786 fn symbol(&self) -> Result<String> {787 Ok(String::from_utf8_lossy(&self.token_prefix).into())788 }789790 /// @notice A description for the collection.791 fn description(&self) -> Result<String> {792 Ok(decode_utf16(self.description.iter().copied())793 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))794 .collect::<String>())795 }796797 /// Returns the owner (in cross format) of the token.798 ///799 /// @param tokenId Id for the token.800 #[solidity(hide)]801 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {802 Self::owner_of_cross(self, token_id)803 }804805 /// Returns the owner (in cross format) of the token.806 ///807 /// @param tokenId Id for the token.808 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {809 Self::token_owner(self, token_id.try_into()?)810 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))811 .or_else(|err| match err {812 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),813 TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(814 ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,815 )),816 })817 }818819 /// @notice Count all RFTs assigned to an owner820 /// @param owner An cross address for whom to query the balance821 /// @return The number of RFTs owned by `owner`, possibly zero822 fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {823 self.consume_store_reads(1)?;824 let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));825 Ok(balance.into())826 }827828 /// Returns the token properties.829 ///830 /// @param tokenId Id for the token.831 /// @param keys Properties keys. Empty keys for all propertyes.832 /// @return Vector of properties key/value pairs.833 fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {834 let keys = keys835 .into_iter()836 .map(|key| {837 <Vec<u8>>::from(key)838 .try_into()839 .map_err(|_| Error::Revert("key too large".into()))840 })841 .collect::<Result<Vec<_>>>()?;842843 <Self as CommonCollectionOperations<T>>::token_properties(844 self,845 token_id.try_into()?,846 if keys.is_empty() { None } else { Some(keys) },847 )848 .into_iter()849 .map(eth::Property::try_from)850 .collect::<Result<Vec<_>>>()851 }852 /// @notice Transfer ownership of an RFT853 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`854 /// is the zero address. Throws if `tokenId` is not a valid RFT.855 /// Throws if RFT pieces have multiple owners.856 /// @param to The new owner857 /// @param tokenId The RFT to transfer858 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]859 fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {860 let caller = T::CrossAccountId::from_eth(caller);861 let to = T::CrossAccountId::from_eth(to);862 let token = token_id.try_into()?;863864 let balance = balance(self, token, &caller)?;865 ensure_single_owner(self, token, balance)?;866867 <Pallet<T>>::transfer(868 self,869 &caller,870 &to,871 token,872 balance,873 &nesting_budget(&self.recorder),874 )875 .map_err(dispatch_to_evm::<T>)?;876 Ok(())877 }878879 /// @notice Transfer ownership of an RFT880 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`881 /// is the zero address. Throws if `tokenId` is not a valid RFT.882 /// Throws if RFT pieces have multiple owners.883 /// @param to The new owner884 /// @param tokenId The RFT to transfer885 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]886 fn transfer_cross(887 &mut self,888 caller: Caller,889 to: eth::CrossAddress,890 token_id: U256,891 ) -> Result<()> {892 let caller = T::CrossAccountId::from_eth(caller);893 let to = to.into_sub_cross_account::<T>()?;894 let token = token_id.try_into()?;895896 let balance = balance(self, token, &caller)?;897 ensure_single_owner(self, token, balance)?;898899 <Pallet<T>>::transfer(900 self,901 &caller,902 &to,903 token,904 balance,905 &nesting_budget(&self.recorder),906 )907 .map_err(dispatch_to_evm::<T>)?;908 Ok(())909 }910911 /// @notice Transfer ownership of an RFT912 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`913 /// is the zero address. Throws if `tokenId` is not a valid RFT.914 /// Throws if RFT pieces have multiple owners.915 /// @param to The new owner916 /// @param tokenId The RFT to transfer917 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]918 fn transfer_from_cross(919 &mut self,920 caller: Caller,921 from: eth::CrossAddress,922 to: eth::CrossAddress,923 token_id: U256,924 ) -> Result<()> {925 let caller = T::CrossAccountId::from_eth(caller);926 let from = from.into_sub_cross_account::<T>()?;927 let to = to.into_sub_cross_account::<T>()?;928 let token_id = token_id.try_into()?;929930 let balance = balance(self, token_id, &from)?;931 ensure_single_owner(self, token_id, balance)?;932933 Pallet::<T>::transfer_from(934 self,935 &caller,936 &from,937 &to,938 token_id,939 balance,940 &nesting_budget(&self.recorder),941 )942 .map_err(dispatch_to_evm::<T>)?;943 Ok(())944 }945946 /// @notice Burns a specific ERC721 token.947 /// @dev Throws unless `msg.sender` is the current owner or an authorized948 /// operator for this RFT. Throws if `from` is not the current owner. Throws949 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.950 /// Throws if RFT pieces have multiple owners.951 /// @param from The current owner of the RFT952 /// @param tokenId The RFT to transfer953 #[solidity(hide)]954 #[weight(<SelfWeightOf<T>>::burn_from())]955 fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {956 let caller = T::CrossAccountId::from_eth(caller);957 let from = T::CrossAccountId::from_eth(from);958 let token = token_id.try_into()?;959960 let balance = balance(self, token, &from)?;961 ensure_single_owner(self, token, balance)?;962963 <Pallet<T>>::burn_from(964 self,965 &caller,966 &from,967 token,968 balance,969 &nesting_budget(&self.recorder),970 )971 .map_err(dispatch_to_evm::<T>)?;972 Ok(())973 }974975 /// @notice Burns a specific ERC721 token.976 /// @dev Throws unless `msg.sender` is the current owner or an authorized977 /// operator for this RFT. Throws if `from` is not the current owner. Throws978 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.979 /// Throws if RFT pieces have multiple owners.980 /// @param from The current owner of the RFT981 /// @param tokenId The RFT to transfer982 #[weight(<SelfWeightOf<T>>::burn_from())]983 fn burn_from_cross(984 &mut self,985 caller: Caller,986 from: eth::CrossAddress,987 token_id: U256,988 ) -> Result<()> {989 let caller = T::CrossAccountId::from_eth(caller);990 let from = from.into_sub_cross_account::<T>()?;991 let token = token_id.try_into()?;992993 let balance = balance(self, token, &from)?;994 ensure_single_owner(self, token, balance)?;995996 <Pallet<T>>::burn_from(997 self,998 &caller,999 &from,1000 token,1001 balance,1002 &nesting_budget(&self.recorder),1003 )1004 .map_err(dispatch_to_evm::<T>)?;1005 Ok(())1006 }10071008 /// @notice Returns next free RFT ID.1009 fn next_token_id(&self) -> Result<U256> {1010 self.consume_store_reads(1)?;1011 Ok(<Pallet<T>>::next_token_id(self)1012 .map_err(dispatch_to_evm::<T>)?1013 .into())1014 }10151016 /// @notice Function to mint multiple tokens.1017 /// @dev `tokenIds` should be an array of consecutive numbers and first number1018 /// should be obtained with `nextTokenId` method1019 /// @param to The new owner1020 /// @param tokenIds IDs of the minted RFTs1021 #[solidity(hide)]1022 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]1023 fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {1024 let caller = T::CrossAccountId::from_eth(caller);1025 let to = T::CrossAccountId::from_eth(to);1026 let mut expected_index = <TokensMinted<T>>::get(self.id)1027 .checked_add(1)1028 .ok_or("item id overflow")?;10291030 let total_tokens = token_ids.len();1031 for id in token_ids.into_iter() {1032 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1033 if id != expected_index {1034 return Err("item id should be next".into());1035 }1036 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;1037 }1038 let users = [(to, 1)]1039 .into_iter()1040 .collect::<BTreeMap<_, _>>()1041 .try_into()1042 .unwrap();1043 let create_item_data = CreateItemData::<T> {1044 users,1045 properties: CollectionPropertiesVec::default(),1046 };1047 let data = (0..total_tokens)1048 .map(|_| create_item_data.clone())1049 .collect();10501051 <Pallet<T>>::create_multiple_items(self, &caller, data, &nesting_budget(&self.recorder))1052 .map_err(dispatch_to_evm::<T>)?;1053 Ok(true)1054 }10551056 /// @notice Function to mint a token.1057 /// @param tokensData Data of minted token(s)1058 #[weight(if tokens_data.len() == 1 {1059 let token_data = tokens_data.first().unwrap();10601061 mint_with_props_weight::<T>(1062 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(token_data.owners.len() as u32),1063 [token_data.properties.len() as u32].into_iter(),1064 )1065 } else {1066 mint_with_props_weight::<T>(1067 <SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(tokens_data.len() as u32),1068 tokens_data.iter().map(|d| d.properties.len() as u32),1069 )1070 })]1071 fn mint_bulk_cross(&mut self, caller: Caller, tokens_data: Vec<MintTokenData>) -> Result<bool> {1072 let caller = T::CrossAccountId::from_eth(caller);1073 let has_multiple_tokens = tokens_data.len() > 1;10741075 let mut create_rft_data = Vec::with_capacity(tokens_data.len());1076 for MintTokenData { owners, properties } in tokens_data {1077 let has_multiple_owners = owners.len() > 1;1078 if has_multiple_tokens & has_multiple_owners {1079 return Err(1080 "creation of multiple tokens supported only if they have single owner each"1081 .into(),1082 );1083 }1084 let users: BoundedBTreeMap<_, _, _> = owners1085 .into_iter()1086 .map(|data| Ok((data.owner.into_sub_cross_account::<T>()?, data.pieces)))1087 .collect::<Result<BTreeMap<_, _>>>()?1088 .try_into()1089 .map_err(|_| "too many users")?;1090 create_rft_data.push(CreateItemData::<T> {1091 properties: properties1092 .into_iter()1093 .map(|property| property.try_into())1094 .collect::<Result<Vec<_>>>()?1095 .try_into()1096 .map_err(|_| "too many properties")?,1097 users,1098 });1099 }11001101 <Pallet<T>>::create_multiple_items(1102 self,1103 &caller,1104 create_rft_data,1105 &nesting_budget(&self.recorder),1106 )1107 .map_err(dispatch_to_evm::<T>)?;1108 Ok(true)1109 }11101111 /// @notice Function to mint multiple tokens with the given tokenUris.1112 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive1113 /// numbers and first number should be obtained with `nextTokenId` method1114 /// @param to The new owner1115 /// @param tokens array of pairs of token ID and token URI for minted tokens1116 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1117 #[weight(1118 mint_with_props_weight::<T>(1119 <SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32),1120 tokens.iter().map(|_| 1),1121 )1122 )]1123 fn mint_bulk_with_token_uri(1124 &mut self,1125 caller: Caller,1126 to: Address,1127 tokens: Vec<TokenUri>,1128 ) -> Result<bool> {1129 let key = key::url();1130 let caller = T::CrossAccountId::from_eth(caller);1131 let to = T::CrossAccountId::from_eth(to);1132 let mut expected_index = <TokensMinted<T>>::get(self.id)1133 .checked_add(1)1134 .ok_or("item id overflow")?;11351136 let mut data = Vec::with_capacity(tokens.len());1137 let users: BoundedBTreeMap<_, _, _> = [(to, 1)]1138 .into_iter()1139 .collect::<BTreeMap<_, _>>()1140 .try_into()1141 .unwrap();1142 for TokenUri { id, uri } in tokens {1143 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1144 if id != expected_index {1145 return Err("item id should be next".into());1146 }1147 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;11481149 let mut properties = CollectionPropertiesVec::default();1150 properties1151 .try_push(Property {1152 key: key.clone(),1153 value: uri1154 .into_bytes()1155 .try_into()1156 .map_err(|_| "token uri is too long")?,1157 })1158 .map_err(|e| Error::Revert(alloc::format!("can't add property: {e:?}")))?;11591160 let create_item_data = CreateItemData::<T> {1161 users: users.clone(),1162 properties,1163 };1164 data.push(create_item_data);1165 }11661167 <Pallet<T>>::create_multiple_items(self, &caller, data, &nesting_budget(&self.recorder))1168 .map_err(dispatch_to_evm::<T>)?;1169 Ok(true)1170 }11711172 /// @notice Function to mint a token.1173 /// @param to The new owner crossAccountId1174 /// @param properties Properties of minted token1175 /// @return uint256 The id of the newly minted token1176 #[weight(mint_with_props_weight::<T>(<SelfWeightOf<T>>::create_item(), [properties.len() as u32].into_iter()))]1177 fn mint_cross(1178 &mut self,1179 caller: Caller,1180 to: eth::CrossAddress,1181 properties: Vec<eth::Property>,1182 ) -> Result<U256> {1183 let token_id = <TokensMinted<T>>::get(self.id)1184 .checked_add(1)1185 .ok_or("item id overflow")?;11861187 let to = to.into_sub_cross_account::<T>()?;11881189 let properties = properties1190 .into_iter()1191 .map(eth::Property::try_into)1192 .collect::<Result<Vec<_>>>()?1193 .try_into()1194 .map_err(|_| Error::Revert("too many properties".to_string()))?;11951196 let caller = T::CrossAccountId::from_eth(caller);11971198 let users = [(to, 1)]1199 .into_iter()1200 .collect::<BTreeMap<_, _>>()1201 .try_into()1202 .unwrap();1203 <Pallet<T>>::create_item(1204 self,1205 &caller,1206 CreateItemData::<T> { users, properties },1207 &nesting_budget(&self.recorder),1208 )1209 .map_err(dispatch_to_evm::<T>)?;12101211 Ok(token_id.into())1212 }12131214 /// Returns EVM address for refungible token1215 ///1216 /// @param token ID of the token1217 fn token_contract_address(&self, token: U256) -> Result<Address> {1218 Ok(T::EvmTokenAddressMapping::token_to_address(1219 self.id,1220 token.try_into().map_err(|_| "token id overflow")?,1221 ))1222 }12231224 /// @notice Returns collection helper contract address1225 fn collection_helper_address(&self) -> Result<Address> {1226 Ok(T::ContractAddress::get())1227 }1228}12291230#[solidity_interface(1231 name = UniqueRefungible,1232 is(1233 ERC721,1234 ERC721Enumerable,1235 ERC721UniqueExtensions,1236 ERC721UniqueMintable,1237 ERC721Burnable,1238 ERC721Metadata(if(this.flags.erc721metadata)),1239 Collection(via(common_mut returns CollectionHandle<T>)),1240 TokenProperties,1241 ),1242 enum(derive(PreDispatch)),1243)]1244impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}12451246// Not a tests, but code generators1247generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1248generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);12491250impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1251where1252 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1253{1254 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1255 fn call(1256 self,1257 handle: &mut impl PrecompileHandle,1258 ) -> Option<pallet_common::erc::PrecompileResult> {1259 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1260 }1261}