difftreelog
chore code review requests
in: master
20 files 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 isMutable Permission to mutate property.59 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.60 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.61 fn set_token_property_permission(62 &mut self,63 caller: caller,64 key: string,65 is_mutable: bool,66 collection_admin: bool,67 token_owner: bool,68 ) -> Result<()> {69 let caller = T::CrossAccountId::from_eth(caller);70 <Pallet<T>>::set_property_permission(71 self,72 &caller,73 PropertyKeyPermission {74 key: <Vec<u8>>::from(key)75 .try_into()76 .map_err(|_| "too long key")?,77 permission: PropertyPermission {78 mutable: is_mutable,79 collection_admin,80 token_owner,81 },82 },83 )84 .map_err(dispatch_to_evm::<T>)85 }8687 /// @notice Set token property value.88 /// @dev Throws error if `msg.sender` has no permission to edit the property.89 /// @param tokenId ID of the token.90 /// @param key Property key.91 /// @param value Property value.92 fn set_property(93 &mut self,94 caller: caller,95 token_id: uint256,96 key: string,97 value: bytes,98 ) -> Result<()> {99 let caller = T::CrossAccountId::from_eth(caller);100 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;101 let key = <Vec<u8>>::from(key)102 .try_into()103 .map_err(|_| "key too long")?;104 let value = value.try_into().map_err(|_| "value too long")?;105106 let nesting_budget = self107 .recorder108 .weight_calls_budget(<StructureWeight<T>>::find_parent());109110 <Pallet<T>>::set_token_property(111 self,112 &caller,113 TokenId(token_id),114 Property { key, value },115 &nesting_budget,116 )117 .map_err(dispatch_to_evm::<T>)118 }119120 /// @notice Delete token property value.121 /// @dev Throws error if `msg.sender` has no permission to edit the property.122 /// @param tokenId ID of the token.123 /// @param key Property key.124 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {125 let caller = T::CrossAccountId::from_eth(caller);126 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;127 let key = <Vec<u8>>::from(key)128 .try_into()129 .map_err(|_| "key too long")?;130131 let nesting_budget = self132 .recorder133 .weight_calls_budget(<StructureWeight<T>>::find_parent());134135 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)136 .map_err(dispatch_to_evm::<T>)137 }138139 /// @notice Get token property value.140 /// @dev Throws error if key not found141 /// @param tokenId ID of the token.142 /// @param key Property key.143 /// @return Property value bytes144 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {145 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;146 let key = <Vec<u8>>::from(key)147 .try_into()148 .map_err(|_| "key too long")?;149150 let props = <TokenProperties<T>>::get((self.id, token_id));151 let prop = props.get(&key).ok_or("key not found")?;152153 Ok(prop.to_vec())154 }155}156157#[derive(ToLog)]158pub enum ERC721Events {159 /// @dev This emits when ownership of any NFT changes by any mechanism.160 /// This event emits when NFTs are created (`from` == 0) and destroyed161 /// (`to` == 0). Exception: during contract creation, any number of NFTs162 /// may be created and assigned without emitting Transfer. At the time of163 /// any transfer, the approved address for that NFT (if any) is reset to none.164 Transfer {165 #[indexed]166 from: address,167 #[indexed]168 to: address,169 #[indexed]170 token_id: uint256,171 },172 /// @dev This emits when the approved address for an NFT is changed or173 /// reaffirmed. The zero address indicates there is no approved address.174 /// When a Transfer event emits, this also indicates that the approved175 /// address for that NFT (if any) is reset to none.176 Approval {177 #[indexed]178 owner: address,179 #[indexed]180 approved: address,181 #[indexed]182 token_id: uint256,183 },184 /// @dev This emits when an operator is enabled or disabled for an owner.185 /// The operator can manage all NFTs of the owner.186 #[allow(dead_code)]187 ApprovalForAll {188 #[indexed]189 owner: address,190 #[indexed]191 operator: address,192 approved: bool,193 },194}195196#[derive(ToLog)]197pub enum ERC721MintableEvents {198 #[allow(dead_code)]199 MintingFinished {},200}201202/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension203/// @dev See https://eips.ethereum.org/EIPS/eip-721204#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]205impl<T: Config> NonfungibleHandle<T> {206 /// @notice A descriptive name for a collection of NFTs in this contract207 fn name(&self) -> Result<string> {208 Ok(decode_utf16(self.name.iter().copied())209 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))210 .collect::<string>())211 }212213 /// @notice An abbreviated name for NFTs in this contract214 fn symbol(&self) -> Result<string> {215 Ok(string::from_utf8_lossy(&self.token_prefix).into())216 }217218 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.219 ///220 /// @dev If the token has a `url` property and it is not empty, it is returned.221 /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.222 /// If the collection property `baseURI` is empty or absent, return "" (empty string)223 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix224 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).225 ///226 /// @return token's const_metadata227 #[solidity(rename_selector = "tokenURI")]228 fn token_uri(&self, token_id: uint256) -> Result<string> {229 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;230231 if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {232 if !url.is_empty() {233 return Ok(url);234 }235 } else if !self.supports_metadata() {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);256 }257 }258259 Ok("".into())260 }261}262263/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension264/// @dev See https://eips.ethereum.org/EIPS/eip-721265#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]266impl<T: Config> NonfungibleHandle<T> {267 /// @notice Enumerate valid NFTs268 /// @param index A counter less than `totalSupply()`269 /// @return The token identifier for the `index`th NFT,270 /// (sort order not specified)271 fn token_by_index(&self, index: uint256) -> Result<uint256> {272 Ok(index)273 }274275 /// @dev Not implemented276 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {277 // TODO: Not implemetable278 Err("not implemented".into())279 }280281 /// @notice Count NFTs tracked by this contract282 /// @return A count of valid NFTs tracked by this contract, where each one of283 /// them has an assigned and queryable owner not equal to the zero address284 fn total_supply(&self) -> Result<uint256> {285 self.consume_store_reads(1)?;286 Ok(<Pallet<T>>::total_supply(self).into())287 }288}289290/// @title ERC-721 Non-Fungible Token Standard291/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md292#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]293impl<T: Config> NonfungibleHandle<T> {294 /// @notice Count all NFTs assigned to an owner295 /// @dev NFTs assigned to the zero address are considered invalid, and this296 /// function throws for queries about the zero address.297 /// @param owner An address for whom to query the balance298 /// @return The number of NFTs owned by `owner`, possibly zero299 fn balance_of(&self, owner: address) -> Result<uint256> {300 self.consume_store_reads(1)?;301 let owner = T::CrossAccountId::from_eth(owner);302 let balance = <AccountBalance<T>>::get((self.id, owner));303 Ok(balance.into())304 }305 /// @notice Find the owner of an NFT306 /// @dev NFTs assigned to zero address are considered invalid, and queries307 /// about them do throw.308 /// @param tokenId The identifier for an NFT309 /// @return The address of the owner of the NFT310 fn owner_of(&self, token_id: uint256) -> Result<address> {311 self.consume_store_reads(1)?;312 let token: TokenId = token_id.try_into()?;313 Ok(*<TokenData<T>>::get((self.id, token))314 .ok_or("token not found")?315 .owner316 .as_eth())317 }318 /// @dev Not implemented319 #[solidity(rename_selector = "safeTransferFrom")]320 fn safe_transfer_from_with_data(321 &mut self,322 _from: address,323 _to: address,324 _token_id: uint256,325 _data: bytes,326 ) -> Result<void> {327 // TODO: Not implemetable328 Err("not implemented".into())329 }330 /// @dev Not implemented331 fn safe_transfer_from(332 &mut self,333 _from: address,334 _to: address,335 _token_id: uint256,336 ) -> Result<void> {337 // TODO: Not implemetable338 Err("not implemented".into())339 }340341 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE342 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE343 /// THEY MAY BE PERMANENTLY LOST344 /// @dev Throws unless `msg.sender` is the current owner or an authorized345 /// operator for this NFT. Throws if `from` is not the current owner. Throws346 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.347 /// @param from The current owner of the NFT348 /// @param to The new owner349 /// @param tokenId The NFT to transfer350 #[weight(<SelfWeightOf<T>>::transfer_from())]351 fn transfer_from(352 &mut self,353 caller: caller,354 from: address,355 to: address,356 token_id: uint256,357 ) -> Result<void> {358 let caller = T::CrossAccountId::from_eth(caller);359 let from = T::CrossAccountId::from_eth(from);360 let to = T::CrossAccountId::from_eth(to);361 let token = token_id.try_into()?;362 let budget = self363 .recorder364 .weight_calls_budget(<StructureWeight<T>>::find_parent());365366 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)367 .map_err(dispatch_to_evm::<T>)?;368 Ok(())369 }370371 /// @notice Set or reaffirm the approved address for an NFT372 /// @dev The zero address indicates there is no approved address.373 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized374 /// operator of the current owner.375 /// @param approved The new approved NFT controller376 /// @param tokenId The NFT to approve377 #[weight(<SelfWeightOf<T>>::approve())]378 fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {379 let caller = T::CrossAccountId::from_eth(caller);380 let approved = T::CrossAccountId::from_eth(approved);381 let token = token_id.try_into()?;382383 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))384 .map_err(dispatch_to_evm::<T>)?;385 Ok(())386 }387388 /// @dev Not implemented389 fn set_approval_for_all(390 &mut self,391 _caller: caller,392 _operator: address,393 _approved: bool,394 ) -> Result<void> {395 // TODO: Not implemetable396 Err("not implemented".into())397 }398399 /// @dev Not implemented400 fn get_approved(&self, _token_id: uint256) -> Result<address> {401 // TODO: Not implemetable402 Err("not implemented".into())403 }404405 /// @dev Not implemented406 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {407 // TODO: Not implemetable408 Err("not implemented".into())409 }410}411412/// @title ERC721 Token that can be irreversibly burned (destroyed).413#[solidity_interface(name = ERC721Burnable)]414impl<T: Config> NonfungibleHandle<T> {415 /// @notice Burns a specific ERC721 token.416 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized417 /// operator of the current owner.418 /// @param tokenId The NFT to approve419 #[weight(<SelfWeightOf<T>>::burn_item())]420 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {421 let caller = T::CrossAccountId::from_eth(caller);422 let token = token_id.try_into()?;423424 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;425 Ok(())426 }427}428429/// @title ERC721 minting logic.430#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]431impl<T: Config> NonfungibleHandle<T> {432 fn minting_finished(&self) -> Result<bool> {433 Ok(false)434 }435436 /// @notice Function to mint token.437 /// @dev `tokenId` should be obtained with `nextTokenId` method,438 /// unlike standard, you can't specify it manually439 /// @param to The new owner440 /// @param tokenId ID of the minted NFT441 #[weight(<SelfWeightOf<T>>::create_item())]442 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {443 let caller = T::CrossAccountId::from_eth(caller);444 let to = T::CrossAccountId::from_eth(to);445 let token_id: u32 = token_id.try_into()?;446 let budget = self447 .recorder448 .weight_calls_budget(<StructureWeight<T>>::find_parent());449450 if <TokensMinted<T>>::get(self.id)451 .checked_add(1)452 .ok_or("item id overflow")?453 != token_id454 {455 return Err("item id should be next".into());456 }457458 <Pallet<T>>::create_item(459 self,460 &caller,461 CreateItemData::<T> {462 properties: BoundedVec::default(),463 owner: to,464 },465 &budget,466 )467 .map_err(dispatch_to_evm::<T>)?;468469 Ok(true)470 }471472 /// @notice Function to mint token with the given tokenUri.473 /// @dev `tokenId` should be obtained with `nextTokenId` method,474 /// unlike standard, you can't specify it manually475 /// @param to The new owner476 /// @param tokenId ID of the minted NFT477 /// @param tokenUri Token URI that would be stored in the NFT properties478 #[solidity(rename_selector = "mintWithTokenURI")]479 #[weight(<SelfWeightOf<T>>::create_item())]480 fn mint_with_token_uri(481 &mut self,482 caller: caller,483 to: address,484 token_id: uint256,485 token_uri: string,486 ) -> Result<bool> {487 let key = key::url();488 let permission = get_token_permission::<T>(self.id, &key)?;489 if !permission.collection_admin {490 return Err("Operation is not allowed".into());491 }492493 let caller = T::CrossAccountId::from_eth(caller);494 let to = T::CrossAccountId::from_eth(to);495 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;496 let budget = self497 .recorder498 .weight_calls_budget(<StructureWeight<T>>::find_parent());499500 if <TokensMinted<T>>::get(self.id)501 .checked_add(1)502 .ok_or("item id overflow")?503 != token_id504 {505 return Err("item id should be next".into());506 }507508 let mut properties = CollectionPropertiesVec::default();509 properties510 .try_push(Property {511 key,512 value: token_uri513 .into_bytes()514 .try_into()515 .map_err(|_| "token uri is too long")?,516 })517 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;518519 <Pallet<T>>::create_item(520 self,521 &caller,522 CreateItemData::<T> {523 properties,524 owner: to,525 },526 &budget,527 )528 .map_err(dispatch_to_evm::<T>)?;529 Ok(true)530 }531532 /// @dev Not implemented533 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {534 Err("not implementable".into())535 }536}537538fn get_token_property<T: Config>(539 collection: &CollectionHandle<T>,540 token_id: u32,541 key: &up_data_structs::PropertyKey,542) -> Result<string> {543 collection.consume_store_reads(1)?;544 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))545 .map_err(|_| Error::Revert("Token properties not found".into()))?;546 if let Some(property) = properties.get(key) {547 return Ok(string::from_utf8_lossy(property).into());548 }549550 Err("Property tokenURI not found".into())551}552553fn get_token_permission<T: Config>(554 collection_id: CollectionId,555 key: &PropertyKey,556) -> Result<PropertyPermission> {557 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)558 .map_err(|_| Error::Revert("No permissions for collection".into()))?;559 let a = token_property_permissions560 .get(key)561 .map(Clone::clone)562 .ok_or_else(|| {563 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();564 Error::Revert(alloc::format!("No permission for key {}", key))565 })?;566 Ok(a)567}568569/// @title Unique extensions for ERC721.570#[solidity_interface(name = ERC721UniqueExtensions)]571impl<T: Config> NonfungibleHandle<T> {572 /// @notice Transfer ownership of an NFT573 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`574 /// is the zero address. Throws if `tokenId` is not a valid NFT.575 /// @param to The new owner576 /// @param tokenId The NFT to transfer577 #[weight(<SelfWeightOf<T>>::transfer())]578 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {579 let caller = T::CrossAccountId::from_eth(caller);580 let to = T::CrossAccountId::from_eth(to);581 let token = token_id.try_into()?;582 let budget = self583 .recorder584 .weight_calls_budget(<StructureWeight<T>>::find_parent());585586 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;587 Ok(())588 }589590 /// @notice Burns a specific ERC721 token.591 /// @dev Throws unless `msg.sender` is the current owner or an authorized592 /// operator for this NFT. Throws if `from` is not the current owner. Throws593 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.594 /// @param from The current owner of the NFT595 /// @param tokenId The NFT to transfer596 #[weight(<SelfWeightOf<T>>::burn_from())]597 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {598 let caller = T::CrossAccountId::from_eth(caller);599 let from = T::CrossAccountId::from_eth(from);600 let token = token_id.try_into()?;601 let budget = self602 .recorder603 .weight_calls_budget(<StructureWeight<T>>::find_parent());604605 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)606 .map_err(dispatch_to_evm::<T>)?;607 Ok(())608 }609610 /// @notice Returns next free NFT ID.611 fn next_token_id(&self) -> Result<uint256> {612 self.consume_store_reads(1)?;613 Ok(<TokensMinted<T>>::get(self.id)614 .checked_add(1)615 .ok_or("item id overflow")?616 .into())617 }618619 /// @notice Function to mint multiple tokens.620 /// @dev `tokenIds` should be an array of consecutive numbers and first number621 /// should be obtained with `nextTokenId` method622 /// @param to The new owner623 /// @param tokenIds IDs of the minted NFTs624 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]625 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {626 let caller = T::CrossAccountId::from_eth(caller);627 let to = T::CrossAccountId::from_eth(to);628 let mut expected_index = <TokensMinted<T>>::get(self.id)629 .checked_add(1)630 .ok_or("item id overflow")?;631 let budget = self632 .recorder633 .weight_calls_budget(<StructureWeight<T>>::find_parent());634635 let total_tokens = token_ids.len();636 for id in token_ids.into_iter() {637 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;638 if id != expected_index {639 return Err("item id should be next".into());640 }641 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;642 }643 let data = (0..total_tokens)644 .map(|_| CreateItemData::<T> {645 properties: BoundedVec::default(),646 owner: to.clone(),647 })648 .collect();649650 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)651 .map_err(dispatch_to_evm::<T>)?;652 Ok(true)653 }654655 /// @notice Function to mint multiple tokens with the given tokenUris.656 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive657 /// numbers and first number should be obtained with `nextTokenId` method658 /// @param to The new owner659 /// @param tokens array of pairs of token ID and token URI for minted tokens660 #[solidity(rename_selector = "mintBulkWithTokenURI")]661 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]662 fn mint_bulk_with_token_uri(663 &mut self,664 caller: caller,665 to: address,666 tokens: Vec<(uint256, string)>,667 ) -> Result<bool> {668 let key = key::url();669 let caller = T::CrossAccountId::from_eth(caller);670 let to = T::CrossAccountId::from_eth(to);671 let mut expected_index = <TokensMinted<T>>::get(self.id)672 .checked_add(1)673 .ok_or("item id overflow")?;674 let budget = self675 .recorder676 .weight_calls_budget(<StructureWeight<T>>::find_parent());677678 let mut data = Vec::with_capacity(tokens.len());679 for (id, token_uri) in tokens {680 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;681 if id != expected_index {682 return Err("item id should be next".into());683 }684 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;685686 let mut properties = CollectionPropertiesVec::default();687 properties688 .try_push(Property {689 key: key.clone(),690 value: token_uri691 .into_bytes()692 .try_into()693 .map_err(|_| "token uri is too long")?,694 })695 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;696697 data.push(CreateItemData::<T> {698 properties,699 owner: to.clone(),700 });701 }702703 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)704 .map_err(dispatch_to_evm::<T>)?;705 Ok(true)706 }707}708709#[solidity_interface(710 name = UniqueNFT,711 is(712 ERC721,713 ERC721Metadata(if(this.supports_metadata())),714 ERC721Enumerable,715 ERC721UniqueExtensions,716 ERC721Mintable,717 ERC721Burnable,718 Collection(via(common_mut returns CollectionHandle<T>)),719 TokenProperties,720 )721)]722impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}723724// Not a tests, but code generators725generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);726generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);727728impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>729where730 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,731{732 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");733734 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {735 call::<T, UniqueNFTCall<T>, _, _>(handle, self)736 }737}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, static_property::key,38 static_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 _};4546use crate::{47 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,48 SelfWeightOf, weights::WeightInfo, TokenProperties,49};5051/// @title A contract that allows to set and delete token properties and change token property permissions.52#[solidity_interface(name = TokenProperties)]53impl<T: Config> NonfungibleHandle<T> {54 /// @notice Set permissions for token property.55 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.56 /// @param key Property key.57 /// @param isMutable Permission to mutate property.58 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.59 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.60 fn set_token_property_permission(61 &mut self,62 caller: caller,63 key: string,64 is_mutable: bool,65 collection_admin: bool,66 token_owner: bool,67 ) -> Result<()> {68 let caller = T::CrossAccountId::from_eth(caller);69 <Pallet<T>>::set_property_permission(70 self,71 &caller,72 PropertyKeyPermission {73 key: <Vec<u8>>::from(key)74 .try_into()75 .map_err(|_| "too long key")?,76 permission: PropertyPermission {77 mutable: is_mutable,78 collection_admin,79 token_owner,80 },81 },82 )83 .map_err(dispatch_to_evm::<T>)84 }8586 /// @notice Set token property value.87 /// @dev Throws error if `msg.sender` has no permission to edit the property.88 /// @param tokenId ID of the token.89 /// @param key Property key.90 /// @param value Property value.91 fn set_property(92 &mut self,93 caller: caller,94 token_id: uint256,95 key: string,96 value: bytes,97 ) -> Result<()> {98 let caller = T::CrossAccountId::from_eth(caller);99 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;100 let key = <Vec<u8>>::from(key)101 .try_into()102 .map_err(|_| "key too long")?;103 let value = value.try_into().map_err(|_| "value too long")?;104105 let nesting_budget = self106 .recorder107 .weight_calls_budget(<StructureWeight<T>>::find_parent());108109 <Pallet<T>>::set_token_property(110 self,111 &caller,112 TokenId(token_id),113 Property { key, value },114 &nesting_budget,115 )116 .map_err(dispatch_to_evm::<T>)117 }118119 /// @notice Delete token property value.120 /// @dev Throws error if `msg.sender` has no permission to edit the property.121 /// @param tokenId ID of the token.122 /// @param key Property key.123 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {124 let caller = T::CrossAccountId::from_eth(caller);125 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;126 let key = <Vec<u8>>::from(key)127 .try_into()128 .map_err(|_| "key too long")?;129130 let nesting_budget = self131 .recorder132 .weight_calls_budget(<StructureWeight<T>>::find_parent());133134 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)135 .map_err(dispatch_to_evm::<T>)136 }137138 /// @notice Get token property value.139 /// @dev Throws error if key not found140 /// @param tokenId ID of the token.141 /// @param key Property key.142 /// @return Property value bytes143 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {144 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;145 let key = <Vec<u8>>::from(key)146 .try_into()147 .map_err(|_| "key too long")?;148149 let props = <TokenProperties<T>>::get((self.id, token_id));150 let prop = props.get(&key).ok_or("key not found")?;151152 Ok(prop.to_vec())153 }154}155156#[derive(ToLog)]157pub enum ERC721Events {158 /// @dev This emits when ownership of any NFT changes by any mechanism.159 /// This event emits when NFTs are created (`from` == 0) and destroyed160 /// (`to` == 0). Exception: during contract creation, any number of NFTs161 /// may be created and assigned without emitting Transfer. At the time of162 /// any transfer, the approved address for that NFT (if any) is reset to none.163 Transfer {164 #[indexed]165 from: address,166 #[indexed]167 to: address,168 #[indexed]169 token_id: uint256,170 },171 /// @dev This emits when the approved address for an NFT is changed or172 /// reaffirmed. The zero address indicates there is no approved address.173 /// When a Transfer event emits, this also indicates that the approved174 /// address for that NFT (if any) is reset to none.175 Approval {176 #[indexed]177 owner: address,178 #[indexed]179 approved: address,180 #[indexed]181 token_id: uint256,182 },183 /// @dev This emits when an operator is enabled or disabled for an owner.184 /// The operator can manage all NFTs of the owner.185 #[allow(dead_code)]186 ApprovalForAll {187 #[indexed]188 owner: address,189 #[indexed]190 operator: address,191 approved: bool,192 },193}194195#[derive(ToLog)]196pub enum ERC721MintableEvents {197 #[allow(dead_code)]198 MintingFinished {},199}200201/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension202/// @dev See https://eips.ethereum.org/EIPS/eip-721203#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]204impl<T: Config> NonfungibleHandle<T> {205 /// @notice A descriptive name for a collection of NFTs in this contract206 fn name(&self) -> Result<string> {207 Ok(decode_utf16(self.name.iter().copied())208 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))209 .collect::<string>())210 }211212 /// @notice An abbreviated name for NFTs in this contract213 fn symbol(&self) -> Result<string> {214 Ok(string::from_utf8_lossy(&self.token_prefix).into())215 }216217 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.218 ///219 /// @dev If the token has a `url` property and it is not empty, it is returned.220 /// 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`.221 /// If the collection property `baseURI` is empty or absent, return "" (empty string)222 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix223 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).224 ///225 /// @return token's const_metadata226 #[solidity(rename_selector = "tokenURI")]227 fn token_uri(&self, token_id: uint256) -> Result<string> {228 if !self.supports_metadata() {229 return Ok("".into());230 }231232 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;233234 match get_token_property(self, token_id_u32, &key::url()).as_deref() {235 Err(_) | Ok("") => (),236 Ok(url) => {237 return Ok(url.into());238 }239 };240241 let base_uri =242 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())243 .map(BoundedVec::into_inner)244 .map(string::from_utf8)245 .transpose()246 .map_err(|e| {247 Error::Revert(alloc::format!(248 "Can not convert value \"baseURI\" to string with error \"{}\"",249 e250 ))251 })?;252253 let base_uri = match base_uri.as_deref() {254 None | Some("") => {255 return Ok("".into());256 }257 Some(base_uri) => base_uri.into(),258 };259260 Ok(261 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {262 Err(_) | Ok("") => base_uri,263 Ok(suffix) => base_uri + suffix,264 },265 )266 }267}268269/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension270/// @dev See https://eips.ethereum.org/EIPS/eip-721271#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]272impl<T: Config> NonfungibleHandle<T> {273 /// @notice Enumerate valid NFTs274 /// @param index A counter less than `totalSupply()`275 /// @return The token identifier for the `index`th NFT,276 /// (sort order not specified)277 fn token_by_index(&self, index: uint256) -> Result<uint256> {278 Ok(index)279 }280281 /// @dev Not implemented282 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {283 // TODO: Not implemetable284 Err("not implemented".into())285 }286287 /// @notice Count NFTs tracked by this contract288 /// @return A count of valid NFTs tracked by this contract, where each one of289 /// them has an assigned and queryable owner not equal to the zero address290 fn total_supply(&self) -> Result<uint256> {291 self.consume_store_reads(1)?;292 Ok(<Pallet<T>>::total_supply(self).into())293 }294}295296/// @title ERC-721 Non-Fungible Token Standard297/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md298#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]299impl<T: Config> NonfungibleHandle<T> {300 /// @notice Count all NFTs assigned to an owner301 /// @dev NFTs assigned to the zero address are considered invalid, and this302 /// function throws for queries about the zero address.303 /// @param owner An address for whom to query the balance304 /// @return The number of NFTs owned by `owner`, possibly zero305 fn balance_of(&self, owner: address) -> Result<uint256> {306 self.consume_store_reads(1)?;307 let owner = T::CrossAccountId::from_eth(owner);308 let balance = <AccountBalance<T>>::get((self.id, owner));309 Ok(balance.into())310 }311 /// @notice Find the owner of an NFT312 /// @dev NFTs assigned to zero address are considered invalid, and queries313 /// about them do throw.314 /// @param tokenId The identifier for an NFT315 /// @return The address of the owner of the NFT316 fn owner_of(&self, token_id: uint256) -> Result<address> {317 self.consume_store_reads(1)?;318 let token: TokenId = token_id.try_into()?;319 Ok(*<TokenData<T>>::get((self.id, token))320 .ok_or("token not found")?321 .owner322 .as_eth())323 }324 /// @dev Not implemented325 #[solidity(rename_selector = "safeTransferFrom")]326 fn safe_transfer_from_with_data(327 &mut self,328 _from: address,329 _to: address,330 _token_id: uint256,331 _data: bytes,332 ) -> Result<void> {333 // TODO: Not implemetable334 Err("not implemented".into())335 }336 /// @dev Not implemented337 fn safe_transfer_from(338 &mut self,339 _from: address,340 _to: address,341 _token_id: uint256,342 ) -> Result<void> {343 // TODO: Not implemetable344 Err("not implemented".into())345 }346347 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE348 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE349 /// THEY MAY BE PERMANENTLY LOST350 /// @dev Throws unless `msg.sender` is the current owner or an authorized351 /// operator for this NFT. Throws if `from` is not the current owner. Throws352 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.353 /// @param from The current owner of the NFT354 /// @param to The new owner355 /// @param tokenId The NFT to transfer356 #[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 ) -> Result<void> {364 let caller = T::CrossAccountId::from_eth(caller);365 let from = T::CrossAccountId::from_eth(from);366 let to = T::CrossAccountId::from_eth(to);367 let token = token_id.try_into()?;368 let budget = self369 .recorder370 .weight_calls_budget(<StructureWeight<T>>::find_parent());371372 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)373 .map_err(dispatch_to_evm::<T>)?;374 Ok(())375 }376377 /// @notice Set or reaffirm the approved address for an NFT378 /// @dev The zero address indicates there is no approved address.379 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized380 /// operator of the current owner.381 /// @param approved The new approved NFT controller382 /// @param tokenId The NFT to approve383 #[weight(<SelfWeightOf<T>>::approve())]384 fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {385 let caller = T::CrossAccountId::from_eth(caller);386 let approved = T::CrossAccountId::from_eth(approved);387 let token = token_id.try_into()?;388389 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))390 .map_err(dispatch_to_evm::<T>)?;391 Ok(())392 }393394 /// @dev Not implemented395 fn set_approval_for_all(396 &mut self,397 _caller: caller,398 _operator: address,399 _approved: bool,400 ) -> Result<void> {401 // TODO: Not implemetable402 Err("not implemented".into())403 }404405 /// @dev Not implemented406 fn get_approved(&self, _token_id: uint256) -> Result<address> {407 // TODO: Not implemetable408 Err("not implemented".into())409 }410411 /// @dev Not implemented412 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {413 // TODO: Not implemetable414 Err("not implemented".into())415 }416}417418/// @title ERC721 Token that can be irreversibly burned (destroyed).419#[solidity_interface(name = ERC721Burnable)]420impl<T: Config> NonfungibleHandle<T> {421 /// @notice Burns a specific ERC721 token.422 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized423 /// operator of the current owner.424 /// @param tokenId The NFT to approve425 #[weight(<SelfWeightOf<T>>::burn_item())]426 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {427 let caller = T::CrossAccountId::from_eth(caller);428 let token = token_id.try_into()?;429430 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;431 Ok(())432 }433}434435/// @title ERC721 minting logic.436#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]437impl<T: Config> NonfungibleHandle<T> {438 fn minting_finished(&self) -> Result<bool> {439 Ok(false)440 }441442 /// @notice Function to mint token.443 /// @dev `tokenId` should be obtained with `nextTokenId` method,444 /// unlike standard, you can't specify it manually445 /// @param to The new owner446 /// @param tokenId ID of the minted NFT447 #[weight(<SelfWeightOf<T>>::create_item())]448 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {449 let caller = T::CrossAccountId::from_eth(caller);450 let to = T::CrossAccountId::from_eth(to);451 let token_id: u32 = token_id.try_into()?;452 let budget = self453 .recorder454 .weight_calls_budget(<StructureWeight<T>>::find_parent());455456 if <TokensMinted<T>>::get(self.id)457 .checked_add(1)458 .ok_or("item id overflow")?459 != token_id460 {461 return Err("item id should be next".into());462 }463464 <Pallet<T>>::create_item(465 self,466 &caller,467 CreateItemData::<T> {468 properties: BoundedVec::default(),469 owner: to,470 },471 &budget,472 )473 .map_err(dispatch_to_evm::<T>)?;474475 Ok(true)476 }477478 /// @notice Function to mint token with the given tokenUri.479 /// @dev `tokenId` should be obtained with `nextTokenId` method,480 /// unlike standard, you can't specify it manually481 /// @param to The new owner482 /// @param tokenId ID of the minted NFT483 /// @param tokenUri Token URI that would be stored in the NFT properties484 #[solidity(rename_selector = "mintWithTokenURI")]485 #[weight(<SelfWeightOf<T>>::create_item())]486 fn mint_with_token_uri(487 &mut self,488 caller: caller,489 to: address,490 token_id: uint256,491 token_uri: string,492 ) -> Result<bool> {493 let key = key::url();494 let permission = get_token_permission::<T>(self.id, &key)?;495 if !permission.collection_admin {496 return Err("Operation is not allowed".into());497 }498499 let caller = T::CrossAccountId::from_eth(caller);500 let to = T::CrossAccountId::from_eth(to);501 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;502 let budget = self503 .recorder504 .weight_calls_budget(<StructureWeight<T>>::find_parent());505506 if <TokensMinted<T>>::get(self.id)507 .checked_add(1)508 .ok_or("item id overflow")?509 != token_id510 {511 return Err("item id should be next".into());512 }513514 let mut properties = CollectionPropertiesVec::default();515 properties516 .try_push(Property {517 key,518 value: token_uri519 .into_bytes()520 .try_into()521 .map_err(|_| "token uri is too long")?,522 })523 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;524525 <Pallet<T>>::create_item(526 self,527 &caller,528 CreateItemData::<T> {529 properties,530 owner: to,531 },532 &budget,533 )534 .map_err(dispatch_to_evm::<T>)?;535 Ok(true)536 }537538 /// @dev Not implemented539 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {540 Err("not implementable".into())541 }542}543544fn get_token_property<T: Config>(545 collection: &CollectionHandle<T>,546 token_id: u32,547 key: &up_data_structs::PropertyKey,548) -> Result<string> {549 collection.consume_store_reads(1)?;550 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))551 .map_err(|_| Error::Revert("Token properties not found".into()))?;552 if let Some(property) = properties.get(key) {553 return Ok(string::from_utf8_lossy(property).into());554 }555556 Err("Property tokenURI not found".into())557}558559fn get_token_permission<T: Config>(560 collection_id: CollectionId,561 key: &PropertyKey,562) -> Result<PropertyPermission> {563 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)564 .map_err(|_| Error::Revert("No permissions for collection".into()))?;565 let a = token_property_permissions566 .get(key)567 .map(Clone::clone)568 .ok_or_else(|| {569 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();570 Error::Revert(alloc::format!("No permission for key {}", key))571 })?;572 Ok(a)573}574575/// @title Unique extensions for ERC721.576#[solidity_interface(name = ERC721UniqueExtensions)]577impl<T: Config> NonfungibleHandle<T> {578 /// @notice Transfer ownership of an NFT579 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`580 /// is the zero address. Throws if `tokenId` is not a valid NFT.581 /// @param to The new owner582 /// @param tokenId The NFT to transfer583 #[weight(<SelfWeightOf<T>>::transfer())]584 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {585 let caller = T::CrossAccountId::from_eth(caller);586 let to = T::CrossAccountId::from_eth(to);587 let token = token_id.try_into()?;588 let budget = self589 .recorder590 .weight_calls_budget(<StructureWeight<T>>::find_parent());591592 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;593 Ok(())594 }595596 /// @notice Burns a specific ERC721 token.597 /// @dev Throws unless `msg.sender` is the current owner or an authorized598 /// operator for this NFT. Throws if `from` is not the current owner. Throws599 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.600 /// @param from The current owner of the NFT601 /// @param tokenId The NFT to transfer602 #[weight(<SelfWeightOf<T>>::burn_from())]603 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {604 let caller = T::CrossAccountId::from_eth(caller);605 let from = T::CrossAccountId::from_eth(from);606 let token = token_id.try_into()?;607 let budget = self608 .recorder609 .weight_calls_budget(<StructureWeight<T>>::find_parent());610611 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)612 .map_err(dispatch_to_evm::<T>)?;613 Ok(())614 }615616 /// @notice Returns next free NFT ID.617 fn next_token_id(&self) -> Result<uint256> {618 self.consume_store_reads(1)?;619 Ok(<TokensMinted<T>>::get(self.id)620 .checked_add(1)621 .ok_or("item id overflow")?622 .into())623 }624625 /// @notice Function to mint multiple tokens.626 /// @dev `tokenIds` should be an array of consecutive numbers and first number627 /// should be obtained with `nextTokenId` method628 /// @param to The new owner629 /// @param tokenIds IDs of the minted NFTs630 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]631 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {632 let caller = T::CrossAccountId::from_eth(caller);633 let to = T::CrossAccountId::from_eth(to);634 let mut expected_index = <TokensMinted<T>>::get(self.id)635 .checked_add(1)636 .ok_or("item id overflow")?;637 let budget = self638 .recorder639 .weight_calls_budget(<StructureWeight<T>>::find_parent());640641 let total_tokens = token_ids.len();642 for id in token_ids.into_iter() {643 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;644 if id != expected_index {645 return Err("item id should be next".into());646 }647 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;648 }649 let data = (0..total_tokens)650 .map(|_| CreateItemData::<T> {651 properties: BoundedVec::default(),652 owner: to.clone(),653 })654 .collect();655656 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)657 .map_err(dispatch_to_evm::<T>)?;658 Ok(true)659 }660661 /// @notice Function to mint multiple tokens with the given tokenUris.662 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive663 /// numbers and first number should be obtained with `nextTokenId` method664 /// @param to The new owner665 /// @param tokens array of pairs of token ID and token URI for minted tokens666 #[solidity(rename_selector = "mintBulkWithTokenURI")]667 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]668 fn mint_bulk_with_token_uri(669 &mut self,670 caller: caller,671 to: address,672 tokens: Vec<(uint256, string)>,673 ) -> Result<bool> {674 let key = key::url();675 let caller = T::CrossAccountId::from_eth(caller);676 let to = T::CrossAccountId::from_eth(to);677 let mut expected_index = <TokensMinted<T>>::get(self.id)678 .checked_add(1)679 .ok_or("item id overflow")?;680 let budget = self681 .recorder682 .weight_calls_budget(<StructureWeight<T>>::find_parent());683684 let mut data = Vec::with_capacity(tokens.len());685 for (id, token_uri) in tokens {686 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;687 if id != expected_index {688 return Err("item id should be next".into());689 }690 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;691692 let mut properties = CollectionPropertiesVec::default();693 properties694 .try_push(Property {695 key: key.clone(),696 value: token_uri697 .into_bytes()698 .try_into()699 .map_err(|_| "token uri is too long")?,700 })701 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;702703 data.push(CreateItemData::<T> {704 properties,705 owner: to.clone(),706 });707 }708709 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)710 .map_err(dispatch_to_evm::<T>)?;711 Ok(true)712 }713}714715impl<T: Config> NonfungibleHandle<T> {716 pub fn supports_metadata(&self) -> bool {717 if let Some(erc721_metadata) =718 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::erc721_metadata())719 {720 *erc721_metadata.into_inner() == *value::ERC721_METADATA_SUPPORTED721 } else {722 false723 }724 }725}726727#[solidity_interface(728 name = UniqueNFT,729 is(730 ERC721,731 ERC721Enumerable,732 ERC721UniqueExtensions,733 ERC721Mintable,734 ERC721Burnable,735 Collection(via(common_mut returns CollectionHandle<T>)),736 TokenProperties,737 ERC721Metadata(if(this.supports_metadata())),738 )739)]740impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}741742// Not a tests, but code generators743generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);744generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);745746impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>747where748 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,749{750 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");751752 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {753 call::<T, UniqueNFTCall<T>, _, _>(handle, self)754 }755}pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -297,18 +297,6 @@
}
}
-impl<T: Config> NonfungibleHandle<T> {
- pub fn supports_metadata(&self) -> bool {
- if let Some(erc721_metadata) =
- pallet_common::Pallet::<T>::get_collection_property(self.id, &key::erc721_metadata())
- {
- *erc721_metadata.into_inner() == *value::ERC721_METADATA_SUPPORTED
- } else {
- false
- }
- }
-}
-
impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {
fn recorder(&self) -> &SubstrateRecorder<T> {
self.0.recorder()
pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -17,6 +17,47 @@
}
}
+/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
+/// @dev See https://eips.ethereum.org/EIPS/eip-721
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+contract ERC721Metadata is Dummy, ERC165 {
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ /// @dev EVM selector for this function is: 0x06fdde03,
+ /// or in textual repr: name()
+ function name() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ /// @notice An abbreviated name for NFTs in this contract
+ /// @dev EVM selector for this function is: 0x95d89b41,
+ /// or in textual repr: symbol()
+ function symbol() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+ ///
+ /// @dev If the token 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 collection property `baseURI` is empty or absent, return "" (empty string)
+ /// otherwise, if token 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).
+ ///
+ /// @return token's const_metadata
+ /// @dev EVM selector for this function is: 0xc87b56dd,
+ /// or in textual repr: tokenURI(uint256)
+ function tokenURI(uint256 tokenId) public view returns (string memory) {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return "";
+ }
+}
+
/// @title A contract that allows to set and delete token properties and change token property permissions.
/// @dev the ERC-165 identifier for this interface is 0x41369377
contract TokenProperties is Dummy, ERC165 {
@@ -177,10 +218,10 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() public view returns (Tuple17 memory) {
+ function collectionSponsor() public view returns (Tuple15 memory) {
require(false, stub_error);
dummy;
- return Tuple17(0x0000000000000000000000000000000000000000, 0);
+ return Tuple15(0x0000000000000000000000000000000000000000, 0);
}
/// Set limits for the collection.
@@ -359,10 +400,10 @@
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
- function collectionOwner() public view returns (Tuple17 memory) {
+ function collectionOwner() public view returns (Tuple15 memory) {
require(false, stub_error);
dummy;
- return Tuple17(0x0000000000000000000000000000000000000000, 0);
+ return Tuple15(0x0000000000000000000000000000000000000000, 0);
}
/// Changes collection owner to another account
@@ -379,7 +420,7 @@
}
/// @dev anonymous struct
-struct Tuple17 {
+struct Tuple15 {
address field_0;
uint256 field_1;
}
@@ -525,7 +566,7 @@
/// @param tokens array of pairs of token ID and token URI for minted tokens
/// @dev EVM selector for this function is: 0x36543006,
/// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) public returns (bool) {
+ function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) public returns (bool) {
require(false, stub_error);
to;
tokens;
@@ -535,7 +576,7 @@
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
uint256 field_0;
string field_1;
}
@@ -577,48 +618,7 @@
require(false, stub_error);
dummy;
return 0;
- }
-}
-
-/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
-/// @dev See https://eips.ethereum.org/EIPS/eip-721
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-contract ERC721Metadata is Dummy, ERC165 {
- /// @notice A descriptive name for a collection of NFTs in this contract
- /// @dev EVM selector for this function is: 0x06fdde03,
- /// or in textual repr: name()
- function name() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-
- /// @notice An abbreviated name for NFTs in this contract
- /// @dev EVM selector for this function is: 0x95d89b41,
- /// or in textual repr: symbol()
- function symbol() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
}
-
- /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
- ///
- /// @dev If the token 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 collection property `baseURI` is empty or absent, return "" (empty string)
- /// otherwise, if token 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).
- ///
- /// @return token's const_metadata
- /// @dev EVM selector for this function is: 0xc87b56dd,
- /// or in textual repr: tokenURI(uint256)
- function tokenURI(uint256 tokenId) public view returns (string memory) {
- require(false, stub_error);
- tokenId;
- dummy;
- return "";
- }
}
/// @dev inlined interface
@@ -766,11 +766,11 @@
Dummy,
ERC165,
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
Collection,
- TokenProperties
+ TokenProperties,
+ ERC721Metadata
{}
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -21,19 +21,15 @@
extern crate alloc;
-use alloc::string::ToString;
use core::{
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
};
use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
-use frame_support::BoundedBTreeMap;
+use frame_support::{BoundedBTreeMap, BoundedVec};
use pallet_common::{
CollectionHandle, CollectionPropertyPermissions,
- erc::{
- CommonEvmHandler, CollectionCall,
- static_property::{key, value as property_value},
- },
+ erc::{CommonEvmHandler, CollectionCall, static_property::key, static_property::value},
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
@@ -222,37 +218,44 @@
/// @return token's const_metadata
#[solidity(rename_selector = "tokenURI")]
fn token_uri(&self, token_id: uint256) -> Result<string> {
+ if !self.supports_metadata() {
+ return Ok("".into());
+ }
+
let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
- if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {
- if !url.is_empty() {
- return Ok(url);
+ match get_token_property(self, token_id_u32, &key::url()).as_deref() {
+ Err(_) | Ok("") => (),
+ Ok(url) => {
+ return Ok(url.into());
}
- } else if !self.supports_metadata() {
- return Err("tokenURI not set".into());
- }
+ };
- if let Some(base_uri) =
+ let base_uri =
pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())
- {
- if !base_uri.is_empty() {
- let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {
+ .map(BoundedVec::into_inner)
+ .map(string::from_utf8)
+ .transpose()
+ .map_err(|e| {
Error::Revert(alloc::format!(
"Can not convert value \"baseURI\" to string with error \"{}\"",
e
))
})?;
- if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {
- if !suffix.is_empty() {
- return Ok(base_uri + suffix.as_str());
- }
- }
- return Ok(base_uri);
+ let base_uri = match base_uri.as_deref() {
+ None | Some("") => {
+ return Ok("".into());
}
- }
+ Some(base_uri) => base_uri.into(),
+ };
- Ok("".into())
+ Ok(
+ match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {
+ Err(_) | Ok("") => base_uri,
+ Ok(suffix) => base_uri + suffix,
+ },
+ )
}
}
@@ -765,17 +768,29 @@
}
}
+impl<T: Config> RefungibleHandle<T> {
+ pub fn supports_metadata(&self) -> bool {
+ if let Some(erc721_metadata) =
+ pallet_common::Pallet::<T>::get_collection_property(self.id, &key::erc721_metadata())
+ {
+ *erc721_metadata.into_inner() == *value::ERC721_METADATA_SUPPORTED
+ } else {
+ false
+ }
+ }
+}
+
#[solidity_interface(
name = UniqueRefungible,
is(
ERC721,
- ERC721Metadata(if(this.supports_metadata())),
ERC721Enumerable,
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
Collection(via(common_mut returns CollectionHandle<T>)),
TokenProperties,
+ ERC721Metadata(if(this.supports_metadata())),
)
)]
impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -304,18 +304,6 @@
}
}
-impl<T: Config> RefungibleHandle<T> {
- pub fn supports_metadata(&self) -> bool {
- if let Some(erc721_metadata) =
- pallet_common::Pallet::<T>::get_collection_property(self.id, &key::erc721_metadata())
- {
- *erc721_metadata.into_inner() == *value::ERC721_METADATA_SUPPORTED
- } else {
- false
- }
- }
-}
-
impl<T: Config> Deref for RefungibleHandle<T> {
type Target = pallet_common::CollectionHandle<T>;
pallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -17,6 +17,45 @@
}
}
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+contract ERC721Metadata is Dummy, ERC165 {
+ /// @notice A descriptive name for a collection of RFTs in this contract
+ /// @dev EVM selector for this function is: 0x06fdde03,
+ /// or in textual repr: name()
+ function name() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ /// @notice An abbreviated name for RFTs in this contract
+ /// @dev EVM selector for this function is: 0x95d89b41,
+ /// or in textual repr: symbol()
+ function symbol() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+ ///
+ /// @dev If the token 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 collection property `baseURI` is empty or absent, return "" (empty string)
+ /// otherwise, if token 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).
+ ///
+ /// @return token's const_metadata
+ /// @dev EVM selector for this function is: 0xc87b56dd,
+ /// or in textual repr: tokenURI(uint256)
+ function tokenURI(uint256 tokenId) public view returns (string memory) {
+ require(false, stub_error);
+ tokenId;
+ dummy;
+ return "";
+ }
+}
+
/// @title A contract that allows to set and delete token properties and change token property permissions.
/// @dev the ERC-165 identifier for this interface is 0x41369377
contract TokenProperties is Dummy, ERC165 {
@@ -177,10 +216,10 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() public view returns (Tuple17 memory) {
+ function collectionSponsor() public view returns (Tuple15 memory) {
require(false, stub_error);
dummy;
- return Tuple17(0x0000000000000000000000000000000000000000, 0);
+ return Tuple15(0x0000000000000000000000000000000000000000, 0);
}
/// Set limits for the collection.
@@ -359,10 +398,10 @@
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
- function collectionOwner() public view returns (Tuple17 memory) {
+ function collectionOwner() public view returns (Tuple15 memory) {
require(false, stub_error);
dummy;
- return Tuple17(0x0000000000000000000000000000000000000000, 0);
+ return Tuple15(0x0000000000000000000000000000000000000000, 0);
}
/// Changes collection owner to another account
@@ -379,7 +418,7 @@
}
/// @dev anonymous struct
-struct Tuple17 {
+struct Tuple15 {
address field_0;
uint256 field_1;
}
@@ -527,7 +566,7 @@
/// @param tokens array of pairs of token ID and token URI for minted tokens
/// @dev EVM selector for this function is: 0x36543006,
/// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) public returns (bool) {
+ function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) public returns (bool) {
require(false, stub_error);
to;
tokens;
@@ -549,7 +588,7 @@
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
uint256 field_0;
string field_1;
}
@@ -591,45 +630,6 @@
require(false, stub_error);
dummy;
return 0;
- }
-}
-
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-contract ERC721Metadata is Dummy, ERC165 {
- /// @notice A descriptive name for a collection of RFTs in this contract
- /// @dev EVM selector for this function is: 0x06fdde03,
- /// or in textual repr: name()
- function name() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-
- /// @notice An abbreviated name for RFTs in this contract
- /// @dev EVM selector for this function is: 0x95d89b41,
- /// or in textual repr: symbol()
- function symbol() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-
- /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
- ///
- /// @dev If the token 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 collection property `baseURI` is empty or absent, return "" (empty string)
- /// otherwise, if token 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).
- ///
- /// @return token's const_metadata
- /// @dev EVM selector for this function is: 0xc87b56dd,
- /// or in textual repr: tokenURI(uint256)
- function tokenURI(uint256 tokenId) public view returns (string memory) {
- require(false, stub_error);
- tokenId;
- dummy;
- return "";
}
}
@@ -776,11 +776,11 @@
Dummy,
ERC165,
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
Collection,
- TokenProperties
+ TokenProperties,
+ ERC721Metadata
{}
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -336,27 +336,6 @@
}
#[weight(<SelfWeightOf<T>>::create_collection())]
- #[deprecated(note = "mathod was renamed to `create_rft_collection`, prefer it instead")]
- fn create_refungible_collection(
- &mut self,
- caller: caller,
- value: value,
- name: string,
- description: string,
- token_prefix: string,
- ) -> Result<address> {
- create_refungible_collection_internal::<T>(
- caller,
- value,
- name,
- description,
- token_prefix,
- Default::default(),
- false,
- )
- }
-
- #[weight(<SelfWeightOf<T>>::create_collection())]
#[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]
fn create_refungible_collection_with_properties(
&mut self,
pallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -23,7 +23,7 @@
}
/// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0x95eb98f4
+/// @dev the ERC-165 identifier for this interface is 0xd14d1221
contract CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
/// Create an NFT collection
/// @param name Name of the collection
@@ -85,21 +85,6 @@
/// @dev EVM selector for this function is: 0xab173450,
/// or in textual repr: createRFTCollection(string,string,string)
function createRFTCollection(
- string memory name,
- string memory description,
- string memory tokenPrefix
- ) public payable returns (address) {
- require(false, stub_error);
- name;
- description;
- tokenPrefix;
- dummy = 0;
- return 0x0000000000000000000000000000000000000000;
- }
-
- /// @dev EVM selector for this function is: 0x44a68ad5,
- /// or in textual repr: createRefungibleCollection(string,string,string)
- function createRefungibleCollection(
string memory name,
string memory description,
string memory tokenPrefix
tests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -18,7 +18,7 @@
}
/// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0x95eb98f4
+/// @dev the ERC-165 identifier for this interface is 0xd14d1221
interface CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
/// Create an NFT collection
/// @param name Name of the collection
@@ -58,14 +58,6 @@
/// @dev EVM selector for this function is: 0xab173450,
/// or in textual repr: createRFTCollection(string,string,string)
function createRFTCollection(
- string memory name,
- string memory description,
- string memory tokenPrefix
- ) external payable returns (address);
-
- /// @dev EVM selector for this function is: 0x44a68ad5,
- /// or in textual repr: createRefungibleCollection(string,string,string)
- function createRefungibleCollection(
string memory name,
string memory description,
string memory tokenPrefix
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -12,6 +12,34 @@
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
+/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
+/// @dev See https://eips.ethereum.org/EIPS/eip-721
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+interface ERC721Metadata is Dummy, ERC165 {
+ /// @notice A descriptive name for a collection of NFTs in this contract
+ /// @dev EVM selector for this function is: 0x06fdde03,
+ /// or in textual repr: name()
+ function name() external view returns (string memory);
+
+ /// @notice An abbreviated name for NFTs in this contract
+ /// @dev EVM selector for this function is: 0x95d89b41,
+ /// or in textual repr: symbol()
+ function symbol() external view returns (string memory);
+
+ /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+ ///
+ /// @dev If the token 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 collection property `baseURI` is empty or absent, return "" (empty string)
+ /// otherwise, if token 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).
+ ///
+ /// @return token's const_metadata
+ /// @dev EVM selector for this function is: 0xc87b56dd,
+ /// or in textual repr: tokenURI(uint256)
+ function tokenURI(uint256 tokenId) external view returns (string memory);
+}
+
/// @title A contract that allows to set and delete token properties and change token property permissions.
/// @dev the ERC-165 identifier for this interface is 0x41369377
interface TokenProperties is Dummy, ERC165 {
@@ -120,7 +148,7 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() external view returns (Tuple17 memory);
+ function collectionSponsor() external view returns (Tuple15 memory);
/// Set limits for the collection.
/// @dev Throws error if limit not found.
@@ -237,7 +265,7 @@
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
- function collectionOwner() external view returns (Tuple17 memory);
+ function collectionOwner() external view returns (Tuple15 memory);
/// Changes collection owner to another account
///
@@ -249,7 +277,7 @@
}
/// @dev anonymous struct
-struct Tuple17 {
+struct Tuple15 {
address field_0;
uint256 field_1;
}
@@ -350,11 +378,11 @@
/// @param tokens array of pairs of token ID and token URI for minted tokens
/// @dev EVM selector for this function is: 0x36543006,
/// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) external returns (bool);
+ function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) external returns (bool);
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
uint256 field_0;
string field_1;
}
@@ -383,35 +411,7 @@
/// or in textual repr: totalSupply()
function totalSupply() external view returns (uint256);
}
-
-/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
-/// @dev See https://eips.ethereum.org/EIPS/eip-721
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-interface ERC721Metadata is Dummy, ERC165 {
- /// @notice A descriptive name for a collection of NFTs in this contract
- /// @dev EVM selector for this function is: 0x06fdde03,
- /// or in textual repr: name()
- function name() external view returns (string memory);
- /// @notice An abbreviated name for NFTs in this contract
- /// @dev EVM selector for this function is: 0x95d89b41,
- /// or in textual repr: symbol()
- function symbol() external view returns (string memory);
-
- /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
- ///
- /// @dev If the token 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 collection property `baseURI` is empty or absent, return "" (empty string)
- /// otherwise, if token 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).
- ///
- /// @return token's const_metadata
- /// @dev EVM selector for this function is: 0xc87b56dd,
- /// or in textual repr: tokenURI(uint256)
- function tokenURI(uint256 tokenId) external view returns (string memory);
-}
-
/// @dev inlined interface
interface ERC721Events {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
@@ -507,11 +507,11 @@
Dummy,
ERC165,
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
Collection,
- TokenProperties
+ TokenProperties,
+ ERC721Metadata
{}
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -12,6 +12,32 @@
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+interface ERC721Metadata is Dummy, ERC165 {
+ /// @notice A descriptive name for a collection of RFTs in this contract
+ /// @dev EVM selector for this function is: 0x06fdde03,
+ /// or in textual repr: name()
+ function name() external view returns (string memory);
+
+ /// @notice An abbreviated name for RFTs in this contract
+ /// @dev EVM selector for this function is: 0x95d89b41,
+ /// or in textual repr: symbol()
+ function symbol() external view returns (string memory);
+
+ /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+ ///
+ /// @dev If the token 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 collection property `baseURI` is empty or absent, return "" (empty string)
+ /// otherwise, if token 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).
+ ///
+ /// @return token's const_metadata
+ /// @dev EVM selector for this function is: 0xc87b56dd,
+ /// or in textual repr: tokenURI(uint256)
+ function tokenURI(uint256 tokenId) external view returns (string memory);
+}
+
/// @title A contract that allows to set and delete token properties and change token property permissions.
/// @dev the ERC-165 identifier for this interface is 0x41369377
interface TokenProperties is Dummy, ERC165 {
@@ -120,7 +146,7 @@
/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
/// @dev EVM selector for this function is: 0x6ec0a9f1,
/// or in textual repr: collectionSponsor()
- function collectionSponsor() external view returns (Tuple17 memory);
+ function collectionSponsor() external view returns (Tuple15 memory);
/// Set limits for the collection.
/// @dev Throws error if limit not found.
@@ -237,7 +263,7 @@
/// If address is canonical then substrate mirror is zero and vice versa.
/// @dev EVM selector for this function is: 0xdf727d3b,
/// or in textual repr: collectionOwner()
- function collectionOwner() external view returns (Tuple17 memory);
+ function collectionOwner() external view returns (Tuple15 memory);
/// Changes collection owner to another account
///
@@ -249,7 +275,7 @@
}
/// @dev anonymous struct
-struct Tuple17 {
+struct Tuple15 {
address field_0;
uint256 field_1;
}
@@ -352,7 +378,7 @@
/// @param tokens array of pairs of token ID and token URI for minted tokens
/// @dev EVM selector for this function is: 0x36543006,
/// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) external returns (bool);
+ function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) external returns (bool);
/// Returns EVM address for refungible token
///
@@ -363,7 +389,7 @@
}
/// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
uint256 field_0;
string field_1;
}
@@ -393,32 +419,6 @@
function totalSupply() external view returns (uint256);
}
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-interface ERC721Metadata is Dummy, ERC165 {
- /// @notice A descriptive name for a collection of RFTs in this contract
- /// @dev EVM selector for this function is: 0x06fdde03,
- /// or in textual repr: name()
- function name() external view returns (string memory);
-
- /// @notice An abbreviated name for RFTs in this contract
- /// @dev EVM selector for this function is: 0x95d89b41,
- /// or in textual repr: symbol()
- function symbol() external view returns (string memory);
-
- /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
- ///
- /// @dev If the token 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 collection property `baseURI` is empty or absent, return "" (empty string)
- /// otherwise, if token 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).
- ///
- /// @return token's const_metadata
- /// @dev EVM selector for this function is: 0xc87b56dd,
- /// or in textual repr: tokenURI(uint256)
- function tokenURI(uint256 tokenId) external view returns (string memory);
-}
-
/// @dev inlined interface
interface ERC721Events {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
@@ -512,11 +512,11 @@
Dummy,
ERC165,
ERC721,
- ERC721Metadata,
ERC721Enumerable,
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
Collection,
- TokenProperties
+ TokenProperties,
+ ERC721Metadata
{}
tests/src/eth/collectionHelpersAbi.jsondiffbeforeafterboth--- a/tests/src/eth/collectionHelpersAbi.json
+++ b/tests/src/eth/collectionHelpersAbi.json
@@ -84,17 +84,6 @@
},
{
"inputs": [
- { "internalType": "string", "name": "name", "type": "string" },
- { "internalType": "string", "name": "description", "type": "string" },
- { "internalType": "string", "name": "tokenPrefix", "type": "string" }
- ],
- "name": "createRefungibleCollection",
- "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
- "stateMutability": "payable",
- "type": "function"
- },
- {
- "inputs": [
{
"internalType": "address",
"name": "collectionAddress",
tests/src/eth/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionProperties.test.ts
+++ b/tests/src/eth/collectionProperties.test.ts
@@ -1,5 +1,6 @@
import {itEth, usingEthPlaygrounds, expect} from './util/playgrounds';
import {IKeyringPair} from '@polkadot/types/types';
+import {Pallets} from '../util/playgrounds';
describe('EVM collection properties', () => {
let donor: IKeyringPair;
@@ -80,7 +81,7 @@
expect(await contract.methods.supportsInterface('0x5b5e139f').call()).to.be.false;
});
- itEth('ERC721Metadata property can be set for RFT collection', async({helper}) => {
+ itEth.ifWithPallets('ERC721Metadata property can be set for RFT collection', [Pallets.ReFungible], async({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
const collection = await helper.rft.mintCollection(donor, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -79,11 +79,11 @@
});
});
- async function setup(helper: EthUniqueHelper, tokenPrefix: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
+ async function setup(helper: EthUniqueHelper, baseUri: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', 'a', 'b', tokenPrefix);
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', 'a', 'b', baseUri);
const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
const nextTokenId = await contract.methods.nextTokenId().call();
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -154,7 +154,7 @@
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
- "internalType": "struct Tuple17",
+ "internalType": "struct Tuple15",
"name": "",
"type": "tuple"
}
@@ -178,7 +178,7 @@
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
- "internalType": "struct Tuple17",
+ "internalType": "struct Tuple15",
"name": "",
"type": "tuple"
}
@@ -287,7 +287,7 @@
{ "internalType": "uint256", "name": "field_0", "type": "uint256" },
{ "internalType": "string", "name": "field_1", "type": "string" }
],
- "internalType": "struct Tuple8[]",
+ "internalType": "struct Tuple6[]",
"name": "tokens",
"type": "tuple[]"
}
tests/src/eth/reFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/reFungibleAbi.json
+++ b/tests/src/eth/reFungibleAbi.json
@@ -154,7 +154,7 @@
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
- "internalType": "struct Tuple17",
+ "internalType": "struct Tuple15",
"name": "",
"type": "tuple"
}
@@ -178,7 +178,7 @@
{ "internalType": "address", "name": "field_0", "type": "address" },
{ "internalType": "uint256", "name": "field_1", "type": "uint256" }
],
- "internalType": "struct Tuple17",
+ "internalType": "struct Tuple15",
"name": "",
"type": "tuple"
}
@@ -287,7 +287,7 @@
{ "internalType": "uint256", "name": "field_0", "type": "uint256" },
{ "internalType": "string", "name": "field_1", "type": "string" }
],
- "internalType": "struct Tuple8[]",
+ "internalType": "struct Tuple6[]",
"name": "tokens",
"type": "tuple[]"
}
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -76,11 +76,11 @@
});
});
- async function setup(helper: EthUniqueHelper, tokenPrefix: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
+ async function setup(helper: EthUniqueHelper, baseUri: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
const owner = await helper.eth.createAccountWithBalance(donor);
const receiver = helper.eth.createAccount();
- const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Mint collection', 'a', 'b', tokenPrefix);
+ const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Mint collection', 'a', 'b', baseUri);
const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
const nextTokenId = await contract.methods.nextTokenId().call();