difftreelog
misk: remove token_uri key const.
in: master
2 files changed
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -437,10 +437,6 @@
use alloc::format;
const EXPECT_CONVERT_ERROR: &str = "length < limit";
- /// Get the "tokenURI" key as [PropertyKey](up_data_structs::PropertyKey).
- pub fn token_uri_key() -> up_data_structs::PropertyKey {
- property_key_from_bytes(b"tokenURI").expect(EXPECT_CONVERT_ERROR)
- }
pub fn schema_name_key() -> up_data_structs::PropertyKey {
property_key_from_bytes(b"schemaName").expect(EXPECT_CONVERT_ERROR)
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::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property_key_value::*},37 CollectionHandle, CollectionPropertyPermissions,38};39use pallet_evm::{account::CrossAccountId, PrecompileHandle};40use pallet_evm_coder_substrate::call;41use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};42use alloc::string::ToString;4344use crate::{45 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,46 SelfWeightOf, weights::WeightInfo, TokenProperties,47};4849/// @title A contract that allows to set and delete token properties and change token property permissions.50#[solidity_interface(name = "TokenProperties")]51impl<T: Config> NonfungibleHandle<T> {52 /// @notice Set permissions for token property.53 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.54 /// @param key Property key.55 /// @param is_mutable Permission to mutate property.56 /// @param collection_admin Permission to mutate property by collection admin if property is mutable.57 /// @param token_owner Permission to mutate property by token owner if property is mutable.58 fn set_token_property_permission(59 &mut self,60 caller: caller,61 key: string,62 is_mutable: bool,63 collection_admin: bool,64 token_owner: bool,65 ) -> Result<()> {66 let caller = T::CrossAccountId::from_eth(caller);67 <Pallet<T>>::set_property_permission(68 self,69 &caller,70 PropertyKeyPermission {71 key: <Vec<u8>>::from(key)72 .try_into()73 .map_err(|_| "too long key")?,74 permission: PropertyPermission {75 mutable: is_mutable,76 collection_admin,77 token_owner,78 },79 },80 )81 .map_err(dispatch_to_evm::<T>)82 }8384 /// @notice Set token property value.85 /// @dev Throws error if `msg.sender` has no permission to edit the property.86 /// @param tokenId ID of the token.87 /// @param key Property key.88 /// @param value Property value.89 fn set_property(90 &mut self,91 caller: caller,92 token_id: uint256,93 key: string,94 value: bytes,95 ) -> Result<()> {96 let caller = T::CrossAccountId::from_eth(caller);97 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;98 let key = <Vec<u8>>::from(key)99 .try_into()100 .map_err(|_| "key too long")?;101 let value = value.try_into().map_err(|_| "value too long")?;102103 let nesting_budget = self104 .recorder105 .weight_calls_budget(<StructureWeight<T>>::find_parent());106107 <Pallet<T>>::set_token_property(108 self,109 &caller,110 TokenId(token_id),111 Property { key, value },112 &nesting_budget,113 )114 .map_err(dispatch_to_evm::<T>)115 }116117 /// @notice Delete token property value.118 /// @dev Throws error if `msg.sender` has no permission to edit the property.119 /// @param tokenId ID of the token.120 /// @param key Property key.121 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {122 let caller = T::CrossAccountId::from_eth(caller);123 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;124 let key = <Vec<u8>>::from(key)125 .try_into()126 .map_err(|_| "key too long")?;127128 let nesting_budget = self129 .recorder130 .weight_calls_budget(<StructureWeight<T>>::find_parent());131132 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)133 .map_err(dispatch_to_evm::<T>)134 }135136 /// @notice Get token property value.137 /// @dev Throws error if key not found138 /// @param tokenId ID of the token.139 /// @param key Property key.140 /// @return Property value bytes141 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {142 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;143 let key = <Vec<u8>>::from(key)144 .try_into()145 .map_err(|_| "key too long")?;146147 let props = <TokenProperties<T>>::get((self.id, token_id));148 let prop = props.get(&key).ok_or("key not found")?;149150 Ok(prop.to_vec())151 }152}153154#[derive(ToLog)]155pub enum ERC721Events {156 /// @dev This emits when ownership of any NFT changes by any mechanism.157 /// This event emits when NFTs are created (`from` == 0) and destroyed158 /// (`to` == 0). Exception: during contract creation, any number of NFTs159 /// may be created and assigned without emitting Transfer. At the time of160 /// any transfer, the approved address for that NFT (if any) is reset to none.161 Transfer {162 #[indexed]163 from: address,164 #[indexed]165 to: address,166 #[indexed]167 token_id: uint256,168 },169 /// @dev This emits when the approved address for an NFT is changed or170 /// reaffirmed. The zero address indicates there is no approved address.171 /// When a Transfer event emits, this also indicates that the approved172 /// address for that NFT (if any) is reset to none.173 Approval {174 #[indexed]175 owner: address,176 #[indexed]177 approved: address,178 #[indexed]179 token_id: uint256,180 },181 /// @dev This emits when an operator is enabled or disabled for an owner.182 /// The operator can manage all NFTs of the owner.183 #[allow(dead_code)]184 ApprovalForAll {185 #[indexed]186 owner: address,187 #[indexed]188 operator: address,189 approved: bool,190 },191}192193#[derive(ToLog)]194pub enum ERC721MintableEvents {195 #[allow(dead_code)]196 MintingFinished {},197}198199/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension200/// @dev See https://eips.ethereum.org/EIPS/eip-721201#[solidity_interface(name = "ERC721Metadata")]202impl<T: Config> NonfungibleHandle<T> {203 /// @notice A descriptive name for a collection of NFTs in this contract204 fn name(&self) -> Result<string> {205 Ok(decode_utf16(self.name.iter().copied())206 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))207 .collect::<string>())208 }209210 /// @notice An abbreviated name for NFTs in this contract211 fn symbol(&self) -> Result<string> {212 Ok(string::from_utf8_lossy(&self.token_prefix).into())213 }214215 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.216 /// @dev Throws if `tokenId` is not a valid NFT. URIs are defined in RFC217 /// 3986. The URI may point to a JSON file that conforms to the "ERC721218 /// Metadata JSON Schema".219 /// @return token's const_metadata220 #[solidity(rename_selector = "tokenURI")]221 fn token_uri(&self, token_id: uint256) -> Result<string> {222 let is_erc721 = || {223 if let Some(shema_name) =224 pallet_common::Pallet::<T>::get_collection_property(self.id, &schema_name_key())225 {226 let shema_name = shema_name.into_inner();227 shema_name == ERC721_METADATA228 } else {229 false230 }231 };232233 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;234235 if let Ok(url) = get_token_property(self, token_id_u32, &u_key()) {236 if !url.is_empty() {237 return Ok(url);238 }239 } else if !is_erc721() {240 return Err("tokenURI not set".into());241 }242243 if let Some(base_uri) =244 pallet_common::Pallet::<T>::get_collection_property(self.id, &base_uri_key())245 {246 if !base_uri.is_empty() {247 let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {248 Error::Revert(alloc::format!(249 "Can not convert value \"baseURI\" to string with error \"{}\"",250 e251 ))252 })?;253 if let Ok(suffix) = get_token_property(self, token_id_u32, &s_key()) {254 if !suffix.is_empty() {255 return Ok(base_uri + suffix.as_str());256 }257 }258259 return Ok(base_uri + token_id.to_string().as_str());260 }261 }262263 Ok("".into())264 }265}266267/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension268/// @dev See https://eips.ethereum.org/EIPS/eip-721269#[solidity_interface(name = "ERC721Enumerable")]270impl<T: Config> NonfungibleHandle<T> {271 /// @notice Enumerate valid NFTs272 /// @param index A counter less than `totalSupply()`273 /// @return The token identifier for the `index`th NFT,274 /// (sort order not specified)275 fn token_by_index(&self, index: uint256) -> Result<uint256> {276 Ok(index)277 }278279 /// @dev Not implemented280 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {281 // TODO: Not implemetable282 Err("not implemented".into())283 }284285 /// @notice Count NFTs tracked by this contract286 /// @return A count of valid NFTs tracked by this contract, where each one of287 /// them has an assigned and queryable owner not equal to the zero address288 fn total_supply(&self) -> Result<uint256> {289 self.consume_store_reads(1)?;290 Ok(<Pallet<T>>::total_supply(self).into())291 }292}293294/// @title ERC-721 Non-Fungible Token Standard295/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md296#[solidity_interface(name = "ERC721", events(ERC721Events))]297impl<T: Config> NonfungibleHandle<T> {298 /// @notice Count all NFTs assigned to an owner299 /// @dev NFTs assigned to the zero address are considered invalid, and this300 /// function throws for queries about the zero address.301 /// @param owner An address for whom to query the balance302 /// @return The number of NFTs owned by `owner`, possibly zero303 fn balance_of(&self, owner: address) -> Result<uint256> {304 self.consume_store_reads(1)?;305 let owner = T::CrossAccountId::from_eth(owner);306 let balance = <AccountBalance<T>>::get((self.id, owner));307 Ok(balance.into())308 }309 /// @notice Find the owner of an NFT310 /// @dev NFTs assigned to zero address are considered invalid, and queries311 /// about them do throw.312 /// @param tokenId The identifier for an NFT313 /// @return The address of the owner of the NFT314 fn owner_of(&self, token_id: uint256) -> Result<address> {315 self.consume_store_reads(1)?;316 let token: TokenId = token_id.try_into()?;317 Ok(*<TokenData<T>>::get((self.id, token))318 .ok_or("token not found")?319 .owner320 .as_eth())321 }322 /// @dev Not implemented323 fn safe_transfer_from_with_data(324 &mut self,325 _from: address,326 _to: address,327 _token_id: uint256,328 _data: bytes,329 _value: value,330 ) -> Result<void> {331 // TODO: Not implemetable332 Err("not implemented".into())333 }334 /// @dev Not implemented335 fn safe_transfer_from(336 &mut self,337 _from: address,338 _to: address,339 _token_id: uint256,340 _value: value,341 ) -> Result<void> {342 // TODO: Not implemetable343 Err("not implemented".into())344 }345346 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE347 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE348 /// THEY MAY BE PERMANENTLY LOST349 /// @dev Throws unless `msg.sender` is the current owner or an authorized350 /// operator for this NFT. Throws if `from` is not the current owner. Throws351 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.352 /// @param from The current owner of the NFT353 /// @param to The new owner354 /// @param tokenId The NFT to transfer355 /// @param _value Not used for an NFT356 #[weight(<SelfWeightOf<T>>::transfer_from())]357 fn transfer_from(358 &mut self,359 caller: caller,360 from: address,361 to: address,362 token_id: uint256,363 _value: value,364 ) -> Result<void> {365 let caller = T::CrossAccountId::from_eth(caller);366 let from = T::CrossAccountId::from_eth(from);367 let to = T::CrossAccountId::from_eth(to);368 let token = token_id.try_into()?;369 let budget = self370 .recorder371 .weight_calls_budget(<StructureWeight<T>>::find_parent());372373 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)374 .map_err(dispatch_to_evm::<T>)?;375 Ok(())376 }377378 /// @notice Set or reaffirm the approved address for an NFT379 /// @dev The zero address indicates there is no approved address.380 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized381 /// operator of the current owner.382 /// @param approved The new approved NFT controller383 /// @param tokenId The NFT to approve384 #[weight(<SelfWeightOf<T>>::approve())]385 fn approve(386 &mut self,387 caller: caller,388 approved: address,389 token_id: uint256,390 _value: value,391 ) -> Result<void> {392 let caller = T::CrossAccountId::from_eth(caller);393 let approved = T::CrossAccountId::from_eth(approved);394 let token = token_id.try_into()?;395396 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))397 .map_err(dispatch_to_evm::<T>)?;398 Ok(())399 }400401 /// @dev Not implemented402 fn set_approval_for_all(403 &mut self,404 _caller: caller,405 _operator: address,406 _approved: bool,407 ) -> Result<void> {408 // TODO: Not implemetable409 Err("not implemented".into())410 }411412 /// @dev Not implemented413 fn get_approved(&self, _token_id: uint256) -> Result<address> {414 // TODO: Not implemetable415 Err("not implemented".into())416 }417418 /// @dev Not implemented419 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {420 // TODO: Not implemetable421 Err("not implemented".into())422 }423}424425/// @title ERC721 Token that can be irreversibly burned (destroyed).426#[solidity_interface(name = "ERC721Burnable")]427impl<T: Config> NonfungibleHandle<T> {428 /// @notice Burns a specific ERC721 token.429 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized430 /// operator of the current owner.431 /// @param tokenId The NFT to approve432 #[weight(<SelfWeightOf<T>>::burn_item())]433 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {434 let caller = T::CrossAccountId::from_eth(caller);435 let token = token_id.try_into()?;436437 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;438 Ok(())439 }440}441442/// @title ERC721 minting logic.443#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]444impl<T: Config> NonfungibleHandle<T> {445 fn minting_finished(&self) -> Result<bool> {446 Ok(false)447 }448449 /// @notice Function to mint token.450 /// @dev `tokenId` should be obtained with `nextTokenId` method,451 /// unlike standard, you can't specify it manually452 /// @param to The new owner453 /// @param tokenId ID of the minted NFT454 #[weight(<SelfWeightOf<T>>::create_item())]455 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {456 let caller = T::CrossAccountId::from_eth(caller);457 let to = T::CrossAccountId::from_eth(to);458 let token_id: u32 = token_id.try_into()?;459 let budget = self460 .recorder461 .weight_calls_budget(<StructureWeight<T>>::find_parent());462463 if <TokensMinted<T>>::get(self.id)464 .checked_add(1)465 .ok_or("item id overflow")?466 != token_id467 {468 return Err("item id should be next".into());469 }470471 <Pallet<T>>::create_item(472 self,473 &caller,474 CreateItemData::<T> {475 properties: BoundedVec::default(),476 owner: to,477 },478 &budget,479 )480 .map_err(dispatch_to_evm::<T>)?;481482 Ok(true)483 }484485 /// @notice Function to mint token with the given tokenUri.486 /// @dev `tokenId` should be obtained with `nextTokenId` method,487 /// unlike standard, you can't specify it manually488 /// @param to The new owner489 /// @param tokenId ID of the minted NFT490 /// @param tokenUri Token URI that would be stored in the NFT properties491 #[solidity(rename_selector = "mintWithTokenURI")]492 #[weight(<SelfWeightOf<T>>::create_item())]493 fn mint_with_token_uri(494 &mut self,495 caller: caller,496 to: address,497 token_id: uint256,498 token_uri: string,499 ) -> Result<bool> {500 let key = u_key();501 let permission = get_token_permission::<T>(self.id, &key)?;502 if !permission.collection_admin {503 return Err("Operation is not allowed".into());504 }505506 let caller = T::CrossAccountId::from_eth(caller);507 let to = T::CrossAccountId::from_eth(to);508 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;509 let budget = self510 .recorder511 .weight_calls_budget(<StructureWeight<T>>::find_parent());512513 if <TokensMinted<T>>::get(self.id)514 .checked_add(1)515 .ok_or("item id overflow")?516 != token_id517 {518 return Err("item id should be next".into());519 }520521 let mut properties = CollectionPropertiesVec::default();522 properties523 .try_push(Property {524 key,525 value: token_uri526 .into_bytes()527 .try_into()528 .map_err(|_| "token uri is too long")?,529 })530 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;531532 <Pallet<T>>::create_item(533 self,534 &caller,535 CreateItemData::<T> {536 properties,537 owner: to,538 },539 &budget,540 )541 .map_err(dispatch_to_evm::<T>)?;542 Ok(true)543 }544545 /// @dev Not implemented546 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {547 Err("not implementable".into())548 }549}550551fn get_token_property<T: Config>(552 collection: &CollectionHandle<T>,553 token_id: u32,554 key: &up_data_structs::PropertyKey,555) -> Result<string> {556 collection.consume_store_reads(1)?;557 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))558 .map_err(|_| Error::Revert("Token properties not found".into()))?;559 if let Some(property) = properties.get(key) {560 return Ok(string::from_utf8_lossy(property).into());561 }562563 Err("Property tokenURI not found".into())564}565566fn get_token_permission<T: Config>(567 collection_id: CollectionId,568 key: &PropertyKey,569) -> Result<PropertyPermission> {570 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)571 .map_err(|_| Error::Revert("No permissions for collection".into()))?;572 let a = token_property_permissions573 .get(key)574 .map(Clone::clone)575 .ok_or_else(|| {576 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();577 Error::Revert(alloc::format!("No permission for key {}", key))578 })?;579 Ok(a)580}581582fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {583 if let Ok(token_property_permissions) =584 CollectionPropertyPermissions::<T>::try_get(collection_id)585 {586 return token_property_permissions.contains_key(key);587 }588589 false590}591592/// @title Unique extensions for ERC721.593#[solidity_interface(name = "ERC721UniqueExtensions")]594impl<T: Config> NonfungibleHandle<T> {595 /// @notice Transfer ownership of an NFT596 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`597 /// is the zero address. Throws if `tokenId` is not a valid NFT.598 /// @param to The new owner599 /// @param tokenId The NFT to transfer600 /// @param _value Not used for an NFT601 #[weight(<SelfWeightOf<T>>::transfer())]602 fn transfer(603 &mut self,604 caller: caller,605 to: address,606 token_id: uint256,607 _value: value,608 ) -> Result<void> {609 let caller = T::CrossAccountId::from_eth(caller);610 let to = T::CrossAccountId::from_eth(to);611 let token = token_id.try_into()?;612 let budget = self613 .recorder614 .weight_calls_budget(<StructureWeight<T>>::find_parent());615616 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;617 Ok(())618 }619620 /// @notice Burns a specific ERC721 token.621 /// @dev Throws unless `msg.sender` is the current owner or an authorized622 /// operator for this NFT. Throws if `from` is not the current owner. Throws623 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.624 /// @param from The current owner of the NFT625 /// @param tokenId The NFT to transfer626 /// @param _value Not used for an NFT627 #[weight(<SelfWeightOf<T>>::burn_from())]628 fn burn_from(629 &mut self,630 caller: caller,631 from: address,632 token_id: uint256,633 _value: value,634 ) -> Result<void> {635 let caller = T::CrossAccountId::from_eth(caller);636 let from = T::CrossAccountId::from_eth(from);637 let token = token_id.try_into()?;638 let budget = self639 .recorder640 .weight_calls_budget(<StructureWeight<T>>::find_parent());641642 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)643 .map_err(dispatch_to_evm::<T>)?;644 Ok(())645 }646647 /// @notice Returns next free NFT ID.648 fn next_token_id(&self) -> Result<uint256> {649 self.consume_store_reads(1)?;650 Ok(<TokensMinted<T>>::get(self.id)651 .checked_add(1)652 .ok_or("item id overflow")?653 .into())654 }655656 /// @notice Function to mint multiple tokens.657 /// @dev `tokenIds` should be an array of consecutive numbers and first number658 /// should be obtained with `nextTokenId` method659 /// @param to The new owner660 /// @param tokenIds IDs of the minted NFTs661 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]662 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {663 let caller = T::CrossAccountId::from_eth(caller);664 let to = T::CrossAccountId::from_eth(to);665 let mut expected_index = <TokensMinted<T>>::get(self.id)666 .checked_add(1)667 .ok_or("item id overflow")?;668 let budget = self669 .recorder670 .weight_calls_budget(<StructureWeight<T>>::find_parent());671672 let total_tokens = token_ids.len();673 for id in token_ids.into_iter() {674 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;675 if id != expected_index {676 return Err("item id should be next".into());677 }678 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;679 }680 let data = (0..total_tokens)681 .map(|_| CreateItemData::<T> {682 properties: BoundedVec::default(),683 owner: to.clone(),684 })685 .collect();686687 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)688 .map_err(dispatch_to_evm::<T>)?;689 Ok(true)690 }691692 /// @notice Function to mint multiple tokens with the given tokenUris.693 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive694 /// numbers and first number should be obtained with `nextTokenId` method695 /// @param to The new owner696 /// @param tokens array of pairs of token ID and token URI for minted tokens697 #[solidity(rename_selector = "mintBulkWithTokenURI")]698 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]699 fn mint_bulk_with_token_uri(700 &mut self,701 caller: caller,702 to: address,703 tokens: Vec<(uint256, string)>,704 ) -> Result<bool> {705 let key = token_uri_key();706 let caller = T::CrossAccountId::from_eth(caller);707 let to = T::CrossAccountId::from_eth(to);708 let mut expected_index = <TokensMinted<T>>::get(self.id)709 .checked_add(1)710 .ok_or("item id overflow")?;711 let budget = self712 .recorder713 .weight_calls_budget(<StructureWeight<T>>::find_parent());714715 let mut data = Vec::with_capacity(tokens.len());716 for (id, token_uri) in tokens {717 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;718 if id != expected_index {719 return Err("item id should be next".into());720 }721 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;722723 let mut properties = CollectionPropertiesVec::default();724 properties725 .try_push(Property {726 key: key.clone(),727 value: token_uri728 .into_bytes()729 .try_into()730 .map_err(|_| "token uri is too long")?,731 })732 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;733734 data.push(CreateItemData::<T> {735 properties,736 owner: to.clone(),737 });738 }739740 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)741 .map_err(dispatch_to_evm::<T>)?;742 Ok(true)743 }744}745746#[solidity_interface(747 name = "UniqueNFT",748 is(749 ERC721,750 ERC721Metadata,751 ERC721Enumerable,752 ERC721UniqueExtensions,753 ERC721Mintable,754 ERC721Burnable,755 via("CollectionHandle<T>", common_mut, Collection),756 TokenProperties,757 )758)]759impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> {}760761// Not a tests, but code generators762generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);763generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);764765impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>766where767 T::AccountId: From<[u8; 32]>,768{769 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");770771 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {772 call::<T, UniqueNFTCall<T>, _, _>(handle, self)773 }774}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::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property_key_value::*},37 CollectionHandle, CollectionPropertyPermissions,38};39use pallet_evm::{account::CrossAccountId, PrecompileHandle};40use pallet_evm_coder_substrate::call;41use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};42use alloc::string::ToString;4344use crate::{45 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,46 SelfWeightOf, weights::WeightInfo, TokenProperties,47};4849/// @title A contract that allows to set and delete token properties and change token property permissions.50#[solidity_interface(name = "TokenProperties")]51impl<T: Config> NonfungibleHandle<T> {52 /// @notice Set permissions for token property.53 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.54 /// @param key Property key.55 /// @param is_mutable Permission to mutate property.56 /// @param collection_admin Permission to mutate property by collection admin if property is mutable.57 /// @param token_owner Permission to mutate property by token owner if property is mutable.58 fn set_token_property_permission(59 &mut self,60 caller: caller,61 key: string,62 is_mutable: bool,63 collection_admin: bool,64 token_owner: bool,65 ) -> Result<()> {66 let caller = T::CrossAccountId::from_eth(caller);67 <Pallet<T>>::set_property_permission(68 self,69 &caller,70 PropertyKeyPermission {71 key: <Vec<u8>>::from(key)72 .try_into()73 .map_err(|_| "too long key")?,74 permission: PropertyPermission {75 mutable: is_mutable,76 collection_admin,77 token_owner,78 },79 },80 )81 .map_err(dispatch_to_evm::<T>)82 }8384 /// @notice Set token property value.85 /// @dev Throws error if `msg.sender` has no permission to edit the property.86 /// @param tokenId ID of the token.87 /// @param key Property key.88 /// @param value Property value.89 fn set_property(90 &mut self,91 caller: caller,92 token_id: uint256,93 key: string,94 value: bytes,95 ) -> Result<()> {96 let caller = T::CrossAccountId::from_eth(caller);97 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;98 let key = <Vec<u8>>::from(key)99 .try_into()100 .map_err(|_| "key too long")?;101 let value = value.try_into().map_err(|_| "value too long")?;102103 let nesting_budget = self104 .recorder105 .weight_calls_budget(<StructureWeight<T>>::find_parent());106107 <Pallet<T>>::set_token_property(108 self,109 &caller,110 TokenId(token_id),111 Property { key, value },112 &nesting_budget,113 )114 .map_err(dispatch_to_evm::<T>)115 }116117 /// @notice Delete token property value.118 /// @dev Throws error if `msg.sender` has no permission to edit the property.119 /// @param tokenId ID of the token.120 /// @param key Property key.121 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {122 let caller = T::CrossAccountId::from_eth(caller);123 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;124 let key = <Vec<u8>>::from(key)125 .try_into()126 .map_err(|_| "key too long")?;127128 let nesting_budget = self129 .recorder130 .weight_calls_budget(<StructureWeight<T>>::find_parent());131132 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)133 .map_err(dispatch_to_evm::<T>)134 }135136 /// @notice Get token property value.137 /// @dev Throws error if key not found138 /// @param tokenId ID of the token.139 /// @param key Property key.140 /// @return Property value bytes141 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {142 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;143 let key = <Vec<u8>>::from(key)144 .try_into()145 .map_err(|_| "key too long")?;146147 let props = <TokenProperties<T>>::get((self.id, token_id));148 let prop = props.get(&key).ok_or("key not found")?;149150 Ok(prop.to_vec())151 }152}153154#[derive(ToLog)]155pub enum ERC721Events {156 /// @dev This emits when ownership of any NFT changes by any mechanism.157 /// This event emits when NFTs are created (`from` == 0) and destroyed158 /// (`to` == 0). Exception: during contract creation, any number of NFTs159 /// may be created and assigned without emitting Transfer. At the time of160 /// any transfer, the approved address for that NFT (if any) is reset to none.161 Transfer {162 #[indexed]163 from: address,164 #[indexed]165 to: address,166 #[indexed]167 token_id: uint256,168 },169 /// @dev This emits when the approved address for an NFT is changed or170 /// reaffirmed. The zero address indicates there is no approved address.171 /// When a Transfer event emits, this also indicates that the approved172 /// address for that NFT (if any) is reset to none.173 Approval {174 #[indexed]175 owner: address,176 #[indexed]177 approved: address,178 #[indexed]179 token_id: uint256,180 },181 /// @dev This emits when an operator is enabled or disabled for an owner.182 /// The operator can manage all NFTs of the owner.183 #[allow(dead_code)]184 ApprovalForAll {185 #[indexed]186 owner: address,187 #[indexed]188 operator: address,189 approved: bool,190 },191}192193#[derive(ToLog)]194pub enum ERC721MintableEvents {195 #[allow(dead_code)]196 MintingFinished {},197}198199/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension200/// @dev See https://eips.ethereum.org/EIPS/eip-721201#[solidity_interface(name = "ERC721Metadata")]202impl<T: Config> NonfungibleHandle<T> {203 /// @notice A descriptive name for a collection of NFTs in this contract204 fn name(&self) -> Result<string> {205 Ok(decode_utf16(self.name.iter().copied())206 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))207 .collect::<string>())208 }209210 /// @notice An abbreviated name for NFTs in this contract211 fn symbol(&self) -> Result<string> {212 Ok(string::from_utf8_lossy(&self.token_prefix).into())213 }214215 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.216 /// @dev Throws if `tokenId` is not a valid NFT. URIs are defined in RFC217 /// 3986. The URI may point to a JSON file that conforms to the "ERC721218 /// Metadata JSON Schema".219 /// @return token's const_metadata220 #[solidity(rename_selector = "tokenURI")]221 fn token_uri(&self, token_id: uint256) -> Result<string> {222 let is_erc721 = || {223 if let Some(shema_name) =224 pallet_common::Pallet::<T>::get_collection_property(self.id, &schema_name_key())225 {226 let shema_name = shema_name.into_inner();227 shema_name == ERC721_METADATA228 } else {229 false230 }231 };232233 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;234235 if let Ok(url) = get_token_property(self, token_id_u32, &u_key()) {236 if !url.is_empty() {237 return Ok(url);238 }239 } else if !is_erc721() {240 return Err("tokenURI not set".into());241 }242243 if let Some(base_uri) =244 pallet_common::Pallet::<T>::get_collection_property(self.id, &base_uri_key())245 {246 if !base_uri.is_empty() {247 let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {248 Error::Revert(alloc::format!(249 "Can not convert value \"baseURI\" to string with error \"{}\"",250 e251 ))252 })?;253 if let Ok(suffix) = get_token_property(self, token_id_u32, &s_key()) {254 if !suffix.is_empty() {255 return Ok(base_uri + suffix.as_str());256 }257 }258259 return Ok(base_uri + token_id.to_string().as_str());260 }261 }262263 Ok("".into())264 }265}266267/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension268/// @dev See https://eips.ethereum.org/EIPS/eip-721269#[solidity_interface(name = "ERC721Enumerable")]270impl<T: Config> NonfungibleHandle<T> {271 /// @notice Enumerate valid NFTs272 /// @param index A counter less than `totalSupply()`273 /// @return The token identifier for the `index`th NFT,274 /// (sort order not specified)275 fn token_by_index(&self, index: uint256) -> Result<uint256> {276 Ok(index)277 }278279 /// @dev Not implemented280 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {281 // TODO: Not implemetable282 Err("not implemented".into())283 }284285 /// @notice Count NFTs tracked by this contract286 /// @return A count of valid NFTs tracked by this contract, where each one of287 /// them has an assigned and queryable owner not equal to the zero address288 fn total_supply(&self) -> Result<uint256> {289 self.consume_store_reads(1)?;290 Ok(<Pallet<T>>::total_supply(self).into())291 }292}293294/// @title ERC-721 Non-Fungible Token Standard295/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md296#[solidity_interface(name = "ERC721", events(ERC721Events))]297impl<T: Config> NonfungibleHandle<T> {298 /// @notice Count all NFTs assigned to an owner299 /// @dev NFTs assigned to the zero address are considered invalid, and this300 /// function throws for queries about the zero address.301 /// @param owner An address for whom to query the balance302 /// @return The number of NFTs owned by `owner`, possibly zero303 fn balance_of(&self, owner: address) -> Result<uint256> {304 self.consume_store_reads(1)?;305 let owner = T::CrossAccountId::from_eth(owner);306 let balance = <AccountBalance<T>>::get((self.id, owner));307 Ok(balance.into())308 }309 /// @notice Find the owner of an NFT310 /// @dev NFTs assigned to zero address are considered invalid, and queries311 /// about them do throw.312 /// @param tokenId The identifier for an NFT313 /// @return The address of the owner of the NFT314 fn owner_of(&self, token_id: uint256) -> Result<address> {315 self.consume_store_reads(1)?;316 let token: TokenId = token_id.try_into()?;317 Ok(*<TokenData<T>>::get((self.id, token))318 .ok_or("token not found")?319 .owner320 .as_eth())321 }322 /// @dev Not implemented323 fn safe_transfer_from_with_data(324 &mut self,325 _from: address,326 _to: address,327 _token_id: uint256,328 _data: bytes,329 _value: value,330 ) -> Result<void> {331 // TODO: Not implemetable332 Err("not implemented".into())333 }334 /// @dev Not implemented335 fn safe_transfer_from(336 &mut self,337 _from: address,338 _to: address,339 _token_id: uint256,340 _value: value,341 ) -> Result<void> {342 // TODO: Not implemetable343 Err("not implemented".into())344 }345346 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE347 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE348 /// THEY MAY BE PERMANENTLY LOST349 /// @dev Throws unless `msg.sender` is the current owner or an authorized350 /// operator for this NFT. Throws if `from` is not the current owner. Throws351 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.352 /// @param from The current owner of the NFT353 /// @param to The new owner354 /// @param tokenId The NFT to transfer355 /// @param _value Not used for an NFT356 #[weight(<SelfWeightOf<T>>::transfer_from())]357 fn transfer_from(358 &mut self,359 caller: caller,360 from: address,361 to: address,362 token_id: uint256,363 _value: value,364 ) -> Result<void> {365 let caller = T::CrossAccountId::from_eth(caller);366 let from = T::CrossAccountId::from_eth(from);367 let to = T::CrossAccountId::from_eth(to);368 let token = token_id.try_into()?;369 let budget = self370 .recorder371 .weight_calls_budget(<StructureWeight<T>>::find_parent());372373 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)374 .map_err(dispatch_to_evm::<T>)?;375 Ok(())376 }377378 /// @notice Set or reaffirm the approved address for an NFT379 /// @dev The zero address indicates there is no approved address.380 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized381 /// operator of the current owner.382 /// @param approved The new approved NFT controller383 /// @param tokenId The NFT to approve384 #[weight(<SelfWeightOf<T>>::approve())]385 fn approve(386 &mut self,387 caller: caller,388 approved: address,389 token_id: uint256,390 _value: value,391 ) -> Result<void> {392 let caller = T::CrossAccountId::from_eth(caller);393 let approved = T::CrossAccountId::from_eth(approved);394 let token = token_id.try_into()?;395396 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))397 .map_err(dispatch_to_evm::<T>)?;398 Ok(())399 }400401 /// @dev Not implemented402 fn set_approval_for_all(403 &mut self,404 _caller: caller,405 _operator: address,406 _approved: bool,407 ) -> Result<void> {408 // TODO: Not implemetable409 Err("not implemented".into())410 }411412 /// @dev Not implemented413 fn get_approved(&self, _token_id: uint256) -> Result<address> {414 // TODO: Not implemetable415 Err("not implemented".into())416 }417418 /// @dev Not implemented419 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {420 // TODO: Not implemetable421 Err("not implemented".into())422 }423}424425/// @title ERC721 Token that can be irreversibly burned (destroyed).426#[solidity_interface(name = "ERC721Burnable")]427impl<T: Config> NonfungibleHandle<T> {428 /// @notice Burns a specific ERC721 token.429 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized430 /// operator of the current owner.431 /// @param tokenId The NFT to approve432 #[weight(<SelfWeightOf<T>>::burn_item())]433 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {434 let caller = T::CrossAccountId::from_eth(caller);435 let token = token_id.try_into()?;436437 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;438 Ok(())439 }440}441442/// @title ERC721 minting logic.443#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]444impl<T: Config> NonfungibleHandle<T> {445 fn minting_finished(&self) -> Result<bool> {446 Ok(false)447 }448449 /// @notice Function to mint token.450 /// @dev `tokenId` should be obtained with `nextTokenId` method,451 /// unlike standard, you can't specify it manually452 /// @param to The new owner453 /// @param tokenId ID of the minted NFT454 #[weight(<SelfWeightOf<T>>::create_item())]455 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {456 let caller = T::CrossAccountId::from_eth(caller);457 let to = T::CrossAccountId::from_eth(to);458 let token_id: u32 = token_id.try_into()?;459 let budget = self460 .recorder461 .weight_calls_budget(<StructureWeight<T>>::find_parent());462463 if <TokensMinted<T>>::get(self.id)464 .checked_add(1)465 .ok_or("item id overflow")?466 != token_id467 {468 return Err("item id should be next".into());469 }470471 <Pallet<T>>::create_item(472 self,473 &caller,474 CreateItemData::<T> {475 properties: BoundedVec::default(),476 owner: to,477 },478 &budget,479 )480 .map_err(dispatch_to_evm::<T>)?;481482 Ok(true)483 }484485 /// @notice Function to mint token with the given tokenUri.486 /// @dev `tokenId` should be obtained with `nextTokenId` method,487 /// unlike standard, you can't specify it manually488 /// @param to The new owner489 /// @param tokenId ID of the minted NFT490 /// @param tokenUri Token URI that would be stored in the NFT properties491 #[solidity(rename_selector = "mintWithTokenURI")]492 #[weight(<SelfWeightOf<T>>::create_item())]493 fn mint_with_token_uri(494 &mut self,495 caller: caller,496 to: address,497 token_id: uint256,498 token_uri: string,499 ) -> Result<bool> {500 let key = u_key();501 let permission = get_token_permission::<T>(self.id, &key)?;502 if !permission.collection_admin {503 return Err("Operation is not allowed".into());504 }505506 let caller = T::CrossAccountId::from_eth(caller);507 let to = T::CrossAccountId::from_eth(to);508 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;509 let budget = self510 .recorder511 .weight_calls_budget(<StructureWeight<T>>::find_parent());512513 if <TokensMinted<T>>::get(self.id)514 .checked_add(1)515 .ok_or("item id overflow")?516 != token_id517 {518 return Err("item id should be next".into());519 }520521 let mut properties = CollectionPropertiesVec::default();522 properties523 .try_push(Property {524 key,525 value: token_uri526 .into_bytes()527 .try_into()528 .map_err(|_| "token uri is too long")?,529 })530 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;531532 <Pallet<T>>::create_item(533 self,534 &caller,535 CreateItemData::<T> {536 properties,537 owner: to,538 },539 &budget,540 )541 .map_err(dispatch_to_evm::<T>)?;542 Ok(true)543 }544545 /// @dev Not implemented546 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {547 Err("not implementable".into())548 }549}550551fn get_token_property<T: Config>(552 collection: &CollectionHandle<T>,553 token_id: u32,554 key: &up_data_structs::PropertyKey,555) -> Result<string> {556 collection.consume_store_reads(1)?;557 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))558 .map_err(|_| Error::Revert("Token properties not found".into()))?;559 if let Some(property) = properties.get(key) {560 return Ok(string::from_utf8_lossy(property).into());561 }562563 Err("Property tokenURI not found".into())564}565566fn get_token_permission<T: Config>(567 collection_id: CollectionId,568 key: &PropertyKey,569) -> Result<PropertyPermission> {570 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)571 .map_err(|_| Error::Revert("No permissions for collection".into()))?;572 let a = token_property_permissions573 .get(key)574 .map(Clone::clone)575 .ok_or_else(|| {576 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();577 Error::Revert(alloc::format!("No permission for key {}", key))578 })?;579 Ok(a)580}581582fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {583 if let Ok(token_property_permissions) =584 CollectionPropertyPermissions::<T>::try_get(collection_id)585 {586 return token_property_permissions.contains_key(key);587 }588589 false590}591592/// @title Unique extensions for ERC721.593#[solidity_interface(name = "ERC721UniqueExtensions")]594impl<T: Config> NonfungibleHandle<T> {595 /// @notice Transfer ownership of an NFT596 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`597 /// is the zero address. Throws if `tokenId` is not a valid NFT.598 /// @param to The new owner599 /// @param tokenId The NFT to transfer600 /// @param _value Not used for an NFT601 #[weight(<SelfWeightOf<T>>::transfer())]602 fn transfer(603 &mut self,604 caller: caller,605 to: address,606 token_id: uint256,607 _value: value,608 ) -> Result<void> {609 let caller = T::CrossAccountId::from_eth(caller);610 let to = T::CrossAccountId::from_eth(to);611 let token = token_id.try_into()?;612 let budget = self613 .recorder614 .weight_calls_budget(<StructureWeight<T>>::find_parent());615616 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;617 Ok(())618 }619620 /// @notice Burns a specific ERC721 token.621 /// @dev Throws unless `msg.sender` is the current owner or an authorized622 /// operator for this NFT. Throws if `from` is not the current owner. Throws623 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.624 /// @param from The current owner of the NFT625 /// @param tokenId The NFT to transfer626 /// @param _value Not used for an NFT627 #[weight(<SelfWeightOf<T>>::burn_from())]628 fn burn_from(629 &mut self,630 caller: caller,631 from: address,632 token_id: uint256,633 _value: value,634 ) -> Result<void> {635 let caller = T::CrossAccountId::from_eth(caller);636 let from = T::CrossAccountId::from_eth(from);637 let token = token_id.try_into()?;638 let budget = self639 .recorder640 .weight_calls_budget(<StructureWeight<T>>::find_parent());641642 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)643 .map_err(dispatch_to_evm::<T>)?;644 Ok(())645 }646647 /// @notice Returns next free NFT ID.648 fn next_token_id(&self) -> Result<uint256> {649 self.consume_store_reads(1)?;650 Ok(<TokensMinted<T>>::get(self.id)651 .checked_add(1)652 .ok_or("item id overflow")?653 .into())654 }655656 /// @notice Function to mint multiple tokens.657 /// @dev `tokenIds` should be an array of consecutive numbers and first number658 /// should be obtained with `nextTokenId` method659 /// @param to The new owner660 /// @param tokenIds IDs of the minted NFTs661 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]662 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {663 let caller = T::CrossAccountId::from_eth(caller);664 let to = T::CrossAccountId::from_eth(to);665 let mut expected_index = <TokensMinted<T>>::get(self.id)666 .checked_add(1)667 .ok_or("item id overflow")?;668 let budget = self669 .recorder670 .weight_calls_budget(<StructureWeight<T>>::find_parent());671672 let total_tokens = token_ids.len();673 for id in token_ids.into_iter() {674 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;675 if id != expected_index {676 return Err("item id should be next".into());677 }678 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;679 }680 let data = (0..total_tokens)681 .map(|_| CreateItemData::<T> {682 properties: BoundedVec::default(),683 owner: to.clone(),684 })685 .collect();686687 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)688 .map_err(dispatch_to_evm::<T>)?;689 Ok(true)690 }691692 /// @notice Function to mint multiple tokens with the given tokenUris.693 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive694 /// numbers and first number should be obtained with `nextTokenId` method695 /// @param to The new owner696 /// @param tokens array of pairs of token ID and token URI for minted tokens697 #[solidity(rename_selector = "mintBulkWithTokenURI")]698 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]699 fn mint_bulk_with_token_uri(700 &mut self,701 caller: caller,702 to: address,703 tokens: Vec<(uint256, string)>,704 ) -> Result<bool> {705 let key = u_key();706 let caller = T::CrossAccountId::from_eth(caller);707 let to = T::CrossAccountId::from_eth(to);708 let mut expected_index = <TokensMinted<T>>::get(self.id)709 .checked_add(1)710 .ok_or("item id overflow")?;711 let budget = self712 .recorder713 .weight_calls_budget(<StructureWeight<T>>::find_parent());714715 let mut data = Vec::with_capacity(tokens.len());716 for (id, token_uri) in tokens {717 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;718 if id != expected_index {719 return Err("item id should be next".into());720 }721 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;722723 let mut properties = CollectionPropertiesVec::default();724 properties725 .try_push(Property {726 key: key.clone(),727 value: token_uri728 .into_bytes()729 .try_into()730 .map_err(|_| "token uri is too long")?,731 })732 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;733734 data.push(CreateItemData::<T> {735 properties,736 owner: to.clone(),737 });738 }739740 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)741 .map_err(dispatch_to_evm::<T>)?;742 Ok(true)743 }744}745746#[solidity_interface(747 name = "UniqueNFT",748 is(749 ERC721,750 ERC721Metadata,751 ERC721Enumerable,752 ERC721UniqueExtensions,753 ERC721Mintable,754 ERC721Burnable,755 via("CollectionHandle<T>", common_mut, Collection),756 TokenProperties,757 )758)]759impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> {}760761// Not a tests, but code generators762generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);763generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);764765impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>766where767 T::AccountId: From<[u8; 32]>,768{769 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");770771 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {772 call::<T, UniqueNFTCall<T>, _, _>(handle, self)773 }774}