difftreelog
fix After rebase
in: master
6 files changed
crates/evm-coder/src/solidity.rsdiffbeforeafterboth--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -479,7 +479,7 @@
}
}
-#[impl_for_tuples(0, 24)]
+#[impl_for_tuples(0, 48)]
impl SolidityFunctions for Tuple {
for_tuples!( where #( Tuple: SolidityFunctions ),* );
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -32,7 +32,7 @@
use crate::{
Pallet, CollectionHandle, Config, CollectionProperties,
- eth::convert_substrate_address_to_cross_account_id,
+ eth::{convert_cross_account_to_uint256, convert_uint256_to_cross_account},
};
/// Events for ethereum collection helper.
@@ -63,7 +63,7 @@
#[solidity_interface(name = Collection)]
impl<T: Config> CollectionHandle<T>
where
- T::AccountId: From<[u8; 32]> + AsRef<[u8]>,
+ T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
{
/// Set collection property.
///
@@ -177,7 +177,7 @@
SponsorshipState::Confirmed(ref sponsor) => sponsor,
};
let sponsor = T::CrossAccountId::from_sub(sponsor.clone());
- let sponsor_sub = convert_cross_account_to_uint256::<T>(&sponsor)?;
+ let sponsor_sub = convert_cross_account_to_uint256::<T>(&sponsor);
Ok((*sponsor.as_eth(), sponsor_sub))
}
@@ -274,7 +274,7 @@
new_admin: uint256,
) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let new_admin = convert_substrate_address_to_cross_account_id::<T>(new_admin);
+ let new_admin = convert_uint256_to_cross_account::<T>(new_admin);
<Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
@@ -287,7 +287,7 @@
admin: uint256,
) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let admin = convert_substrate_address_to_cross_account_id::<T>(admin);
+ let admin = convert_uint256_to_cross_account::<T>(admin);
<Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
@@ -461,7 +461,7 @@
/// @param user account to verify
/// @return "true" if account is the owner or admin
fn is_owner_or_admin_substrate(&self, user: uint256) -> Result<bool> {
- let user = convert_substrate_address_to_cross_account_id::<T>(user);
+ let user = convert_uint256_to_cross_account::<T>(user);
Ok(self.is_owner_or_admin(&user))
}
@@ -494,7 +494,7 @@
/// @param newOwner new owner substrate account
fn set_owner_substrate(&mut self, caller: caller, new_owner: uint256) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
- let new_owner = convert_substrate_address_to_cross_account_id::<T>(new_owner);
+ let new_owner = convert_uint256_to_cross_account::<T>(new_owner);
self.set_owner_internal(caller, new_owner)
.map_err(dispatch_to_evm::<T>)
}
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -154,14 +154,14 @@
Collection(common_mut, CollectionHandle<T>),
)
)]
-impl<T: Config> FungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8]> {}
+impl<T: Config> FungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}
generate_stubgen!(gen_impl, UniqueFungibleCall<()>, true);
generate_stubgen!(gen_iface, UniqueFungibleCall<()>, false);
impl<T: Config> CommonEvmHandler for FungibleHandle<T>
where
- T::AccountId: From<[u8; 32]> + AsRef<[u8]>,
+ T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
{
const CODE: &'static [u8] = include_bytes!("./stubs/UniqueFungible.raw");
pallets/nonfungible/src/erc.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;23use core::{24 char::{REPLACEMENT_CHARACTER, decode_utf16},25 convert::TryInto,26};27use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};28use frame_support::BoundedVec;29use up_data_structs::{30 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,31 CollectionPropertiesVec,32};33use pallet_evm_coder_substrate::dispatch_to_evm;34use sp_std::vec::Vec;35use pallet_common::{36 erc::{37 CommonEvmHandler, PrecompileResult, CollectionCall,38 static_property::{key, value as property_value},39 },40 CollectionHandle, CollectionPropertyPermissions,41};42use pallet_evm::{account::CrossAccountId, PrecompileHandle};43use pallet_evm_coder_substrate::call;44use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};45use alloc::string::ToString;4647use crate::{48 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,49 SelfWeightOf, weights::WeightInfo, TokenProperties,50};5152/// @title A contract that allows to set and delete token properties and change token property permissions.53#[solidity_interface(name = TokenProperties)]54impl<T: Config> NonfungibleHandle<T> {55 /// @notice Set permissions for token property.56 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.57 /// @param key Property key.58 /// @param isMutable Permission to mutate property.59 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.60 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.61 fn set_token_property_permission(62 &mut self,63 caller: caller,64 key: string,65 is_mutable: bool,66 collection_admin: bool,67 token_owner: bool,68 ) -> Result<()> {69 let caller = T::CrossAccountId::from_eth(caller);70 <Pallet<T>>::set_property_permission(71 self,72 &caller,73 PropertyKeyPermission {74 key: <Vec<u8>>::from(key)75 .try_into()76 .map_err(|_| "too long key")?,77 permission: PropertyPermission {78 mutable: is_mutable,79 collection_admin,80 token_owner,81 },82 },83 )84 .map_err(dispatch_to_evm::<T>)85 }8687 /// @notice Set token property value.88 /// @dev Throws error if `msg.sender` has no permission to edit the property.89 /// @param tokenId ID of the token.90 /// @param key Property key.91 /// @param value Property value.92 fn set_property(93 &mut self,94 caller: caller,95 token_id: uint256,96 key: string,97 value: bytes,98 ) -> Result<()> {99 let caller = T::CrossAccountId::from_eth(caller);100 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;101 let key = <Vec<u8>>::from(key)102 .try_into()103 .map_err(|_| "key too long")?;104 let value = value.try_into().map_err(|_| "value too long")?;105106 let nesting_budget = self107 .recorder108 .weight_calls_budget(<StructureWeight<T>>::find_parent());109110 <Pallet<T>>::set_token_property(111 self,112 &caller,113 TokenId(token_id),114 Property { key, value },115 &nesting_budget,116 )117 .map_err(dispatch_to_evm::<T>)118 }119120 /// @notice Delete token property value.121 /// @dev Throws error if `msg.sender` has no permission to edit the property.122 /// @param tokenId ID of the token.123 /// @param key Property key.124 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {125 let caller = T::CrossAccountId::from_eth(caller);126 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;127 let key = <Vec<u8>>::from(key)128 .try_into()129 .map_err(|_| "key too long")?;130131 let nesting_budget = self132 .recorder133 .weight_calls_budget(<StructureWeight<T>>::find_parent());134135 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)136 .map_err(dispatch_to_evm::<T>)137 }138139 /// @notice Get token property value.140 /// @dev Throws error if key not found141 /// @param tokenId ID of the token.142 /// @param key Property key.143 /// @return Property value bytes144 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {145 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;146 let key = <Vec<u8>>::from(key)147 .try_into()148 .map_err(|_| "key too long")?;149150 let props = <TokenProperties<T>>::get((self.id, token_id));151 let prop = props.get(&key).ok_or("key not found")?;152153 Ok(prop.to_vec())154 }155}156157#[derive(ToLog)]158pub enum ERC721Events {159 /// @dev This emits when ownership of any NFT changes by any mechanism.160 /// This event emits when NFTs are created (`from` == 0) and destroyed161 /// (`to` == 0). Exception: during contract creation, any number of NFTs162 /// may be created and assigned without emitting Transfer. At the time of163 /// any transfer, the approved address for that NFT (if any) is reset to none.164 Transfer {165 #[indexed]166 from: address,167 #[indexed]168 to: address,169 #[indexed]170 token_id: uint256,171 },172 /// @dev This emits when the approved address for an NFT is changed or173 /// reaffirmed. The zero address indicates there is no approved address.174 /// When a Transfer event emits, this also indicates that the approved175 /// address for that NFT (if any) is reset to none.176 Approval {177 #[indexed]178 owner: address,179 #[indexed]180 approved: address,181 #[indexed]182 token_id: uint256,183 },184 /// @dev This emits when an operator is enabled or disabled for an owner.185 /// The operator can manage all NFTs of the owner.186 #[allow(dead_code)]187 ApprovalForAll {188 #[indexed]189 owner: address,190 #[indexed]191 operator: address,192 approved: bool,193 },194}195196#[derive(ToLog)]197pub enum ERC721MintableEvents {198 #[allow(dead_code)]199 MintingFinished {},200}201202/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension203/// @dev See https://eips.ethereum.org/EIPS/eip-721204#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]205impl<T: Config> NonfungibleHandle<T> {206 /// @notice A descriptive name for a collection of NFTs in this contract207 fn name(&self) -> Result<string> {208 Ok(decode_utf16(self.name.iter().copied())209 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))210 .collect::<string>())211 }212213 /// @notice An abbreviated name for NFTs in this contract214 fn symbol(&self) -> Result<string> {215 Ok(string::from_utf8_lossy(&self.token_prefix).into())216 }217218 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.219 ///220 /// @dev If the token has a `url` property and it is not empty, it is returned.221 /// 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`.222 /// If the collection property `baseURI` is empty or absent, return "" (empty string)223 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix224 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).225 ///226 /// @return token's const_metadata227 #[solidity(rename_selector = "tokenURI")]228 fn token_uri(&self, token_id: uint256) -> Result<string> {229 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;230231 if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {232 if !url.is_empty() {233 return Ok(url);234 }235 } else if !is_erc721_metadata_compatible::<T>(self.id) {236 return Err("tokenURI not set".into());237 }238239 if let Some(base_uri) =240 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())241 {242 if !base_uri.is_empty() {243 let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {244 Error::Revert(alloc::format!(245 "Can not convert value \"baseURI\" to string with error \"{}\"",246 e247 ))248 })?;249 if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {250 if !suffix.is_empty() {251 return Ok(base_uri + suffix.as_str());252 }253 }254255 return Ok(base_uri + token_id.to_string().as_str());256 }257 }258259 Ok("".into())260 }261}262263/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension264/// @dev See https://eips.ethereum.org/EIPS/eip-721265#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]266impl<T: Config> NonfungibleHandle<T> {267 /// @notice Enumerate valid NFTs268 /// @param index A counter less than `totalSupply()`269 /// @return The token identifier for the `index`th NFT,270 /// (sort order not specified)271 fn token_by_index(&self, index: uint256) -> Result<uint256> {272 Ok(index)273 }274275 /// @dev Not implemented276 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {277 // TODO: Not implemetable278 Err("not implemented".into())279 }280281 /// @notice Count NFTs tracked by this contract282 /// @return A count of valid NFTs tracked by this contract, where each one of283 /// them has an assigned and queryable owner not equal to the zero address284 fn total_supply(&self) -> Result<uint256> {285 self.consume_store_reads(1)?;286 Ok(<Pallet<T>>::total_supply(self).into())287 }288}289290/// @title ERC-721 Non-Fungible Token Standard291/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md292#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]293impl<T: Config> NonfungibleHandle<T> {294 /// @notice Count all NFTs assigned to an owner295 /// @dev NFTs assigned to the zero address are considered invalid, and this296 /// function throws for queries about the zero address.297 /// @param owner An address for whom to query the balance298 /// @return The number of NFTs owned by `owner`, possibly zero299 fn balance_of(&self, owner: address) -> Result<uint256> {300 self.consume_store_reads(1)?;301 let owner = T::CrossAccountId::from_eth(owner);302 let balance = <AccountBalance<T>>::get((self.id, owner));303 Ok(balance.into())304 }305 /// @notice Find the owner of an NFT306 /// @dev NFTs assigned to zero address are considered invalid, and queries307 /// about them do throw.308 /// @param tokenId The identifier for an NFT309 /// @return The address of the owner of the NFT310 fn owner_of(&self, token_id: uint256) -> Result<address> {311 self.consume_store_reads(1)?;312 let token: TokenId = token_id.try_into()?;313 Ok(*<TokenData<T>>::get((self.id, token))314 .ok_or("token not found")?315 .owner316 .as_eth())317 }318 /// @dev Not implemented319 #[solidity(rename_selector = "safeTransferFrom")]320 fn safe_transfer_from_with_data(321 &mut self,322 _from: address,323 _to: address,324 _token_id: uint256,325 _data: bytes,326 ) -> Result<void> {327 // TODO: Not implemetable328 Err("not implemented".into())329 }330 /// @dev Not implemented331 fn safe_transfer_from(332 &mut self,333 _from: address,334 _to: address,335 _token_id: uint256,336 ) -> Result<void> {337 // TODO: Not implemetable338 Err("not implemented".into())339 }340341 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE342 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE343 /// THEY MAY BE PERMANENTLY LOST344 /// @dev Throws unless `msg.sender` is the current owner or an authorized345 /// operator for this NFT. Throws if `from` is not the current owner. Throws346 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.347 /// @param from The current owner of the NFT348 /// @param to The new owner349 /// @param tokenId The NFT to transfer350 #[weight(<SelfWeightOf<T>>::transfer_from())]351 fn transfer_from(352 &mut self,353 caller: caller,354 from: address,355 to: address,356 token_id: uint256,357 ) -> Result<void> {358 let caller = T::CrossAccountId::from_eth(caller);359 let from = T::CrossAccountId::from_eth(from);360 let to = T::CrossAccountId::from_eth(to);361 let token = token_id.try_into()?;362 let budget = self363 .recorder364 .weight_calls_budget(<StructureWeight<T>>::find_parent());365366 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)367 .map_err(dispatch_to_evm::<T>)?;368 Ok(())369 }370371 /// @notice Set or reaffirm the approved address for an NFT372 /// @dev The zero address indicates there is no approved address.373 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized374 /// operator of the current owner.375 /// @param approved The new approved NFT controller376 /// @param tokenId The NFT to approve377 #[weight(<SelfWeightOf<T>>::approve())]378 fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {379 let caller = T::CrossAccountId::from_eth(caller);380 let approved = T::CrossAccountId::from_eth(approved);381 let token = token_id.try_into()?;382383 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))384 .map_err(dispatch_to_evm::<T>)?;385 Ok(())386 }387388 /// @dev Not implemented389 fn set_approval_for_all(390 &mut self,391 _caller: caller,392 _operator: address,393 _approved: bool,394 ) -> Result<void> {395 // TODO: Not implemetable396 Err("not implemented".into())397 }398399 /// @dev Not implemented400 fn get_approved(&self, _token_id: uint256) -> Result<address> {401 // TODO: Not implemetable402 Err("not implemented".into())403 }404405 /// @dev Not implemented406 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {407 // TODO: Not implemetable408 Err("not implemented".into())409 }410}411412/// @title ERC721 Token that can be irreversibly burned (destroyed).413#[solidity_interface(name = ERC721Burnable)]414impl<T: Config> NonfungibleHandle<T> {415 /// @notice Burns a specific ERC721 token.416 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized417 /// operator of the current owner.418 /// @param tokenId The NFT to approve419 #[weight(<SelfWeightOf<T>>::burn_item())]420 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {421 let caller = T::CrossAccountId::from_eth(caller);422 let token = token_id.try_into()?;423424 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;425 Ok(())426 }427}428429/// @title ERC721 minting logic.430#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]431impl<T: Config> NonfungibleHandle<T> {432 fn minting_finished(&self) -> Result<bool> {433 Ok(false)434 }435436 /// @notice Function to mint token.437 /// @dev `tokenId` should be obtained with `nextTokenId` method,438 /// unlike standard, you can't specify it manually439 /// @param to The new owner440 /// @param tokenId ID of the minted NFT441 #[weight(<SelfWeightOf<T>>::create_item())]442 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {443 let caller = T::CrossAccountId::from_eth(caller);444 let to = T::CrossAccountId::from_eth(to);445 let token_id: u32 = token_id.try_into()?;446 let budget = self447 .recorder448 .weight_calls_budget(<StructureWeight<T>>::find_parent());449450 if <TokensMinted<T>>::get(self.id)451 .checked_add(1)452 .ok_or("item id overflow")?453 != token_id454 {455 return Err("item id should be next".into());456 }457458 <Pallet<T>>::create_item(459 self,460 &caller,461 CreateItemData::<T> {462 properties: BoundedVec::default(),463 owner: to,464 },465 &budget,466 )467 .map_err(dispatch_to_evm::<T>)?;468469 Ok(true)470 }471472 /// @notice Function to mint token with the given tokenUri.473 /// @dev `tokenId` should be obtained with `nextTokenId` method,474 /// unlike standard, you can't specify it manually475 /// @param to The new owner476 /// @param tokenId ID of the minted NFT477 /// @param tokenUri Token URI that would be stored in the NFT properties478 #[solidity(rename_selector = "mintWithTokenURI")]479 #[weight(<SelfWeightOf<T>>::create_item())]480 fn mint_with_token_uri(481 &mut self,482 caller: caller,483 to: address,484 token_id: uint256,485 token_uri: string,486 ) -> Result<bool> {487 let key = key::url();488 let permission = get_token_permission::<T>(self.id, &key)?;489 if !permission.collection_admin {490 return Err("Operation is not allowed".into());491 }492493 let caller = T::CrossAccountId::from_eth(caller);494 let to = T::CrossAccountId::from_eth(to);495 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;496 let budget = self497 .recorder498 .weight_calls_budget(<StructureWeight<T>>::find_parent());499500 if <TokensMinted<T>>::get(self.id)501 .checked_add(1)502 .ok_or("item id overflow")?503 != token_id504 {505 return Err("item id should be next".into());506 }507508 let mut properties = CollectionPropertiesVec::default();509 properties510 .try_push(Property {511 key,512 value: token_uri513 .into_bytes()514 .try_into()515 .map_err(|_| "token uri is too long")?,516 })517 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;518519 <Pallet<T>>::create_item(520 self,521 &caller,522 CreateItemData::<T> {523 properties,524 owner: to,525 },526 &budget,527 )528 .map_err(dispatch_to_evm::<T>)?;529 Ok(true)530 }531532 /// @dev Not implemented533 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {534 Err("not implementable".into())535 }536}537538fn get_token_property<T: Config>(539 collection: &CollectionHandle<T>,540 token_id: u32,541 key: &up_data_structs::PropertyKey,542) -> Result<string> {543 collection.consume_store_reads(1)?;544 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))545 .map_err(|_| Error::Revert("Token properties not found".into()))?;546 if let Some(property) = properties.get(key) {547 return Ok(string::from_utf8_lossy(property).into());548 }549550 Err("Property tokenURI not found".into())551}552553fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {554 if let Some(shema_name) =555 pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())556 {557 let shema_name = shema_name.into_inner();558 shema_name == property_value::ERC721_METADATA559 } else {560 false561 }562}563564fn get_token_permission<T: Config>(565 collection_id: CollectionId,566 key: &PropertyKey,567) -> Result<PropertyPermission> {568 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)569 .map_err(|_| Error::Revert("No permissions for collection".into()))?;570 let a = token_property_permissions571 .get(key)572 .map(Clone::clone)573 .ok_or_else(|| {574 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();575 Error::Revert(alloc::format!("No permission for key {}", key))576 })?;577 Ok(a)578}579580fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {581 if let Ok(token_property_permissions) =582 CollectionPropertyPermissions::<T>::try_get(collection_id)583 {584 return token_property_permissions.contains_key(key);585 }586587 false588}589590/// @title Unique extensions for ERC721.591#[solidity_interface(name = ERC721UniqueExtensions)]592impl<T: Config> NonfungibleHandle<T> {593 /// @notice Transfer ownership of an NFT594 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`595 /// is the zero address. Throws if `tokenId` is not a valid NFT.596 /// @param to The new owner597 /// @param tokenId The NFT to transfer598 #[weight(<SelfWeightOf<T>>::transfer())]599 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {600 let caller = T::CrossAccountId::from_eth(caller);601 let to = T::CrossAccountId::from_eth(to);602 let token = token_id.try_into()?;603 let budget = self604 .recorder605 .weight_calls_budget(<StructureWeight<T>>::find_parent());606607 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;608 Ok(())609 }610611 /// @notice Burns a specific ERC721 token.612 /// @dev Throws unless `msg.sender` is the current owner or an authorized613 /// operator for this NFT. Throws if `from` is not the current owner. Throws614 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.615 /// @param from The current owner of the NFT616 /// @param tokenId The NFT to transfer617 #[weight(<SelfWeightOf<T>>::burn_from())]618 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {619 let caller = T::CrossAccountId::from_eth(caller);620 let from = T::CrossAccountId::from_eth(from);621 let token = token_id.try_into()?;622 let budget = self623 .recorder624 .weight_calls_budget(<StructureWeight<T>>::find_parent());625626 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)627 .map_err(dispatch_to_evm::<T>)?;628 Ok(())629 }630631 /// @notice Returns next free NFT ID.632 fn next_token_id(&self) -> Result<uint256> {633 self.consume_store_reads(1)?;634 Ok(<TokensMinted<T>>::get(self.id)635 .checked_add(1)636 .ok_or("item id overflow")?637 .into())638 }639640 /// @notice Function to mint multiple tokens.641 /// @dev `tokenIds` should be an array of consecutive numbers and first number642 /// should be obtained with `nextTokenId` method643 /// @param to The new owner644 /// @param tokenIds IDs of the minted NFTs645 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]646 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {647 let caller = T::CrossAccountId::from_eth(caller);648 let to = T::CrossAccountId::from_eth(to);649 let mut expected_index = <TokensMinted<T>>::get(self.id)650 .checked_add(1)651 .ok_or("item id overflow")?;652 let budget = self653 .recorder654 .weight_calls_budget(<StructureWeight<T>>::find_parent());655656 let total_tokens = token_ids.len();657 for id in token_ids.into_iter() {658 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;659 if id != expected_index {660 return Err("item id should be next".into());661 }662 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;663 }664 let data = (0..total_tokens)665 .map(|_| CreateItemData::<T> {666 properties: BoundedVec::default(),667 owner: to.clone(),668 })669 .collect();670671 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)672 .map_err(dispatch_to_evm::<T>)?;673 Ok(true)674 }675676 /// @notice Function to mint multiple tokens with the given tokenUris.677 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive678 /// numbers and first number should be obtained with `nextTokenId` method679 /// @param to The new owner680 /// @param tokens array of pairs of token ID and token URI for minted tokens681 #[solidity(rename_selector = "mintBulkWithTokenURI")]682 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]683 fn mint_bulk_with_token_uri(684 &mut self,685 caller: caller,686 to: address,687 tokens: Vec<(uint256, string)>,688 ) -> Result<bool> {689 let key = key::url();690 let caller = T::CrossAccountId::from_eth(caller);691 let to = T::CrossAccountId::from_eth(to);692 let mut expected_index = <TokensMinted<T>>::get(self.id)693 .checked_add(1)694 .ok_or("item id overflow")?;695 let budget = self696 .recorder697 .weight_calls_budget(<StructureWeight<T>>::find_parent());698699 let mut data = Vec::with_capacity(tokens.len());700 for (id, token_uri) in tokens {701 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;702 if id != expected_index {703 return Err("item id should be next".into());704 }705 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;706707 let mut properties = CollectionPropertiesVec::default();708 properties709 .try_push(Property {710 key: key.clone(),711 value: token_uri712 .into_bytes()713 .try_into()714 .map_err(|_| "token uri is too long")?,715 })716 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;717718 data.push(CreateItemData::<T> {719 properties,720 owner: to.clone(),721 });722 }723724 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)725 .map_err(dispatch_to_evm::<T>)?;726 Ok(true)727 }728}729730#[solidity_interface(731 name = UniqueNFT,732 is(733 ERC721,734 ERC721Metadata,735 ERC721Enumerable,736 ERC721UniqueExtensions,737 ERC721Mintable,738 ERC721Burnable,739 Collection(common_mut, CollectionHandle<T>),740 TokenProperties,741 )742)]743impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8]> {}744745// Not a tests, but code generators746generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);747generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);748749impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>750where751 T::AccountId: From<[u8; 32]> + AsRef<[u8]>,752{753 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");754755 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {756 call::<T, UniqueNFTCall<T>, _, _>(handle, self)757 }758}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;23use core::{24 char::{REPLACEMENT_CHARACTER, decode_utf16},25 convert::TryInto,26};27use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};28use frame_support::BoundedVec;29use up_data_structs::{30 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,31 CollectionPropertiesVec,32};33use pallet_evm_coder_substrate::dispatch_to_evm;34use sp_std::vec::Vec;35use pallet_common::{36 erc::{37 CommonEvmHandler, PrecompileResult, CollectionCall,38 static_property::{key, value as property_value},39 },40 CollectionHandle, CollectionPropertyPermissions,41};42use pallet_evm::{account::CrossAccountId, PrecompileHandle};43use pallet_evm_coder_substrate::call;44use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};45use alloc::string::ToString;4647use crate::{48 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,49 SelfWeightOf, weights::WeightInfo, TokenProperties,50};5152/// @title A contract that allows to set and delete token properties and change token property permissions.53#[solidity_interface(name = TokenProperties)]54impl<T: Config> NonfungibleHandle<T> {55 /// @notice Set permissions for token property.56 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.57 /// @param key Property key.58 /// @param isMutable Permission to mutate property.59 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.60 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.61 fn set_token_property_permission(62 &mut self,63 caller: caller,64 key: string,65 is_mutable: bool,66 collection_admin: bool,67 token_owner: bool,68 ) -> Result<()> {69 let caller = T::CrossAccountId::from_eth(caller);70 <Pallet<T>>::set_property_permission(71 self,72 &caller,73 PropertyKeyPermission {74 key: <Vec<u8>>::from(key)75 .try_into()76 .map_err(|_| "too long key")?,77 permission: PropertyPermission {78 mutable: is_mutable,79 collection_admin,80 token_owner,81 },82 },83 )84 .map_err(dispatch_to_evm::<T>)85 }8687 /// @notice Set token property value.88 /// @dev Throws error if `msg.sender` has no permission to edit the property.89 /// @param tokenId ID of the token.90 /// @param key Property key.91 /// @param value Property value.92 fn set_property(93 &mut self,94 caller: caller,95 token_id: uint256,96 key: string,97 value: bytes,98 ) -> Result<()> {99 let caller = T::CrossAccountId::from_eth(caller);100 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;101 let key = <Vec<u8>>::from(key)102 .try_into()103 .map_err(|_| "key too long")?;104 let value = value.try_into().map_err(|_| "value too long")?;105106 let nesting_budget = self107 .recorder108 .weight_calls_budget(<StructureWeight<T>>::find_parent());109110 <Pallet<T>>::set_token_property(111 self,112 &caller,113 TokenId(token_id),114 Property { key, value },115 &nesting_budget,116 )117 .map_err(dispatch_to_evm::<T>)118 }119120 /// @notice Delete token property value.121 /// @dev Throws error if `msg.sender` has no permission to edit the property.122 /// @param tokenId ID of the token.123 /// @param key Property key.124 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {125 let caller = T::CrossAccountId::from_eth(caller);126 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;127 let key = <Vec<u8>>::from(key)128 .try_into()129 .map_err(|_| "key too long")?;130131 let nesting_budget = self132 .recorder133 .weight_calls_budget(<StructureWeight<T>>::find_parent());134135 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)136 .map_err(dispatch_to_evm::<T>)137 }138139 /// @notice Get token property value.140 /// @dev Throws error if key not found141 /// @param tokenId ID of the token.142 /// @param key Property key.143 /// @return Property value bytes144 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {145 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;146 let key = <Vec<u8>>::from(key)147 .try_into()148 .map_err(|_| "key too long")?;149150 let props = <TokenProperties<T>>::get((self.id, token_id));151 let prop = props.get(&key).ok_or("key not found")?;152153 Ok(prop.to_vec())154 }155}156157#[derive(ToLog)]158pub enum ERC721Events {159 /// @dev This emits when ownership of any NFT changes by any mechanism.160 /// This event emits when NFTs are created (`from` == 0) and destroyed161 /// (`to` == 0). Exception: during contract creation, any number of NFTs162 /// may be created and assigned without emitting Transfer. At the time of163 /// any transfer, the approved address for that NFT (if any) is reset to none.164 Transfer {165 #[indexed]166 from: address,167 #[indexed]168 to: address,169 #[indexed]170 token_id: uint256,171 },172 /// @dev This emits when the approved address for an NFT is changed or173 /// reaffirmed. The zero address indicates there is no approved address.174 /// When a Transfer event emits, this also indicates that the approved175 /// address for that NFT (if any) is reset to none.176 Approval {177 #[indexed]178 owner: address,179 #[indexed]180 approved: address,181 #[indexed]182 token_id: uint256,183 },184 /// @dev This emits when an operator is enabled or disabled for an owner.185 /// The operator can manage all NFTs of the owner.186 #[allow(dead_code)]187 ApprovalForAll {188 #[indexed]189 owner: address,190 #[indexed]191 operator: address,192 approved: bool,193 },194}195196#[derive(ToLog)]197pub enum ERC721MintableEvents {198 #[allow(dead_code)]199 MintingFinished {},200}201202/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension203/// @dev See https://eips.ethereum.org/EIPS/eip-721204#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]205impl<T: Config> NonfungibleHandle<T> {206 /// @notice A descriptive name for a collection of NFTs in this contract207 fn name(&self) -> Result<string> {208 Ok(decode_utf16(self.name.iter().copied())209 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))210 .collect::<string>())211 }212213 /// @notice An abbreviated name for NFTs in this contract214 fn symbol(&self) -> Result<string> {215 Ok(string::from_utf8_lossy(&self.token_prefix).into())216 }217218 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.219 ///220 /// @dev If the token has a `url` property and it is not empty, it is returned.221 /// 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`.222 /// If the collection property `baseURI` is empty or absent, return "" (empty string)223 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix224 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).225 ///226 /// @return token's const_metadata227 #[solidity(rename_selector = "tokenURI")]228 fn token_uri(&self, token_id: uint256) -> Result<string> {229 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;230231 if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {232 if !url.is_empty() {233 return Ok(url);234 }235 } else if !is_erc721_metadata_compatible::<T>(self.id) {236 return Err("tokenURI not set".into());237 }238239 if let Some(base_uri) =240 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())241 {242 if !base_uri.is_empty() {243 let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {244 Error::Revert(alloc::format!(245 "Can not convert value \"baseURI\" to string with error \"{}\"",246 e247 ))248 })?;249 if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {250 if !suffix.is_empty() {251 return Ok(base_uri + suffix.as_str());252 }253 }254255 return Ok(base_uri + token_id.to_string().as_str());256 }257 }258259 Ok("".into())260 }261}262263/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension264/// @dev See https://eips.ethereum.org/EIPS/eip-721265#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]266impl<T: Config> NonfungibleHandle<T> {267 /// @notice Enumerate valid NFTs268 /// @param index A counter less than `totalSupply()`269 /// @return The token identifier for the `index`th NFT,270 /// (sort order not specified)271 fn token_by_index(&self, index: uint256) -> Result<uint256> {272 Ok(index)273 }274275 /// @dev Not implemented276 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {277 // TODO: Not implemetable278 Err("not implemented".into())279 }280281 /// @notice Count NFTs tracked by this contract282 /// @return A count of valid NFTs tracked by this contract, where each one of283 /// them has an assigned and queryable owner not equal to the zero address284 fn total_supply(&self) -> Result<uint256> {285 self.consume_store_reads(1)?;286 Ok(<Pallet<T>>::total_supply(self).into())287 }288}289290/// @title ERC-721 Non-Fungible Token Standard291/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md292#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]293impl<T: Config> NonfungibleHandle<T> {294 /// @notice Count all NFTs assigned to an owner295 /// @dev NFTs assigned to the zero address are considered invalid, and this296 /// function throws for queries about the zero address.297 /// @param owner An address for whom to query the balance298 /// @return The number of NFTs owned by `owner`, possibly zero299 fn balance_of(&self, owner: address) -> Result<uint256> {300 self.consume_store_reads(1)?;301 let owner = T::CrossAccountId::from_eth(owner);302 let balance = <AccountBalance<T>>::get((self.id, owner));303 Ok(balance.into())304 }305 /// @notice Find the owner of an NFT306 /// @dev NFTs assigned to zero address are considered invalid, and queries307 /// about them do throw.308 /// @param tokenId The identifier for an NFT309 /// @return The address of the owner of the NFT310 fn owner_of(&self, token_id: uint256) -> Result<address> {311 self.consume_store_reads(1)?;312 let token: TokenId = token_id.try_into()?;313 Ok(*<TokenData<T>>::get((self.id, token))314 .ok_or("token not found")?315 .owner316 .as_eth())317 }318 /// @dev Not implemented319 #[solidity(rename_selector = "safeTransferFrom")]320 fn safe_transfer_from_with_data(321 &mut self,322 _from: address,323 _to: address,324 _token_id: uint256,325 _data: bytes,326 ) -> Result<void> {327 // TODO: Not implemetable328 Err("not implemented".into())329 }330 /// @dev Not implemented331 fn safe_transfer_from(332 &mut self,333 _from: address,334 _to: address,335 _token_id: uint256,336 ) -> Result<void> {337 // TODO: Not implemetable338 Err("not implemented".into())339 }340341 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE342 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE343 /// THEY MAY BE PERMANENTLY LOST344 /// @dev Throws unless `msg.sender` is the current owner or an authorized345 /// operator for this NFT. Throws if `from` is not the current owner. Throws346 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.347 /// @param from The current owner of the NFT348 /// @param to The new owner349 /// @param tokenId The NFT to transfer350 #[weight(<SelfWeightOf<T>>::transfer_from())]351 fn transfer_from(352 &mut self,353 caller: caller,354 from: address,355 to: address,356 token_id: uint256,357 ) -> Result<void> {358 let caller = T::CrossAccountId::from_eth(caller);359 let from = T::CrossAccountId::from_eth(from);360 let to = T::CrossAccountId::from_eth(to);361 let token = token_id.try_into()?;362 let budget = self363 .recorder364 .weight_calls_budget(<StructureWeight<T>>::find_parent());365366 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)367 .map_err(dispatch_to_evm::<T>)?;368 Ok(())369 }370371 /// @notice Set or reaffirm the approved address for an NFT372 /// @dev The zero address indicates there is no approved address.373 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized374 /// operator of the current owner.375 /// @param approved The new approved NFT controller376 /// @param tokenId The NFT to approve377 #[weight(<SelfWeightOf<T>>::approve())]378 fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {379 let caller = T::CrossAccountId::from_eth(caller);380 let approved = T::CrossAccountId::from_eth(approved);381 let token = token_id.try_into()?;382383 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))384 .map_err(dispatch_to_evm::<T>)?;385 Ok(())386 }387388 /// @dev Not implemented389 fn set_approval_for_all(390 &mut self,391 _caller: caller,392 _operator: address,393 _approved: bool,394 ) -> Result<void> {395 // TODO: Not implemetable396 Err("not implemented".into())397 }398399 /// @dev Not implemented400 fn get_approved(&self, _token_id: uint256) -> Result<address> {401 // TODO: Not implemetable402 Err("not implemented".into())403 }404405 /// @dev Not implemented406 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {407 // TODO: Not implemetable408 Err("not implemented".into())409 }410}411412/// @title ERC721 Token that can be irreversibly burned (destroyed).413#[solidity_interface(name = ERC721Burnable)]414impl<T: Config> NonfungibleHandle<T> {415 /// @notice Burns a specific ERC721 token.416 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized417 /// operator of the current owner.418 /// @param tokenId The NFT to approve419 #[weight(<SelfWeightOf<T>>::burn_item())]420 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {421 let caller = T::CrossAccountId::from_eth(caller);422 let token = token_id.try_into()?;423424 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;425 Ok(())426 }427}428429/// @title ERC721 minting logic.430#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]431impl<T: Config> NonfungibleHandle<T> {432 fn minting_finished(&self) -> Result<bool> {433 Ok(false)434 }435436 /// @notice Function to mint token.437 /// @dev `tokenId` should be obtained with `nextTokenId` method,438 /// unlike standard, you can't specify it manually439 /// @param to The new owner440 /// @param tokenId ID of the minted NFT441 #[weight(<SelfWeightOf<T>>::create_item())]442 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {443 let caller = T::CrossAccountId::from_eth(caller);444 let to = T::CrossAccountId::from_eth(to);445 let token_id: u32 = token_id.try_into()?;446 let budget = self447 .recorder448 .weight_calls_budget(<StructureWeight<T>>::find_parent());449450 if <TokensMinted<T>>::get(self.id)451 .checked_add(1)452 .ok_or("item id overflow")?453 != token_id454 {455 return Err("item id should be next".into());456 }457458 <Pallet<T>>::create_item(459 self,460 &caller,461 CreateItemData::<T> {462 properties: BoundedVec::default(),463 owner: to,464 },465 &budget,466 )467 .map_err(dispatch_to_evm::<T>)?;468469 Ok(true)470 }471472 /// @notice Function to mint token with the given tokenUri.473 /// @dev `tokenId` should be obtained with `nextTokenId` method,474 /// unlike standard, you can't specify it manually475 /// @param to The new owner476 /// @param tokenId ID of the minted NFT477 /// @param tokenUri Token URI that would be stored in the NFT properties478 #[solidity(rename_selector = "mintWithTokenURI")]479 #[weight(<SelfWeightOf<T>>::create_item())]480 fn mint_with_token_uri(481 &mut self,482 caller: caller,483 to: address,484 token_id: uint256,485 token_uri: string,486 ) -> Result<bool> {487 let key = key::url();488 let permission = get_token_permission::<T>(self.id, &key)?;489 if !permission.collection_admin {490 return Err("Operation is not allowed".into());491 }492493 let caller = T::CrossAccountId::from_eth(caller);494 let to = T::CrossAccountId::from_eth(to);495 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;496 let budget = self497 .recorder498 .weight_calls_budget(<StructureWeight<T>>::find_parent());499500 if <TokensMinted<T>>::get(self.id)501 .checked_add(1)502 .ok_or("item id overflow")?503 != token_id504 {505 return Err("item id should be next".into());506 }507508 let mut properties = CollectionPropertiesVec::default();509 properties510 .try_push(Property {511 key,512 value: token_uri513 .into_bytes()514 .try_into()515 .map_err(|_| "token uri is too long")?,516 })517 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;518519 <Pallet<T>>::create_item(520 self,521 &caller,522 CreateItemData::<T> {523 properties,524 owner: to,525 },526 &budget,527 )528 .map_err(dispatch_to_evm::<T>)?;529 Ok(true)530 }531532 /// @dev Not implemented533 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {534 Err("not implementable".into())535 }536}537538fn get_token_property<T: Config>(539 collection: &CollectionHandle<T>,540 token_id: u32,541 key: &up_data_structs::PropertyKey,542) -> Result<string> {543 collection.consume_store_reads(1)?;544 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))545 .map_err(|_| Error::Revert("Token properties not found".into()))?;546 if let Some(property) = properties.get(key) {547 return Ok(string::from_utf8_lossy(property).into());548 }549550 Err("Property tokenURI not found".into())551}552553fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {554 if let Some(shema_name) =555 pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())556 {557 let shema_name = shema_name.into_inner();558 shema_name == property_value::ERC721_METADATA559 } else {560 false561 }562}563564fn get_token_permission<T: Config>(565 collection_id: CollectionId,566 key: &PropertyKey,567) -> Result<PropertyPermission> {568 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)569 .map_err(|_| Error::Revert("No permissions for collection".into()))?;570 let a = token_property_permissions571 .get(key)572 .map(Clone::clone)573 .ok_or_else(|| {574 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();575 Error::Revert(alloc::format!("No permission for key {}", key))576 })?;577 Ok(a)578}579580fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {581 if let Ok(token_property_permissions) =582 CollectionPropertyPermissions::<T>::try_get(collection_id)583 {584 return token_property_permissions.contains_key(key);585 }586587 false588}589590/// @title Unique extensions for ERC721.591#[solidity_interface(name = ERC721UniqueExtensions)]592impl<T: Config> NonfungibleHandle<T> {593 /// @notice Transfer ownership of an NFT594 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`595 /// is the zero address. Throws if `tokenId` is not a valid NFT.596 /// @param to The new owner597 /// @param tokenId The NFT to transfer598 #[weight(<SelfWeightOf<T>>::transfer())]599 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {600 let caller = T::CrossAccountId::from_eth(caller);601 let to = T::CrossAccountId::from_eth(to);602 let token = token_id.try_into()?;603 let budget = self604 .recorder605 .weight_calls_budget(<StructureWeight<T>>::find_parent());606607 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;608 Ok(())609 }610611 /// @notice Burns a specific ERC721 token.612 /// @dev Throws unless `msg.sender` is the current owner or an authorized613 /// operator for this NFT. Throws if `from` is not the current owner. Throws614 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.615 /// @param from The current owner of the NFT616 /// @param tokenId The NFT to transfer617 #[weight(<SelfWeightOf<T>>::burn_from())]618 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {619 let caller = T::CrossAccountId::from_eth(caller);620 let from = T::CrossAccountId::from_eth(from);621 let token = token_id.try_into()?;622 let budget = self623 .recorder624 .weight_calls_budget(<StructureWeight<T>>::find_parent());625626 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)627 .map_err(dispatch_to_evm::<T>)?;628 Ok(())629 }630631 /// @notice Returns next free NFT ID.632 fn next_token_id(&self) -> Result<uint256> {633 self.consume_store_reads(1)?;634 Ok(<TokensMinted<T>>::get(self.id)635 .checked_add(1)636 .ok_or("item id overflow")?637 .into())638 }639640 /// @notice Function to mint multiple tokens.641 /// @dev `tokenIds` should be an array of consecutive numbers and first number642 /// should be obtained with `nextTokenId` method643 /// @param to The new owner644 /// @param tokenIds IDs of the minted NFTs645 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]646 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {647 let caller = T::CrossAccountId::from_eth(caller);648 let to = T::CrossAccountId::from_eth(to);649 let mut expected_index = <TokensMinted<T>>::get(self.id)650 .checked_add(1)651 .ok_or("item id overflow")?;652 let budget = self653 .recorder654 .weight_calls_budget(<StructureWeight<T>>::find_parent());655656 let total_tokens = token_ids.len();657 for id in token_ids.into_iter() {658 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;659 if id != expected_index {660 return Err("item id should be next".into());661 }662 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;663 }664 let data = (0..total_tokens)665 .map(|_| CreateItemData::<T> {666 properties: BoundedVec::default(),667 owner: to.clone(),668 })669 .collect();670671 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)672 .map_err(dispatch_to_evm::<T>)?;673 Ok(true)674 }675676 /// @notice Function to mint multiple tokens with the given tokenUris.677 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive678 /// numbers and first number should be obtained with `nextTokenId` method679 /// @param to The new owner680 /// @param tokens array of pairs of token ID and token URI for minted tokens681 #[solidity(rename_selector = "mintBulkWithTokenURI")]682 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]683 fn mint_bulk_with_token_uri(684 &mut self,685 caller: caller,686 to: address,687 tokens: Vec<(uint256, string)>,688 ) -> Result<bool> {689 let key = key::url();690 let caller = T::CrossAccountId::from_eth(caller);691 let to = T::CrossAccountId::from_eth(to);692 let mut expected_index = <TokensMinted<T>>::get(self.id)693 .checked_add(1)694 .ok_or("item id overflow")?;695 let budget = self696 .recorder697 .weight_calls_budget(<StructureWeight<T>>::find_parent());698699 let mut data = Vec::with_capacity(tokens.len());700 for (id, token_uri) in tokens {701 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;702 if id != expected_index {703 return Err("item id should be next".into());704 }705 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;706707 let mut properties = CollectionPropertiesVec::default();708 properties709 .try_push(Property {710 key: key.clone(),711 value: token_uri712 .into_bytes()713 .try_into()714 .map_err(|_| "token uri is too long")?,715 })716 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;717718 data.push(CreateItemData::<T> {719 properties,720 owner: to.clone(),721 });722 }723724 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)725 .map_err(dispatch_to_evm::<T>)?;726 Ok(true)727 }728}729730#[solidity_interface(731 name = UniqueNFT,732 is(733 ERC721,734 ERC721Metadata,735 ERC721Enumerable,736 ERC721UniqueExtensions,737 ERC721Mintable,738 ERC721Burnable,739 Collection(common_mut, CollectionHandle<T>),740 TokenProperties,741 )742)]743impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}744745// Not a tests, but code generators746generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);747generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);748749impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>750where751 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,752{753 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");754755 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {756 call::<T, UniqueNFTCall<T>, _, _>(handle, self)757 }758}pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -789,7 +789,7 @@
TokenProperties,
)
)]
-impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8]> {}
+impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}
// Not a tests, but code generators
generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);
@@ -797,7 +797,7 @@
impl<T: Config> CommonEvmHandler for RefungibleHandle<T>
where
- T::AccountId: From<[u8; 32]> + AsRef<[u8]>,
+ T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
{
const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");
fn call(
runtime/common/dispatch.rsdiffbeforeafterboth--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -124,7 +124,7 @@
+ pallet_fungible::Config
+ pallet_nonfungible::Config
+ pallet_refungible::Config,
- T::AccountId: From<[u8; 32]> + AsRef<[u8]>,
+ T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,
{
fn is_reserved(target: &H160) -> bool {
map_eth_to_id(target).is_some()