difftreelog
misk: * Add docs. * Detailed changelog. * Move lambd is_erc721 to separate function is_erc721_metadata_compatible.
in: master
3 files changed
pallets/common/CHANGELOG.MDdiffbeforeafterboth--- a/pallets/common/CHANGELOG.MD
+++ b/pallets/common/CHANGELOG.MD
@@ -2,14 +2,13 @@
All notable changes to this project will be documented in this file.
+## [0.1.3] - 2022-07-25
+### Add
+- Some static property keys and values.
+
## [0.1.2] - 2022-07-20
### Fixed
- Some methods in `#[solidity_interface]` for `CollectionHandle` had invalid
mutability modifiers, causing invalid stub/abi generation.
-
-
-## [0.1.3] - 2022-07-25
-### Add
-- Some static property keys and values.
\ No newline at end of file
pallets/nonfungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/nonfungible/CHANGELOG.md
+++ b/pallets/nonfungible/CHANGELOG.md
@@ -4,7 +4,14 @@
## [0.1.2] - 2022-07-25
### Changed
-- New alghoritm for retrieving `token_iri`.
+- New `token_uri` retrieval logic:
+
+ If the collection has a `url` property and it is not empty, it is returned.
+ 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`.
+
+ If the property `baseURI` is empty or absent, return "" (empty string)
+ otherwise, if property `suffix` present and is non-empty, return concatenation of baseURI and suffix
+ otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
## [0.1.1] - 2022-07-14
### Added
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 /// @dev Throws if `tokenId` is not a valid NFT. URIs are defined in RFC220 /// 3986. The URI may point to a JSON file that conforms to the "ERC721221 /// Metadata JSON Schema".222 /// @return token's const_metadata223 #[solidity(rename_selector = "tokenURI")]224 fn token_uri(&self, token_id: uint256) -> Result<string> {225 let is_erc721 = || {226 if let Some(shema_name) =227 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::schema_name())228 {229 let shema_name = shema_name.into_inner();230 shema_name == property_value::ERC721_METADATA231 } else {232 false233 }234 };235236 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;237238 if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {239 if !url.is_empty() {240 return Ok(url);241 }242 } else if !is_erc721() {243 return Err("tokenURI not set".into());244 }245246 if let Some(base_uri) =247 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())248 {249 if !base_uri.is_empty() {250 let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {251 Error::Revert(alloc::format!(252 "Can not convert value \"baseURI\" to string with error \"{}\"",253 e254 ))255 })?;256 if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {257 if !suffix.is_empty() {258 return Ok(base_uri + suffix.as_str());259 }260 }261262 return Ok(base_uri + token_id.to_string().as_str());263 }264 }265266 Ok("".into())267 }268}269270/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension271/// @dev See https://eips.ethereum.org/EIPS/eip-721272#[solidity_interface(name = "ERC721Enumerable")]273impl<T: Config> NonfungibleHandle<T> {274 /// @notice Enumerate valid NFTs275 /// @param index A counter less than `totalSupply()`276 /// @return The token identifier for the `index`th NFT,277 /// (sort order not specified)278 fn token_by_index(&self, index: uint256) -> Result<uint256> {279 Ok(index)280 }281282 /// @dev Not implemented283 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {284 // TODO: Not implemetable285 Err("not implemented".into())286 }287288 /// @notice Count NFTs tracked by this contract289 /// @return A count of valid NFTs tracked by this contract, where each one of290 /// them has an assigned and queryable owner not equal to the zero address291 fn total_supply(&self) -> Result<uint256> {292 self.consume_store_reads(1)?;293 Ok(<Pallet<T>>::total_supply(self).into())294 }295}296297/// @title ERC-721 Non-Fungible Token Standard298/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md299#[solidity_interface(name = "ERC721", events(ERC721Events))]300impl<T: Config> NonfungibleHandle<T> {301 /// @notice Count all NFTs assigned to an owner302 /// @dev NFTs assigned to the zero address are considered invalid, and this303 /// function throws for queries about the zero address.304 /// @param owner An address for whom to query the balance305 /// @return The number of NFTs owned by `owner`, possibly zero306 fn balance_of(&self, owner: address) -> Result<uint256> {307 self.consume_store_reads(1)?;308 let owner = T::CrossAccountId::from_eth(owner);309 let balance = <AccountBalance<T>>::get((self.id, owner));310 Ok(balance.into())311 }312 /// @notice Find the owner of an NFT313 /// @dev NFTs assigned to zero address are considered invalid, and queries314 /// about them do throw.315 /// @param tokenId The identifier for an NFT316 /// @return The address of the owner of the NFT317 fn owner_of(&self, token_id: uint256) -> Result<address> {318 self.consume_store_reads(1)?;319 let token: TokenId = token_id.try_into()?;320 Ok(*<TokenData<T>>::get((self.id, token))321 .ok_or("token not found")?322 .owner323 .as_eth())324 }325 /// @dev Not implemented326 fn safe_transfer_from_with_data(327 &mut self,328 _from: address,329 _to: address,330 _token_id: uint256,331 _data: bytes,332 _value: value,333 ) -> Result<void> {334 // TODO: Not implemetable335 Err("not implemented".into())336 }337 /// @dev Not implemented338 fn safe_transfer_from(339 &mut self,340 _from: address,341 _to: address,342 _token_id: uint256,343 _value: value,344 ) -> Result<void> {345 // TODO: Not implemetable346 Err("not implemented".into())347 }348349 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE350 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE351 /// THEY MAY BE PERMANENTLY LOST352 /// @dev Throws unless `msg.sender` is the current owner or an authorized353 /// operator for this NFT. Throws if `from` is not the current owner. Throws354 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.355 /// @param from The current owner of the NFT356 /// @param to The new owner357 /// @param tokenId The NFT to transfer358 /// @param _value Not used for an NFT359 #[weight(<SelfWeightOf<T>>::transfer_from())]360 fn transfer_from(361 &mut self,362 caller: caller,363 from: address,364 to: address,365 token_id: uint256,366 _value: value,367 ) -> Result<void> {368 let caller = T::CrossAccountId::from_eth(caller);369 let from = T::CrossAccountId::from_eth(from);370 let to = T::CrossAccountId::from_eth(to);371 let token = token_id.try_into()?;372 let budget = self373 .recorder374 .weight_calls_budget(<StructureWeight<T>>::find_parent());375376 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)377 .map_err(dispatch_to_evm::<T>)?;378 Ok(())379 }380381 /// @notice Set or reaffirm the approved address for an NFT382 /// @dev The zero address indicates there is no approved address.383 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized384 /// operator of the current owner.385 /// @param approved The new approved NFT controller386 /// @param tokenId The NFT to approve387 #[weight(<SelfWeightOf<T>>::approve())]388 fn approve(389 &mut self,390 caller: caller,391 approved: address,392 token_id: uint256,393 _value: value,394 ) -> Result<void> {395 let caller = T::CrossAccountId::from_eth(caller);396 let approved = T::CrossAccountId::from_eth(approved);397 let token = token_id.try_into()?;398399 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))400 .map_err(dispatch_to_evm::<T>)?;401 Ok(())402 }403404 /// @dev Not implemented405 fn set_approval_for_all(406 &mut self,407 _caller: caller,408 _operator: address,409 _approved: bool,410 ) -> Result<void> {411 // TODO: Not implemetable412 Err("not implemented".into())413 }414415 /// @dev Not implemented416 fn get_approved(&self, _token_id: uint256) -> Result<address> {417 // TODO: Not implemetable418 Err("not implemented".into())419 }420421 /// @dev Not implemented422 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {423 // TODO: Not implemetable424 Err("not implemented".into())425 }426}427428/// @title ERC721 Token that can be irreversibly burned (destroyed).429#[solidity_interface(name = "ERC721Burnable")]430impl<T: Config> NonfungibleHandle<T> {431 /// @notice Burns a specific ERC721 token.432 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized433 /// operator of the current owner.434 /// @param tokenId The NFT to approve435 #[weight(<SelfWeightOf<T>>::burn_item())]436 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {437 let caller = T::CrossAccountId::from_eth(caller);438 let token = token_id.try_into()?;439440 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;441 Ok(())442 }443}444445/// @title ERC721 minting logic.446#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]447impl<T: Config> NonfungibleHandle<T> {448 fn minting_finished(&self) -> Result<bool> {449 Ok(false)450 }451452 /// @notice Function to mint token.453 /// @dev `tokenId` should be obtained with `nextTokenId` method,454 /// unlike standard, you can't specify it manually455 /// @param to The new owner456 /// @param tokenId ID of the minted NFT457 #[weight(<SelfWeightOf<T>>::create_item())]458 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {459 let caller = T::CrossAccountId::from_eth(caller);460 let to = T::CrossAccountId::from_eth(to);461 let token_id: u32 = token_id.try_into()?;462 let budget = self463 .recorder464 .weight_calls_budget(<StructureWeight<T>>::find_parent());465466 if <TokensMinted<T>>::get(self.id)467 .checked_add(1)468 .ok_or("item id overflow")?469 != token_id470 {471 return Err("item id should be next".into());472 }473474 <Pallet<T>>::create_item(475 self,476 &caller,477 CreateItemData::<T> {478 properties: BoundedVec::default(),479 owner: to,480 },481 &budget,482 )483 .map_err(dispatch_to_evm::<T>)?;484485 Ok(true)486 }487488 /// @notice Function to mint token with the given tokenUri.489 /// @dev `tokenId` should be obtained with `nextTokenId` method,490 /// unlike standard, you can't specify it manually491 /// @param to The new owner492 /// @param tokenId ID of the minted NFT493 /// @param tokenUri Token URI that would be stored in the NFT properties494 #[solidity(rename_selector = "mintWithTokenURI")]495 #[weight(<SelfWeightOf<T>>::create_item())]496 fn mint_with_token_uri(497 &mut self,498 caller: caller,499 to: address,500 token_id: uint256,501 token_uri: string,502 ) -> Result<bool> {503 let key = key::url();504 let permission = get_token_permission::<T>(self.id, &key)?;505 if !permission.collection_admin {506 return Err("Operation is not allowed".into());507 }508509 let caller = T::CrossAccountId::from_eth(caller);510 let to = T::CrossAccountId::from_eth(to);511 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;512 let budget = self513 .recorder514 .weight_calls_budget(<StructureWeight<T>>::find_parent());515516 if <TokensMinted<T>>::get(self.id)517 .checked_add(1)518 .ok_or("item id overflow")?519 != token_id520 {521 return Err("item id should be next".into());522 }523524 let mut properties = CollectionPropertiesVec::default();525 properties526 .try_push(Property {527 key,528 value: token_uri529 .into_bytes()530 .try_into()531 .map_err(|_| "token uri is too long")?,532 })533 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;534535 <Pallet<T>>::create_item(536 self,537 &caller,538 CreateItemData::<T> {539 properties,540 owner: to,541 },542 &budget,543 )544 .map_err(dispatch_to_evm::<T>)?;545 Ok(true)546 }547548 /// @dev Not implemented549 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {550 Err("not implementable".into())551 }552}553554fn get_token_property<T: Config>(555 collection: &CollectionHandle<T>,556 token_id: u32,557 key: &up_data_structs::PropertyKey,558) -> Result<string> {559 collection.consume_store_reads(1)?;560 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))561 .map_err(|_| Error::Revert("Token properties not found".into()))?;562 if let Some(property) = properties.get(key) {563 return Ok(string::from_utf8_lossy(property).into());564 }565566 Err("Property tokenURI not found".into())567}568569fn get_token_permission<T: Config>(570 collection_id: CollectionId,571 key: &PropertyKey,572) -> Result<PropertyPermission> {573 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)574 .map_err(|_| Error::Revert("No permissions for collection".into()))?;575 let a = token_property_permissions576 .get(key)577 .map(Clone::clone)578 .ok_or_else(|| {579 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();580 Error::Revert(alloc::format!("No permission for key {}", key))581 })?;582 Ok(a)583}584585fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {586 if let Ok(token_property_permissions) =587 CollectionPropertyPermissions::<T>::try_get(collection_id)588 {589 return token_property_permissions.contains_key(key);590 }591592 false593}594595/// @title Unique extensions for ERC721.596#[solidity_interface(name = "ERC721UniqueExtensions")]597impl<T: Config> NonfungibleHandle<T> {598 /// @notice Transfer ownership of an NFT599 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`600 /// is the zero address. Throws if `tokenId` is not a valid NFT.601 /// @param to The new owner602 /// @param tokenId The NFT to transfer603 /// @param _value Not used for an NFT604 #[weight(<SelfWeightOf<T>>::transfer())]605 fn transfer(606 &mut self,607 caller: caller,608 to: address,609 token_id: uint256,610 _value: value,611 ) -> Result<void> {612 let caller = T::CrossAccountId::from_eth(caller);613 let to = T::CrossAccountId::from_eth(to);614 let token = token_id.try_into()?;615 let budget = self616 .recorder617 .weight_calls_budget(<StructureWeight<T>>::find_parent());618619 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;620 Ok(())621 }622623 /// @notice Burns a specific ERC721 token.624 /// @dev Throws unless `msg.sender` is the current owner or an authorized625 /// operator for this NFT. Throws if `from` is not the current owner. Throws626 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.627 /// @param from The current owner of the NFT628 /// @param tokenId The NFT to transfer629 /// @param _value Not used for an NFT630 #[weight(<SelfWeightOf<T>>::burn_from())]631 fn burn_from(632 &mut self,633 caller: caller,634 from: address,635 token_id: uint256,636 _value: value,637 ) -> Result<void> {638 let caller = T::CrossAccountId::from_eth(caller);639 let from = T::CrossAccountId::from_eth(from);640 let token = token_id.try_into()?;641 let budget = self642 .recorder643 .weight_calls_budget(<StructureWeight<T>>::find_parent());644645 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)646 .map_err(dispatch_to_evm::<T>)?;647 Ok(())648 }649650 /// @notice Returns next free NFT ID.651 fn next_token_id(&self) -> Result<uint256> {652 self.consume_store_reads(1)?;653 Ok(<TokensMinted<T>>::get(self.id)654 .checked_add(1)655 .ok_or("item id overflow")?656 .into())657 }658659 /// @notice Function to mint multiple tokens.660 /// @dev `tokenIds` should be an array of consecutive numbers and first number661 /// should be obtained with `nextTokenId` method662 /// @param to The new owner663 /// @param tokenIds IDs of the minted NFTs664 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]665 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {666 let caller = T::CrossAccountId::from_eth(caller);667 let to = T::CrossAccountId::from_eth(to);668 let mut expected_index = <TokensMinted<T>>::get(self.id)669 .checked_add(1)670 .ok_or("item id overflow")?;671 let budget = self672 .recorder673 .weight_calls_budget(<StructureWeight<T>>::find_parent());674675 let total_tokens = token_ids.len();676 for id in token_ids.into_iter() {677 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;678 if id != expected_index {679 return Err("item id should be next".into());680 }681 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;682 }683 let data = (0..total_tokens)684 .map(|_| CreateItemData::<T> {685 properties: BoundedVec::default(),686 owner: to.clone(),687 })688 .collect();689690 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)691 .map_err(dispatch_to_evm::<T>)?;692 Ok(true)693 }694695 /// @notice Function to mint multiple tokens with the given tokenUris.696 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive697 /// numbers and first number should be obtained with `nextTokenId` method698 /// @param to The new owner699 /// @param tokens array of pairs of token ID and token URI for minted tokens700 #[solidity(rename_selector = "mintBulkWithTokenURI")]701 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]702 fn mint_bulk_with_token_uri(703 &mut self,704 caller: caller,705 to: address,706 tokens: Vec<(uint256, string)>,707 ) -> Result<bool> {708 let key = key::url();709 let caller = T::CrossAccountId::from_eth(caller);710 let to = T::CrossAccountId::from_eth(to);711 let mut expected_index = <TokensMinted<T>>::get(self.id)712 .checked_add(1)713 .ok_or("item id overflow")?;714 let budget = self715 .recorder716 .weight_calls_budget(<StructureWeight<T>>::find_parent());717718 let mut data = Vec::with_capacity(tokens.len());719 for (id, token_uri) in tokens {720 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;721 if id != expected_index {722 return Err("item id should be next".into());723 }724 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;725726 let mut properties = CollectionPropertiesVec::default();727 properties728 .try_push(Property {729 key: key.clone(),730 value: token_uri731 .into_bytes()732 .try_into()733 .map_err(|_| "token uri is too long")?,734 })735 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;736737 data.push(CreateItemData::<T> {738 properties,739 owner: to.clone(),740 });741 }742743 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)744 .map_err(dispatch_to_evm::<T>)?;745 Ok(true)746 }747}748749#[solidity_interface(750 name = "UniqueNFT",751 is(752 ERC721,753 ERC721Metadata,754 ERC721Enumerable,755 ERC721UniqueExtensions,756 ERC721Mintable,757 ERC721Burnable,758 via("CollectionHandle<T>", common_mut, Collection),759 TokenProperties,760 )761)]762impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> {}763764// Not a tests, but code generators765generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);766generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);767768impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>769where770 T::AccountId: From<[u8; 32]>,771{772 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");773774 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {775 call::<T, UniqueNFTCall<T>, _, _>(handle, self)776 }777}