difftreelog
misk: fix pr
in: master
1 file changed
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 is_mutable Permission to mutate property.59 /// @param collection_admin Permission to mutate property by collection admin if property is mutable.60 /// @param token_owner 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")]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 collection 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 ///223 /// If the property `baseURI` is empty or absent, return "" (empty string)224 /// otherwise, if property `suffix` present and is non-empty, return concatenation of baseURI and suffix225 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).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")]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))]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 fn safe_transfer_from_with_data(320 &mut self,321 _from: address,322 _to: address,323 _token_id: uint256,324 _data: bytes,325 _value: value,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 _value: value,337 ) -> Result<void> {338 // TODO: Not implemetable339 Err("not implemented".into())340 }341342 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE343 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE344 /// THEY MAY BE PERMANENTLY LOST345 /// @dev Throws unless `msg.sender` is the current owner or an authorized346 /// operator for this NFT. Throws if `from` is not the current owner. Throws347 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.348 /// @param from The current owner of the NFT349 /// @param to The new owner350 /// @param tokenId The NFT to transfer351 /// @param _value Not used for an NFT352 #[weight(<SelfWeightOf<T>>::transfer_from())]353 fn transfer_from(354 &mut self,355 caller: caller,356 from: address,357 to: address,358 token_id: uint256,359 _value: value,360 ) -> Result<void> {361 let caller = T::CrossAccountId::from_eth(caller);362 let from = T::CrossAccountId::from_eth(from);363 let to = T::CrossAccountId::from_eth(to);364 let token = token_id.try_into()?;365 let budget = self366 .recorder367 .weight_calls_budget(<StructureWeight<T>>::find_parent());368369 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)370 .map_err(dispatch_to_evm::<T>)?;371 Ok(())372 }373374 /// @notice Set or reaffirm the approved address for an NFT375 /// @dev The zero address indicates there is no approved address.376 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized377 /// operator of the current owner.378 /// @param approved The new approved NFT controller379 /// @param tokenId The NFT to approve380 #[weight(<SelfWeightOf<T>>::approve())]381 fn approve(382 &mut self,383 caller: caller,384 approved: address,385 token_id: uint256,386 _value: value,387 ) -> Result<void> {388 let caller = T::CrossAccountId::from_eth(caller);389 let approved = T::CrossAccountId::from_eth(approved);390 let token = token_id.try_into()?;391392 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))393 .map_err(dispatch_to_evm::<T>)?;394 Ok(())395 }396397 /// @dev Not implemented398 fn set_approval_for_all(399 &mut self,400 _caller: caller,401 _operator: address,402 _approved: bool,403 ) -> Result<void> {404 // TODO: Not implemetable405 Err("not implemented".into())406 }407408 /// @dev Not implemented409 fn get_approved(&self, _token_id: uint256) -> Result<address> {410 // TODO: Not implemetable411 Err("not implemented".into())412 }413414 /// @dev Not implemented415 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {416 // TODO: Not implemetable417 Err("not implemented".into())418 }419}420421/// @title ERC721 Token that can be irreversibly burned (destroyed).422#[solidity_interface(name = "ERC721Burnable")]423impl<T: Config> NonfungibleHandle<T> {424 /// @notice Burns a specific ERC721 token.425 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized426 /// operator of the current owner.427 /// @param tokenId The NFT to approve428 #[weight(<SelfWeightOf<T>>::burn_item())]429 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {430 let caller = T::CrossAccountId::from_eth(caller);431 let token = token_id.try_into()?;432433 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;434 Ok(())435 }436}437438/// @title ERC721 minting logic.439#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]440impl<T: Config> NonfungibleHandle<T> {441 fn minting_finished(&self) -> Result<bool> {442 Ok(false)443 }444445 /// @notice Function to mint token.446 /// @dev `tokenId` should be obtained with `nextTokenId` method,447 /// unlike standard, you can't specify it manually448 /// @param to The new owner449 /// @param tokenId ID of the minted NFT450 #[weight(<SelfWeightOf<T>>::create_item())]451 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {452 let caller = T::CrossAccountId::from_eth(caller);453 let to = T::CrossAccountId::from_eth(to);454 let token_id: u32 = token_id.try_into()?;455 let budget = self456 .recorder457 .weight_calls_budget(<StructureWeight<T>>::find_parent());458459 if <TokensMinted<T>>::get(self.id)460 .checked_add(1)461 .ok_or("item id overflow")?462 != token_id463 {464 return Err("item id should be next".into());465 }466467 <Pallet<T>>::create_item(468 self,469 &caller,470 CreateItemData::<T> {471 properties: BoundedVec::default(),472 owner: to,473 },474 &budget,475 )476 .map_err(dispatch_to_evm::<T>)?;477478 Ok(true)479 }480481 /// @notice Function to mint token with the given tokenUri.482 /// @dev `tokenId` should be obtained with `nextTokenId` method,483 /// unlike standard, you can't specify it manually484 /// @param to The new owner485 /// @param tokenId ID of the minted NFT486 /// @param tokenUri Token URI that would be stored in the NFT properties487 #[solidity(rename_selector = "mintWithTokenURI")]488 #[weight(<SelfWeightOf<T>>::create_item())]489 fn mint_with_token_uri(490 &mut self,491 caller: caller,492 to: address,493 token_id: uint256,494 token_uri: string,495 ) -> Result<bool> {496 let key = key::url();497 let permission = get_token_permission::<T>(self.id, &key)?;498 if !permission.collection_admin {499 return Err("Operation is not allowed".into());500 }501502 let caller = T::CrossAccountId::from_eth(caller);503 let to = T::CrossAccountId::from_eth(to);504 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;505 let budget = self506 .recorder507 .weight_calls_budget(<StructureWeight<T>>::find_parent());508509 if <TokensMinted<T>>::get(self.id)510 .checked_add(1)511 .ok_or("item id overflow")?512 != token_id513 {514 return Err("item id should be next".into());515 }516517 let mut properties = CollectionPropertiesVec::default();518 properties519 .try_push(Property {520 key,521 value: token_uri522 .into_bytes()523 .try_into()524 .map_err(|_| "token uri is too long")?,525 })526 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;527528 <Pallet<T>>::create_item(529 self,530 &caller,531 CreateItemData::<T> {532 properties,533 owner: to,534 },535 &budget,536 )537 .map_err(dispatch_to_evm::<T>)?;538 Ok(true)539 }540541 /// @dev Not implemented542 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {543 Err("not implementable".into())544 }545}546547fn get_token_property<T: Config>(548 collection: &CollectionHandle<T>,549 token_id: u32,550 key: &up_data_structs::PropertyKey,551) -> Result<string> {552 collection.consume_store_reads(1)?;553 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))554 .map_err(|_| Error::Revert("Token properties not found".into()))?;555 if let Some(property) = properties.get(key) {556 return Ok(string::from_utf8_lossy(property).into());557 }558559 Err("Property tokenURI not found".into())560}561562fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {563 if let Some(shema_name) =564 pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())565 {566 let shema_name = shema_name.into_inner();567 shema_name == property_value::ERC721_METADATA568 } else {569 false570 }571}572573fn get_token_permission<T: Config>(574 collection_id: CollectionId,575 key: &PropertyKey,576) -> Result<PropertyPermission> {577 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)578 .map_err(|_| Error::Revert("No permissions for collection".into()))?;579 let a = token_property_permissions580 .get(key)581 .map(Clone::clone)582 .ok_or_else(|| {583 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();584 Error::Revert(alloc::format!("No permission for key {}", key))585 })?;586 Ok(a)587}588589fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {590 if let Ok(token_property_permissions) =591 CollectionPropertyPermissions::<T>::try_get(collection_id)592 {593 return token_property_permissions.contains_key(key);594 }595596 false597}598599/// @title Unique extensions for ERC721.600#[solidity_interface(name = "ERC721UniqueExtensions")]601impl<T: Config> NonfungibleHandle<T> {602 /// @notice Transfer ownership of an NFT603 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`604 /// is the zero address. Throws if `tokenId` is not a valid NFT.605 /// @param to The new owner606 /// @param tokenId The NFT to transfer607 /// @param _value Not used for an NFT608 #[weight(<SelfWeightOf<T>>::transfer())]609 fn transfer(610 &mut self,611 caller: caller,612 to: address,613 token_id: uint256,614 _value: value,615 ) -> Result<void> {616 let caller = T::CrossAccountId::from_eth(caller);617 let to = T::CrossAccountId::from_eth(to);618 let token = token_id.try_into()?;619 let budget = self620 .recorder621 .weight_calls_budget(<StructureWeight<T>>::find_parent());622623 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;624 Ok(())625 }626627 /// @notice Burns a specific ERC721 token.628 /// @dev Throws unless `msg.sender` is the current owner or an authorized629 /// operator for this NFT. Throws if `from` is not the current owner. Throws630 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.631 /// @param from The current owner of the NFT632 /// @param tokenId The NFT to transfer633 /// @param _value Not used for an NFT634 #[weight(<SelfWeightOf<T>>::burn_from())]635 fn burn_from(636 &mut self,637 caller: caller,638 from: address,639 token_id: uint256,640 _value: value,641 ) -> Result<void> {642 let caller = T::CrossAccountId::from_eth(caller);643 let from = T::CrossAccountId::from_eth(from);644 let token = token_id.try_into()?;645 let budget = self646 .recorder647 .weight_calls_budget(<StructureWeight<T>>::find_parent());648649 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)650 .map_err(dispatch_to_evm::<T>)?;651 Ok(())652 }653654 /// @notice Returns next free NFT ID.655 fn next_token_id(&self) -> Result<uint256> {656 self.consume_store_reads(1)?;657 Ok(<TokensMinted<T>>::get(self.id)658 .checked_add(1)659 .ok_or("item id overflow")?660 .into())661 }662663 /// @notice Function to mint multiple tokens.664 /// @dev `tokenIds` should be an array of consecutive numbers and first number665 /// should be obtained with `nextTokenId` method666 /// @param to The new owner667 /// @param tokenIds IDs of the minted NFTs668 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]669 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {670 let caller = T::CrossAccountId::from_eth(caller);671 let to = T::CrossAccountId::from_eth(to);672 let mut expected_index = <TokensMinted<T>>::get(self.id)673 .checked_add(1)674 .ok_or("item id overflow")?;675 let budget = self676 .recorder677 .weight_calls_budget(<StructureWeight<T>>::find_parent());678679 let total_tokens = token_ids.len();680 for id in token_ids.into_iter() {681 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;682 if id != expected_index {683 return Err("item id should be next".into());684 }685 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;686 }687 let data = (0..total_tokens)688 .map(|_| CreateItemData::<T> {689 properties: BoundedVec::default(),690 owner: to.clone(),691 })692 .collect();693694 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)695 .map_err(dispatch_to_evm::<T>)?;696 Ok(true)697 }698699 /// @notice Function to mint multiple tokens with the given tokenUris.700 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive701 /// numbers and first number should be obtained with `nextTokenId` method702 /// @param to The new owner703 /// @param tokens array of pairs of token ID and token URI for minted tokens704 #[solidity(rename_selector = "mintBulkWithTokenURI")]705 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]706 fn mint_bulk_with_token_uri(707 &mut self,708 caller: caller,709 to: address,710 tokens: Vec<(uint256, string)>,711 ) -> Result<bool> {712 let key = key::url();713 let caller = T::CrossAccountId::from_eth(caller);714 let to = T::CrossAccountId::from_eth(to);715 let mut expected_index = <TokensMinted<T>>::get(self.id)716 .checked_add(1)717 .ok_or("item id overflow")?;718 let budget = self719 .recorder720 .weight_calls_budget(<StructureWeight<T>>::find_parent());721722 let mut data = Vec::with_capacity(tokens.len());723 for (id, token_uri) in tokens {724 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;725 if id != expected_index {726 return Err("item id should be next".into());727 }728 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;729730 let mut properties = CollectionPropertiesVec::default();731 properties732 .try_push(Property {733 key: key.clone(),734 value: token_uri735 .into_bytes()736 .try_into()737 .map_err(|_| "token uri is too long")?,738 })739 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;740741 data.push(CreateItemData::<T> {742 properties,743 owner: to.clone(),744 });745 }746747 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)748 .map_err(dispatch_to_evm::<T>)?;749 Ok(true)750 }751}752753#[solidity_interface(754 name = "UniqueNFT",755 is(756 ERC721,757 ERC721Metadata,758 ERC721Enumerable,759 ERC721UniqueExtensions,760 ERC721Mintable,761 ERC721Burnable,762 via("CollectionHandle<T>", common_mut, Collection),763 TokenProperties,764 )765)]766impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> {}767768// Not a tests, but code generators769generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);770generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);771772impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>773where774 T::AccountId: From<[u8; 32]>,775{776 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");777778 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {779 call::<T, UniqueNFTCall<T>, _, _>(handle, self)780 }781}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 is_mutable Permission to mutate property.59 /// @param collection_admin Permission to mutate property by collection admin if property is mutable.60 /// @param token_owner 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")]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 collection 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 property `baseURI` is empty or absent, return "" (empty string)223 /// otherwise, if 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")]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))]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 fn safe_transfer_from_with_data(320 &mut self,321 _from: address,322 _to: address,323 _token_id: uint256,324 _data: bytes,325 _value: value,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 _value: value,337 ) -> Result<void> {338 // TODO: Not implemetable339 Err("not implemented".into())340 }341342 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE343 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE344 /// THEY MAY BE PERMANENTLY LOST345 /// @dev Throws unless `msg.sender` is the current owner or an authorized346 /// operator for this NFT. Throws if `from` is not the current owner. Throws347 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.348 /// @param from The current owner of the NFT349 /// @param to The new owner350 /// @param tokenId The NFT to transfer351 /// @param _value Not used for an NFT352 #[weight(<SelfWeightOf<T>>::transfer_from())]353 fn transfer_from(354 &mut self,355 caller: caller,356 from: address,357 to: address,358 token_id: uint256,359 _value: value,360 ) -> Result<void> {361 let caller = T::CrossAccountId::from_eth(caller);362 let from = T::CrossAccountId::from_eth(from);363 let to = T::CrossAccountId::from_eth(to);364 let token = token_id.try_into()?;365 let budget = self366 .recorder367 .weight_calls_budget(<StructureWeight<T>>::find_parent());368369 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)370 .map_err(dispatch_to_evm::<T>)?;371 Ok(())372 }373374 /// @notice Set or reaffirm the approved address for an NFT375 /// @dev The zero address indicates there is no approved address.376 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized377 /// operator of the current owner.378 /// @param approved The new approved NFT controller379 /// @param tokenId The NFT to approve380 #[weight(<SelfWeightOf<T>>::approve())]381 fn approve(382 &mut self,383 caller: caller,384 approved: address,385 token_id: uint256,386 _value: value,387 ) -> Result<void> {388 let caller = T::CrossAccountId::from_eth(caller);389 let approved = T::CrossAccountId::from_eth(approved);390 let token = token_id.try_into()?;391392 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))393 .map_err(dispatch_to_evm::<T>)?;394 Ok(())395 }396397 /// @dev Not implemented398 fn set_approval_for_all(399 &mut self,400 _caller: caller,401 _operator: address,402 _approved: bool,403 ) -> Result<void> {404 // TODO: Not implemetable405 Err("not implemented".into())406 }407408 /// @dev Not implemented409 fn get_approved(&self, _token_id: uint256) -> Result<address> {410 // TODO: Not implemetable411 Err("not implemented".into())412 }413414 /// @dev Not implemented415 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {416 // TODO: Not implemetable417 Err("not implemented".into())418 }419}420421/// @title ERC721 Token that can be irreversibly burned (destroyed).422#[solidity_interface(name = "ERC721Burnable")]423impl<T: Config> NonfungibleHandle<T> {424 /// @notice Burns a specific ERC721 token.425 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized426 /// operator of the current owner.427 /// @param tokenId The NFT to approve428 #[weight(<SelfWeightOf<T>>::burn_item())]429 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {430 let caller = T::CrossAccountId::from_eth(caller);431 let token = token_id.try_into()?;432433 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;434 Ok(())435 }436}437438/// @title ERC721 minting logic.439#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]440impl<T: Config> NonfungibleHandle<T> {441 fn minting_finished(&self) -> Result<bool> {442 Ok(false)443 }444445 /// @notice Function to mint token.446 /// @dev `tokenId` should be obtained with `nextTokenId` method,447 /// unlike standard, you can't specify it manually448 /// @param to The new owner449 /// @param tokenId ID of the minted NFT450 #[weight(<SelfWeightOf<T>>::create_item())]451 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {452 let caller = T::CrossAccountId::from_eth(caller);453 let to = T::CrossAccountId::from_eth(to);454 let token_id: u32 = token_id.try_into()?;455 let budget = self456 .recorder457 .weight_calls_budget(<StructureWeight<T>>::find_parent());458459 if <TokensMinted<T>>::get(self.id)460 .checked_add(1)461 .ok_or("item id overflow")?462 != token_id463 {464 return Err("item id should be next".into());465 }466467 <Pallet<T>>::create_item(468 self,469 &caller,470 CreateItemData::<T> {471 properties: BoundedVec::default(),472 owner: to,473 },474 &budget,475 )476 .map_err(dispatch_to_evm::<T>)?;477478 Ok(true)479 }480481 /// @notice Function to mint token with the given tokenUri.482 /// @dev `tokenId` should be obtained with `nextTokenId` method,483 /// unlike standard, you can't specify it manually484 /// @param to The new owner485 /// @param tokenId ID of the minted NFT486 /// @param tokenUri Token URI that would be stored in the NFT properties487 #[solidity(rename_selector = "mintWithTokenURI")]488 #[weight(<SelfWeightOf<T>>::create_item())]489 fn mint_with_token_uri(490 &mut self,491 caller: caller,492 to: address,493 token_id: uint256,494 token_uri: string,495 ) -> Result<bool> {496 let key = key::url();497 let permission = get_token_permission::<T>(self.id, &key)?;498 if !permission.collection_admin {499 return Err("Operation is not allowed".into());500 }501502 let caller = T::CrossAccountId::from_eth(caller);503 let to = T::CrossAccountId::from_eth(to);504 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;505 let budget = self506 .recorder507 .weight_calls_budget(<StructureWeight<T>>::find_parent());508509 if <TokensMinted<T>>::get(self.id)510 .checked_add(1)511 .ok_or("item id overflow")?512 != token_id513 {514 return Err("item id should be next".into());515 }516517 let mut properties = CollectionPropertiesVec::default();518 properties519 .try_push(Property {520 key,521 value: token_uri522 .into_bytes()523 .try_into()524 .map_err(|_| "token uri is too long")?,525 })526 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;527528 <Pallet<T>>::create_item(529 self,530 &caller,531 CreateItemData::<T> {532 properties,533 owner: to,534 },535 &budget,536 )537 .map_err(dispatch_to_evm::<T>)?;538 Ok(true)539 }540541 /// @dev Not implemented542 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {543 Err("not implementable".into())544 }545}546547fn get_token_property<T: Config>(548 collection: &CollectionHandle<T>,549 token_id: u32,550 key: &up_data_structs::PropertyKey,551) -> Result<string> {552 collection.consume_store_reads(1)?;553 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))554 .map_err(|_| Error::Revert("Token properties not found".into()))?;555 if let Some(property) = properties.get(key) {556 return Ok(string::from_utf8_lossy(property).into());557 }558559 Err("Property tokenURI not found".into())560}561562fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {563 if let Some(shema_name) =564 pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())565 {566 let shema_name = shema_name.into_inner();567 shema_name == property_value::ERC721_METADATA568 } else {569 false570 }571}572573fn get_token_permission<T: Config>(574 collection_id: CollectionId,575 key: &PropertyKey,576) -> Result<PropertyPermission> {577 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)578 .map_err(|_| Error::Revert("No permissions for collection".into()))?;579 let a = token_property_permissions580 .get(key)581 .map(Clone::clone)582 .ok_or_else(|| {583 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();584 Error::Revert(alloc::format!("No permission for key {}", key))585 })?;586 Ok(a)587}588589fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {590 if let Ok(token_property_permissions) =591 CollectionPropertyPermissions::<T>::try_get(collection_id)592 {593 return token_property_permissions.contains_key(key);594 }595596 false597}598599/// @title Unique extensions for ERC721.600#[solidity_interface(name = "ERC721UniqueExtensions")]601impl<T: Config> NonfungibleHandle<T> {602 /// @notice Transfer ownership of an NFT603 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`604 /// is the zero address. Throws if `tokenId` is not a valid NFT.605 /// @param to The new owner606 /// @param tokenId The NFT to transfer607 /// @param _value Not used for an NFT608 #[weight(<SelfWeightOf<T>>::transfer())]609 fn transfer(610 &mut self,611 caller: caller,612 to: address,613 token_id: uint256,614 _value: value,615 ) -> Result<void> {616 let caller = T::CrossAccountId::from_eth(caller);617 let to = T::CrossAccountId::from_eth(to);618 let token = token_id.try_into()?;619 let budget = self620 .recorder621 .weight_calls_budget(<StructureWeight<T>>::find_parent());622623 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;624 Ok(())625 }626627 /// @notice Burns a specific ERC721 token.628 /// @dev Throws unless `msg.sender` is the current owner or an authorized629 /// operator for this NFT. Throws if `from` is not the current owner. Throws630 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.631 /// @param from The current owner of the NFT632 /// @param tokenId The NFT to transfer633 /// @param _value Not used for an NFT634 #[weight(<SelfWeightOf<T>>::burn_from())]635 fn burn_from(636 &mut self,637 caller: caller,638 from: address,639 token_id: uint256,640 _value: value,641 ) -> Result<void> {642 let caller = T::CrossAccountId::from_eth(caller);643 let from = T::CrossAccountId::from_eth(from);644 let token = token_id.try_into()?;645 let budget = self646 .recorder647 .weight_calls_budget(<StructureWeight<T>>::find_parent());648649 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)650 .map_err(dispatch_to_evm::<T>)?;651 Ok(())652 }653654 /// @notice Returns next free NFT ID.655 fn next_token_id(&self) -> Result<uint256> {656 self.consume_store_reads(1)?;657 Ok(<TokensMinted<T>>::get(self.id)658 .checked_add(1)659 .ok_or("item id overflow")?660 .into())661 }662663 /// @notice Function to mint multiple tokens.664 /// @dev `tokenIds` should be an array of consecutive numbers and first number665 /// should be obtained with `nextTokenId` method666 /// @param to The new owner667 /// @param tokenIds IDs of the minted NFTs668 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]669 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {670 let caller = T::CrossAccountId::from_eth(caller);671 let to = T::CrossAccountId::from_eth(to);672 let mut expected_index = <TokensMinted<T>>::get(self.id)673 .checked_add(1)674 .ok_or("item id overflow")?;675 let budget = self676 .recorder677 .weight_calls_budget(<StructureWeight<T>>::find_parent());678679 let total_tokens = token_ids.len();680 for id in token_ids.into_iter() {681 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;682 if id != expected_index {683 return Err("item id should be next".into());684 }685 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;686 }687 let data = (0..total_tokens)688 .map(|_| CreateItemData::<T> {689 properties: BoundedVec::default(),690 owner: to.clone(),691 })692 .collect();693694 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)695 .map_err(dispatch_to_evm::<T>)?;696 Ok(true)697 }698699 /// @notice Function to mint multiple tokens with the given tokenUris.700 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive701 /// numbers and first number should be obtained with `nextTokenId` method702 /// @param to The new owner703 /// @param tokens array of pairs of token ID and token URI for minted tokens704 #[solidity(rename_selector = "mintBulkWithTokenURI")]705 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]706 fn mint_bulk_with_token_uri(707 &mut self,708 caller: caller,709 to: address,710 tokens: Vec<(uint256, string)>,711 ) -> Result<bool> {712 let key = key::url();713 let caller = T::CrossAccountId::from_eth(caller);714 let to = T::CrossAccountId::from_eth(to);715 let mut expected_index = <TokensMinted<T>>::get(self.id)716 .checked_add(1)717 .ok_or("item id overflow")?;718 let budget = self719 .recorder720 .weight_calls_budget(<StructureWeight<T>>::find_parent());721722 let mut data = Vec::with_capacity(tokens.len());723 for (id, token_uri) in tokens {724 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;725 if id != expected_index {726 return Err("item id should be next".into());727 }728 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;729730 let mut properties = CollectionPropertiesVec::default();731 properties732 .try_push(Property {733 key: key.clone(),734 value: token_uri735 .into_bytes()736 .try_into()737 .map_err(|_| "token uri is too long")?,738 })739 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;740741 data.push(CreateItemData::<T> {742 properties,743 owner: to.clone(),744 });745 }746747 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)748 .map_err(dispatch_to_evm::<T>)?;749 Ok(true)750 }751}752753#[solidity_interface(754 name = "UniqueNFT",755 is(756 ERC721,757 ERC721Metadata,758 ERC721Enumerable,759 ERC721UniqueExtensions,760 ERC721Mintable,761 ERC721Burnable,762 via("CollectionHandle<T>", common_mut, Collection),763 TokenProperties,764 )765)]766impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> {}767768// Not a tests, but code generators769generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);770generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);771772impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>773where774 T::AccountId: From<[u8; 32]>,775{776 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");777778 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {779 call::<T, UniqueNFTCall<T>, _, _>(handle, self)780 }781}