difftreelog
CORE-441 Add some properties atcollection creation
in: master
4 files changed
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -430,10 +430,53 @@
Ok(())
}
-/// Get the "tokenURI" key as [PropertyKey](up_data_structs::PropertyKey).
-pub fn token_uri_key() -> up_data_structs::PropertyKey {
- b"tokenURI"
- .to_vec()
- .try_into()
- .expect("length < limit; qed")
+pub mod static_property_key_value {
+ use evm_coder::{
+ execution::{Result, Error},
+ };
+ use alloc::format;
+
+ const EXPECT_CONVERT_ERROR: &str = "length < limit";
+ /// Get the "tokenURI" key as [PropertyKey](up_data_structs::PropertyKey).
+ pub fn token_uri_key() -> up_data_structs::PropertyKey {
+ property_key_from_bytes(b"tokenURI").expect(EXPECT_CONVERT_ERROR)
+ }
+
+ pub fn schema_name_key() -> up_data_structs::PropertyKey {
+ property_key_from_bytes(b"schemaName").expect(EXPECT_CONVERT_ERROR)
+ }
+
+ pub fn base_uri_key() -> up_data_structs::PropertyKey {
+ property_key_from_bytes(b"baseURI").expect(EXPECT_CONVERT_ERROR)
+ }
+
+ pub fn u_key() -> up_data_structs::PropertyKey {
+ property_key_from_bytes(b"u").expect(EXPECT_CONVERT_ERROR)
+ }
+
+ pub fn s_key() -> up_data_structs::PropertyKey {
+ property_key_from_bytes(b"s").expect(EXPECT_CONVERT_ERROR)
+ }
+
+ pub fn erc721_value() -> up_data_structs::PropertyValue {
+ property_value_from_bytes(b"ERC721").expect(EXPECT_CONVERT_ERROR)
+ }
+
+ pub fn property_key_from_bytes(bytes: &[u8]) -> Result<up_data_structs::PropertyKey> {
+ bytes.to_vec().try_into().map_err(|_| {
+ Error::Revert(format!(
+ "Property key is too long. Max length is {}.",
+ up_data_structs::PropertyKey::bound()
+ ))
+ })
+ }
+
+ pub fn property_value_from_bytes(bytes: &[u8]) -> Result<up_data_structs::PropertyValue> {
+ bytes.to_vec().try_into().map_err(|_| {
+ Error::Revert(format!(
+ "Property key is too long. Max length is {}.",
+ up_data_structs::PropertyKey::bound()
+ ))
+ })
+ }
}
pallets/nonfungible/src/erc.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;23use core::{24 char::{REPLACEMENT_CHARACTER, decode_utf16},25 convert::TryInto,26};27use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};28use frame_support::BoundedVec;29use up_data_structs::{30 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,31 CollectionPropertiesVec,32};33use pallet_evm_coder_substrate::dispatch_to_evm;34use sp_std::vec::Vec;35use pallet_common::{36 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, token_uri_key},37 CollectionHandle, CollectionPropertyPermissions,38};39use pallet_evm::{account::CrossAccountId, PrecompileHandle};40use pallet_evm_coder_substrate::call;41use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};4243use crate::{44 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,45 SelfWeightOf, weights::WeightInfo, TokenProperties,46};4748/// @title A contract that allows to set and delete token properties and change token property permissions.49#[solidity_interface(name = "TokenProperties")]50impl<T: Config> NonfungibleHandle<T> {51 /// @notice Set permissions for token property.52 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.53 /// @param key Property key.54 /// @param is_mutable Permission to mutate property.55 /// @param collection_admin Permission to mutate property by collection admin if property is mutable.56 /// @param token_owner Permission to mutate property by token owner if property is mutable.57 fn set_token_property_permission(58 &mut self,59 caller: caller,60 key: string,61 is_mutable: bool,62 collection_admin: bool,63 token_owner: bool,64 ) -> Result<()> {65 let caller = T::CrossAccountId::from_eth(caller);66 <Pallet<T>>::set_property_permission(67 self,68 &caller,69 PropertyKeyPermission {70 key: <Vec<u8>>::from(key)71 .try_into()72 .map_err(|_| "too long key")?,73 permission: PropertyPermission {74 mutable: is_mutable,75 collection_admin,76 token_owner,77 },78 },79 )80 .map_err(dispatch_to_evm::<T>)81 }8283 /// @notice Set token property value.84 /// @dev Throws error if `msg.sender` has no permission to edit the property.85 /// @param tokenId ID of the token.86 /// @param key Property key.87 /// @param value Property value.88 fn set_property(89 &mut self,90 caller: caller,91 token_id: uint256,92 key: string,93 value: bytes,94 ) -> Result<()> {95 let caller = T::CrossAccountId::from_eth(caller);96 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;97 let key = <Vec<u8>>::from(key)98 .try_into()99 .map_err(|_| "key too long")?;100 let value = value.try_into().map_err(|_| "value too long")?;101102 let nesting_budget = self103 .recorder104 .weight_calls_budget(<StructureWeight<T>>::find_parent());105106 <Pallet<T>>::set_token_property(107 self,108 &caller,109 TokenId(token_id),110 Property { key, value },111 &nesting_budget,112 )113 .map_err(dispatch_to_evm::<T>)114 }115116 /// @notice Delete token property value.117 /// @dev Throws error if `msg.sender` has no permission to edit the property.118 /// @param tokenId ID of the token.119 /// @param key Property key.120 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {121 let caller = T::CrossAccountId::from_eth(caller);122 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;123 let key = <Vec<u8>>::from(key)124 .try_into()125 .map_err(|_| "key too long")?;126127 let nesting_budget = self128 .recorder129 .weight_calls_budget(<StructureWeight<T>>::find_parent());130131 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)132 .map_err(dispatch_to_evm::<T>)133 }134135 /// @notice Get token property value.136 /// @dev Throws error if key not found137 /// @param tokenId ID of the token.138 /// @param key Property key.139 /// @return Property value bytes140 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {141 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;142 let key = <Vec<u8>>::from(key)143 .try_into()144 .map_err(|_| "key too long")?;145146 let props = <TokenProperties<T>>::get((self.id, token_id));147 let prop = props.get(&key).ok_or("key not found")?;148149 Ok(prop.to_vec())150 }151}152153#[derive(ToLog)]154pub enum ERC721Events {155 /// @dev This emits when ownership of any NFT changes by any mechanism.156 /// This event emits when NFTs are created (`from` == 0) and destroyed157 /// (`to` == 0). Exception: during contract creation, any number of NFTs158 /// may be created and assigned without emitting Transfer. At the time of159 /// any transfer, the approved address for that NFT (if any) is reset to none.160 Transfer {161 #[indexed]162 from: address,163 #[indexed]164 to: address,165 #[indexed]166 token_id: uint256,167 },168 /// @dev This emits when the approved address for an NFT is changed or169 /// reaffirmed. The zero address indicates there is no approved address.170 /// When a Transfer event emits, this also indicates that the approved171 /// address for that NFT (if any) is reset to none.172 Approval {173 #[indexed]174 owner: address,175 #[indexed]176 approved: address,177 #[indexed]178 token_id: uint256,179 },180 /// @dev This emits when an operator is enabled or disabled for an owner.181 /// The operator can manage all NFTs of the owner.182 #[allow(dead_code)]183 ApprovalForAll {184 #[indexed]185 owner: address,186 #[indexed]187 operator: address,188 approved: bool,189 },190}191192#[derive(ToLog)]193pub enum ERC721MintableEvents {194 #[allow(dead_code)]195 MintingFinished {},196}197198/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension199/// @dev See https://eips.ethereum.org/EIPS/eip-721200#[solidity_interface(name = "ERC721Metadata")]201impl<T: Config> NonfungibleHandle<T> {202 /// @notice A descriptive name for a collection of NFTs in this contract203 fn name(&self) -> Result<string> {204 Ok(decode_utf16(self.name.iter().copied())205 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))206 .collect::<string>())207 }208209 /// @notice An abbreviated name for NFTs in this contract210 fn symbol(&self) -> Result<string> {211 Ok(string::from_utf8_lossy(&self.token_prefix).into())212 }213214 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.215 /// @dev Throws if `tokenId` is not a valid NFT. URIs are defined in RFC216 /// 3986. The URI may point to a JSON file that conforms to the "ERC721217 /// Metadata JSON Schema".218 /// @return token's const_metadata219 #[solidity(rename_selector = "tokenURI")]220 fn token_uri(&self, token_id: uint256) -> Result<string> {221 let key = token_uri_key();222 if !has_token_permission::<T>(self.id, &key) {223 return Err("No tokenURI permission".into());224 }225226 self.consume_store_reads(1)?;227 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;228229 let properties = <TokenProperties<T>>::try_get((self.id, token_id))230 .map_err(|_| Error::Revert("Token properties not found".into()))?;231 if let Some(property) = properties.get(&key) {232 return Ok(string::from_utf8_lossy(property).into());233 }234235 Err("Property tokenURI not found".into())236 }237}238239/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension240/// @dev See https://eips.ethereum.org/EIPS/eip-721241#[solidity_interface(name = "ERC721Enumerable")]242impl<T: Config> NonfungibleHandle<T> {243 /// @notice Enumerate valid NFTs244 /// @param index A counter less than `totalSupply()`245 /// @return The token identifier for the `index`th NFT,246 /// (sort order not specified)247 fn token_by_index(&self, index: uint256) -> Result<uint256> {248 Ok(index)249 }250251 /// @dev Not implemented252 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {253 // TODO: Not implemetable254 Err("not implemented".into())255 }256257 /// @notice Count NFTs tracked by this contract258 /// @return A count of valid NFTs tracked by this contract, where each one of259 /// them has an assigned and queryable owner not equal to the zero address260 fn total_supply(&self) -> Result<uint256> {261 self.consume_store_reads(1)?;262 Ok(<Pallet<T>>::total_supply(self).into())263 }264}265266/// @title ERC-721 Non-Fungible Token Standard267/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md268#[solidity_interface(name = "ERC721", events(ERC721Events))]269impl<T: Config> NonfungibleHandle<T> {270 /// @notice Count all NFTs assigned to an owner271 /// @dev NFTs assigned to the zero address are considered invalid, and this272 /// function throws for queries about the zero address.273 /// @param owner An address for whom to query the balance274 /// @return The number of NFTs owned by `owner`, possibly zero275 fn balance_of(&self, owner: address) -> Result<uint256> {276 self.consume_store_reads(1)?;277 let owner = T::CrossAccountId::from_eth(owner);278 let balance = <AccountBalance<T>>::get((self.id, owner));279 Ok(balance.into())280 }281 /// @notice Find the owner of an NFT282 /// @dev NFTs assigned to zero address are considered invalid, and queries283 /// about them do throw.284 /// @param tokenId The identifier for an NFT285 /// @return The address of the owner of the NFT286 fn owner_of(&self, token_id: uint256) -> Result<address> {287 self.consume_store_reads(1)?;288 let token: TokenId = token_id.try_into()?;289 Ok(*<TokenData<T>>::get((self.id, token))290 .ok_or("token not found")?291 .owner292 .as_eth())293 }294 /// @dev Not implemented295 fn safe_transfer_from_with_data(296 &mut self,297 _from: address,298 _to: address,299 _token_id: uint256,300 _data: bytes,301 _value: value,302 ) -> Result<void> {303 // TODO: Not implemetable304 Err("not implemented".into())305 }306 /// @dev Not implemented307 fn safe_transfer_from(308 &mut self,309 _from: address,310 _to: address,311 _token_id: uint256,312 _value: value,313 ) -> Result<void> {314 // TODO: Not implemetable315 Err("not implemented".into())316 }317318 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE319 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE320 /// THEY MAY BE PERMANENTLY LOST321 /// @dev Throws unless `msg.sender` is the current owner or an authorized322 /// operator for this NFT. Throws if `from` is not the current owner. Throws323 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.324 /// @param from The current owner of the NFT325 /// @param to The new owner326 /// @param tokenId The NFT to transfer327 /// @param _value Not used for an NFT328 #[weight(<SelfWeightOf<T>>::transfer_from())]329 fn transfer_from(330 &mut self,331 caller: caller,332 from: address,333 to: address,334 token_id: uint256,335 _value: value,336 ) -> Result<void> {337 let caller = T::CrossAccountId::from_eth(caller);338 let from = T::CrossAccountId::from_eth(from);339 let to = T::CrossAccountId::from_eth(to);340 let token = token_id.try_into()?;341 let budget = self342 .recorder343 .weight_calls_budget(<StructureWeight<T>>::find_parent());344345 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)346 .map_err(dispatch_to_evm::<T>)?;347 Ok(())348 }349350 /// @notice Set or reaffirm the approved address for an NFT351 /// @dev The zero address indicates there is no approved address.352 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized353 /// operator of the current owner.354 /// @param approved The new approved NFT controller355 /// @param tokenId The NFT to approve356 #[weight(<SelfWeightOf<T>>::approve())]357 fn approve(358 &mut self,359 caller: caller,360 approved: address,361 token_id: uint256,362 _value: value,363 ) -> Result<void> {364 let caller = T::CrossAccountId::from_eth(caller);365 let approved = T::CrossAccountId::from_eth(approved);366 let token = token_id.try_into()?;367368 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))369 .map_err(dispatch_to_evm::<T>)?;370 Ok(())371 }372373 /// @dev Not implemented374 fn set_approval_for_all(375 &mut self,376 _caller: caller,377 _operator: address,378 _approved: bool,379 ) -> Result<void> {380 // TODO: Not implemetable381 Err("not implemented".into())382 }383384 /// @dev Not implemented385 fn get_approved(&self, _token_id: uint256) -> Result<address> {386 // TODO: Not implemetable387 Err("not implemented".into())388 }389390 /// @dev Not implemented391 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {392 // TODO: Not implemetable393 Err("not implemented".into())394 }395}396397/// @title ERC721 Token that can be irreversibly burned (destroyed).398#[solidity_interface(name = "ERC721Burnable")]399impl<T: Config> NonfungibleHandle<T> {400 /// @notice Burns a specific ERC721 token.401 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized402 /// operator of the current owner.403 /// @param tokenId The NFT to approve404 #[weight(<SelfWeightOf<T>>::burn_item())]405 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {406 let caller = T::CrossAccountId::from_eth(caller);407 let token = token_id.try_into()?;408409 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;410 Ok(())411 }412}413414/// @title ERC721 minting logic.415#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]416impl<T: Config> NonfungibleHandle<T> {417 fn minting_finished(&self) -> Result<bool> {418 Ok(false)419 }420421 /// @notice Function to mint token.422 /// @dev `tokenId` should be obtained with `nextTokenId` method,423 /// unlike standard, you can't specify it manually424 /// @param to The new owner425 /// @param tokenId ID of the minted NFT426 #[weight(<SelfWeightOf<T>>::create_item())]427 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {428 let caller = T::CrossAccountId::from_eth(caller);429 let to = T::CrossAccountId::from_eth(to);430 let token_id: u32 = token_id.try_into()?;431 let budget = self432 .recorder433 .weight_calls_budget(<StructureWeight<T>>::find_parent());434435 if <TokensMinted<T>>::get(self.id)436 .checked_add(1)437 .ok_or("item id overflow")?438 != token_id439 {440 return Err("item id should be next".into());441 }442443 <Pallet<T>>::create_item(444 self,445 &caller,446 CreateItemData::<T> {447 properties: BoundedVec::default(),448 owner: to,449 },450 &budget,451 )452 .map_err(dispatch_to_evm::<T>)?;453454 Ok(true)455 }456457 /// @notice Function to mint token with the given tokenUri.458 /// @dev `tokenId` should be obtained with `nextTokenId` method,459 /// unlike standard, you can't specify it manually460 /// @param to The new owner461 /// @param tokenId ID of the minted NFT462 /// @param tokenUri Token URI that would be stored in the NFT properties463 #[solidity(rename_selector = "mintWithTokenURI")]464 #[weight(<SelfWeightOf<T>>::create_item())]465 fn mint_with_token_uri(466 &mut self,467 caller: caller,468 to: address,469 token_id: uint256,470 token_uri: string,471 ) -> Result<bool> {472 let key = token_uri_key();473 let permission = get_token_permission::<T>(self.id, &key)?;474 if !permission.collection_admin {475 return Err("Operation is not allowed".into());476 }477478 let caller = T::CrossAccountId::from_eth(caller);479 let to = T::CrossAccountId::from_eth(to);480 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;481 let budget = self482 .recorder483 .weight_calls_budget(<StructureWeight<T>>::find_parent());484485 if <TokensMinted<T>>::get(self.id)486 .checked_add(1)487 .ok_or("item id overflow")?488 != token_id489 {490 return Err("item id should be next".into());491 }492493 let mut properties = CollectionPropertiesVec::default();494 properties495 .try_push(Property {496 key,497 value: token_uri498 .into_bytes()499 .try_into()500 .map_err(|_| "token uri is too long")?,501 })502 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;503504 <Pallet<T>>::create_item(505 self,506 &caller,507 CreateItemData::<T> {508 properties,509 owner: to,510 },511 &budget,512 )513 .map_err(dispatch_to_evm::<T>)?;514 Ok(true)515 }516517 /// @dev Not implemented518 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {519 Err("not implementable".into())520 }521}522523fn get_token_permission<T: Config>(524 collection_id: CollectionId,525 key: &PropertyKey,526) -> Result<PropertyPermission> {527 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)528 .map_err(|_| Error::Revert("No permissions for collection".into()))?;529 let a = token_property_permissions530 .get(key)531 .map(|p| p.clone())532 .ok_or_else(|| Error::Revert("No permission".into()))?;533 Ok(a)534}535536fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {537 if let Ok(token_property_permissions) =538 CollectionPropertyPermissions::<T>::try_get(collection_id)539 {540 return token_property_permissions.contains_key(key);541 }542543 false544}545546/// @title Unique extensions for ERC721.547#[solidity_interface(name = "ERC721UniqueExtensions")]548impl<T: Config> NonfungibleHandle<T> {549 /// @notice Transfer ownership of an NFT550 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`551 /// is the zero address. Throws if `tokenId` is not a valid NFT.552 /// @param to The new owner553 /// @param tokenId The NFT to transfer554 /// @param _value Not used for an NFT555 #[weight(<SelfWeightOf<T>>::transfer())]556 fn transfer(557 &mut self,558 caller: caller,559 to: address,560 token_id: uint256,561 _value: value,562 ) -> Result<void> {563 let caller = T::CrossAccountId::from_eth(caller);564 let to = T::CrossAccountId::from_eth(to);565 let token = token_id.try_into()?;566 let budget = self567 .recorder568 .weight_calls_budget(<StructureWeight<T>>::find_parent());569570 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;571 Ok(())572 }573574 /// @notice Burns a specific ERC721 token.575 /// @dev Throws unless `msg.sender` is the current owner or an authorized576 /// operator for this NFT. Throws if `from` is not the current owner. Throws577 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.578 /// @param from The current owner of the NFT579 /// @param tokenId The NFT to transfer580 /// @param _value Not used for an NFT581 #[weight(<SelfWeightOf<T>>::burn_from())]582 fn burn_from(583 &mut self,584 caller: caller,585 from: address,586 token_id: uint256,587 _value: value,588 ) -> Result<void> {589 let caller = T::CrossAccountId::from_eth(caller);590 let from = T::CrossAccountId::from_eth(from);591 let token = token_id.try_into()?;592 let budget = self593 .recorder594 .weight_calls_budget(<StructureWeight<T>>::find_parent());595596 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)597 .map_err(dispatch_to_evm::<T>)?;598 Ok(())599 }600601 /// @notice Returns next free NFT ID.602 fn next_token_id(&self) -> Result<uint256> {603 self.consume_store_reads(1)?;604 Ok(<TokensMinted<T>>::get(self.id)605 .checked_add(1)606 .ok_or("item id overflow")?607 .into())608 }609610 /// @notice Function to mint multiple tokens.611 /// @dev `tokenIds` should be an array of consecutive numbers and first number612 /// should be obtained with `nextTokenId` method613 /// @param to The new owner614 /// @param tokenIds IDs of the minted NFTs615 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]616 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {617 let caller = T::CrossAccountId::from_eth(caller);618 let to = T::CrossAccountId::from_eth(to);619 let mut expected_index = <TokensMinted<T>>::get(self.id)620 .checked_add(1)621 .ok_or("item id overflow")?;622 let budget = self623 .recorder624 .weight_calls_budget(<StructureWeight<T>>::find_parent());625626 let total_tokens = token_ids.len();627 for id in token_ids.into_iter() {628 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;629 if id != expected_index {630 return Err("item id should be next".into());631 }632 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;633 }634 let data = (0..total_tokens)635 .map(|_| CreateItemData::<T> {636 properties: BoundedVec::default(),637 owner: to.clone(),638 })639 .collect();640641 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)642 .map_err(dispatch_to_evm::<T>)?;643 Ok(true)644 }645646 /// @notice Function to mint multiple tokens with the given tokenUris.647 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive648 /// numbers and first number should be obtained with `nextTokenId` method649 /// @param to The new owner650 /// @param tokens array of pairs of token ID and token URI for minted tokens651 #[solidity(rename_selector = "mintBulkWithTokenURI")]652 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]653 fn mint_bulk_with_token_uri(654 &mut self,655 caller: caller,656 to: address,657 tokens: Vec<(uint256, string)>,658 ) -> Result<bool> {659 let key = token_uri_key();660 let caller = T::CrossAccountId::from_eth(caller);661 let to = T::CrossAccountId::from_eth(to);662 let mut expected_index = <TokensMinted<T>>::get(self.id)663 .checked_add(1)664 .ok_or("item id overflow")?;665 let budget = self666 .recorder667 .weight_calls_budget(<StructureWeight<T>>::find_parent());668669 let mut data = Vec::with_capacity(tokens.len());670 for (id, token_uri) in tokens {671 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;672 if id != expected_index {673 return Err("item id should be next".into());674 }675 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;676677 let mut properties = CollectionPropertiesVec::default();678 properties679 .try_push(Property {680 key: key.clone(),681 value: token_uri682 .into_bytes()683 .try_into()684 .map_err(|_| "token uri is too long")?,685 })686 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;687688 data.push(CreateItemData::<T> {689 properties,690 owner: to.clone(),691 });692 }693694 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)695 .map_err(dispatch_to_evm::<T>)?;696 Ok(true)697 }698}699700#[solidity_interface(701 name = "UniqueNFT",702 is(703 ERC721,704 ERC721Metadata,705 ERC721Enumerable,706 ERC721UniqueExtensions,707 ERC721Mintable,708 ERC721Burnable,709 via("CollectionHandle<T>", common_mut, Collection),710 TokenProperties,711 )712)]713impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> {}714715// Not a tests, but code generators716generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);717generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);718719impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>720where721 T::AccountId: From<[u8; 32]>,722{723 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");724725 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {726 call::<T, UniqueNFTCall<T>, _, _>(handle, self)727 }728}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;23use core::{24 char::{REPLACEMENT_CHARACTER, decode_utf16},25 convert::TryInto,26};27use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};28use frame_support::BoundedVec;29use up_data_structs::{30 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,31 CollectionPropertiesVec,32};33use pallet_evm_coder_substrate::dispatch_to_evm;34use sp_std::vec::Vec;35use pallet_common::{36 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property_key_value::*},37 CollectionHandle, CollectionPropertyPermissions,38};39use pallet_evm::{account::CrossAccountId, PrecompileHandle};40use pallet_evm_coder_substrate::call;41use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};4243use crate::{44 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,45 SelfWeightOf, weights::WeightInfo, TokenProperties,46};4748/// @title A contract that allows to set and delete token properties and change token property permissions.49#[solidity_interface(name = "TokenProperties")]50impl<T: Config> NonfungibleHandle<T> {51 /// @notice Set permissions for token property.52 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.53 /// @param key Property key.54 /// @param is_mutable Permission to mutate property.55 /// @param collection_admin Permission to mutate property by collection admin if property is mutable.56 /// @param token_owner Permission to mutate property by token owner if property is mutable.57 fn set_token_property_permission(58 &mut self,59 caller: caller,60 key: string,61 is_mutable: bool,62 collection_admin: bool,63 token_owner: bool,64 ) -> Result<()> {65 let caller = T::CrossAccountId::from_eth(caller);66 <Pallet<T>>::set_property_permission(67 self,68 &caller,69 PropertyKeyPermission {70 key: <Vec<u8>>::from(key)71 .try_into()72 .map_err(|_| "too long key")?,73 permission: PropertyPermission {74 mutable: is_mutable,75 collection_admin,76 token_owner,77 },78 },79 )80 .map_err(dispatch_to_evm::<T>)81 }8283 /// @notice Set token property value.84 /// @dev Throws error if `msg.sender` has no permission to edit the property.85 /// @param tokenId ID of the token.86 /// @param key Property key.87 /// @param value Property value.88 fn set_property(89 &mut self,90 caller: caller,91 token_id: uint256,92 key: string,93 value: bytes,94 ) -> Result<()> {95 let caller = T::CrossAccountId::from_eth(caller);96 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;97 let key = <Vec<u8>>::from(key)98 .try_into()99 .map_err(|_| "key too long")?;100 let value = value.try_into().map_err(|_| "value too long")?;101102 let nesting_budget = self103 .recorder104 .weight_calls_budget(<StructureWeight<T>>::find_parent());105106 <Pallet<T>>::set_token_property(107 self,108 &caller,109 TokenId(token_id),110 Property { key, value },111 &nesting_budget,112 )113 .map_err(dispatch_to_evm::<T>)114 }115116 /// @notice Delete token property value.117 /// @dev Throws error if `msg.sender` has no permission to edit the property.118 /// @param tokenId ID of the token.119 /// @param key Property key.120 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {121 let caller = T::CrossAccountId::from_eth(caller);122 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;123 let key = <Vec<u8>>::from(key)124 .try_into()125 .map_err(|_| "key too long")?;126127 let nesting_budget = self128 .recorder129 .weight_calls_budget(<StructureWeight<T>>::find_parent());130131 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)132 .map_err(dispatch_to_evm::<T>)133 }134135 /// @notice Get token property value.136 /// @dev Throws error if key not found137 /// @param tokenId ID of the token.138 /// @param key Property key.139 /// @return Property value bytes140 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {141 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;142 let key = <Vec<u8>>::from(key)143 .try_into()144 .map_err(|_| "key too long")?;145146 let props = <TokenProperties<T>>::get((self.id, token_id));147 let prop = props.get(&key).ok_or("key not found")?;148149 Ok(prop.to_vec())150 }151}152153#[derive(ToLog)]154pub enum ERC721Events {155 /// @dev This emits when ownership of any NFT changes by any mechanism.156 /// This event emits when NFTs are created (`from` == 0) and destroyed157 /// (`to` == 0). Exception: during contract creation, any number of NFTs158 /// may be created and assigned without emitting Transfer. At the time of159 /// any transfer, the approved address for that NFT (if any) is reset to none.160 Transfer {161 #[indexed]162 from: address,163 #[indexed]164 to: address,165 #[indexed]166 token_id: uint256,167 },168 /// @dev This emits when the approved address for an NFT is changed or169 /// reaffirmed. The zero address indicates there is no approved address.170 /// When a Transfer event emits, this also indicates that the approved171 /// address for that NFT (if any) is reset to none.172 Approval {173 #[indexed]174 owner: address,175 #[indexed]176 approved: address,177 #[indexed]178 token_id: uint256,179 },180 /// @dev This emits when an operator is enabled or disabled for an owner.181 /// The operator can manage all NFTs of the owner.182 #[allow(dead_code)]183 ApprovalForAll {184 #[indexed]185 owner: address,186 #[indexed]187 operator: address,188 approved: bool,189 },190}191192#[derive(ToLog)]193pub enum ERC721MintableEvents {194 #[allow(dead_code)]195 MintingFinished {},196}197198/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension199/// @dev See https://eips.ethereum.org/EIPS/eip-721200#[solidity_interface(name = "ERC721Metadata")]201impl<T: Config> NonfungibleHandle<T> {202 /// @notice A descriptive name for a collection of NFTs in this contract203 fn name(&self) -> Result<string> {204 Ok(decode_utf16(self.name.iter().copied())205 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))206 .collect::<string>())207 }208209 /// @notice An abbreviated name for NFTs in this contract210 fn symbol(&self) -> Result<string> {211 Ok(string::from_utf8_lossy(&self.token_prefix).into())212 }213214 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.215 /// @dev Throws if `tokenId` is not a valid NFT. URIs are defined in RFC216 /// 3986. The URI may point to a JSON file that conforms to the "ERC721217 /// Metadata JSON Schema".218 /// @return token's const_metadata219 #[solidity(rename_selector = "tokenURI")]220 fn token_uri(&self, token_id: uint256) -> Result<string> {221 let key = token_uri_key();222 if !has_token_permission::<T>(self.id, &key) {223 return Err("No tokenURI permission".into());224 }225226 self.consume_store_reads(1)?;227 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;228229 let properties = <TokenProperties<T>>::try_get((self.id, token_id))230 .map_err(|_| Error::Revert("Token properties not found".into()))?;231 if let Some(property) = properties.get(&key) {232 return Ok(string::from_utf8_lossy(property).into());233 }234235 Err("Property tokenURI not found".into())236 }237}238239/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension240/// @dev See https://eips.ethereum.org/EIPS/eip-721241#[solidity_interface(name = "ERC721Enumerable")]242impl<T: Config> NonfungibleHandle<T> {243 /// @notice Enumerate valid NFTs244 /// @param index A counter less than `totalSupply()`245 /// @return The token identifier for the `index`th NFT,246 /// (sort order not specified)247 fn token_by_index(&self, index: uint256) -> Result<uint256> {248 Ok(index)249 }250251 /// @dev Not implemented252 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {253 // TODO: Not implemetable254 Err("not implemented".into())255 }256257 /// @notice Count NFTs tracked by this contract258 /// @return A count of valid NFTs tracked by this contract, where each one of259 /// them has an assigned and queryable owner not equal to the zero address260 fn total_supply(&self) -> Result<uint256> {261 self.consume_store_reads(1)?;262 Ok(<Pallet<T>>::total_supply(self).into())263 }264}265266/// @title ERC-721 Non-Fungible Token Standard267/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md268#[solidity_interface(name = "ERC721", events(ERC721Events))]269impl<T: Config> NonfungibleHandle<T> {270 /// @notice Count all NFTs assigned to an owner271 /// @dev NFTs assigned to the zero address are considered invalid, and this272 /// function throws for queries about the zero address.273 /// @param owner An address for whom to query the balance274 /// @return The number of NFTs owned by `owner`, possibly zero275 fn balance_of(&self, owner: address) -> Result<uint256> {276 self.consume_store_reads(1)?;277 let owner = T::CrossAccountId::from_eth(owner);278 let balance = <AccountBalance<T>>::get((self.id, owner));279 Ok(balance.into())280 }281 /// @notice Find the owner of an NFT282 /// @dev NFTs assigned to zero address are considered invalid, and queries283 /// about them do throw.284 /// @param tokenId The identifier for an NFT285 /// @return The address of the owner of the NFT286 fn owner_of(&self, token_id: uint256) -> Result<address> {287 self.consume_store_reads(1)?;288 let token: TokenId = token_id.try_into()?;289 Ok(*<TokenData<T>>::get((self.id, token))290 .ok_or("token not found")?291 .owner292 .as_eth())293 }294 /// @dev Not implemented295 fn safe_transfer_from_with_data(296 &mut self,297 _from: address,298 _to: address,299 _token_id: uint256,300 _data: bytes,301 _value: value,302 ) -> Result<void> {303 // TODO: Not implemetable304 Err("not implemented".into())305 }306 /// @dev Not implemented307 fn safe_transfer_from(308 &mut self,309 _from: address,310 _to: address,311 _token_id: uint256,312 _value: value,313 ) -> Result<void> {314 // TODO: Not implemetable315 Err("not implemented".into())316 }317318 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE319 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE320 /// THEY MAY BE PERMANENTLY LOST321 /// @dev Throws unless `msg.sender` is the current owner or an authorized322 /// operator for this NFT. Throws if `from` is not the current owner. Throws323 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.324 /// @param from The current owner of the NFT325 /// @param to The new owner326 /// @param tokenId The NFT to transfer327 /// @param _value Not used for an NFT328 #[weight(<SelfWeightOf<T>>::transfer_from())]329 fn transfer_from(330 &mut self,331 caller: caller,332 from: address,333 to: address,334 token_id: uint256,335 _value: value,336 ) -> Result<void> {337 let caller = T::CrossAccountId::from_eth(caller);338 let from = T::CrossAccountId::from_eth(from);339 let to = T::CrossAccountId::from_eth(to);340 let token = token_id.try_into()?;341 let budget = self342 .recorder343 .weight_calls_budget(<StructureWeight<T>>::find_parent());344345 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)346 .map_err(dispatch_to_evm::<T>)?;347 Ok(())348 }349350 /// @notice Set or reaffirm the approved address for an NFT351 /// @dev The zero address indicates there is no approved address.352 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized353 /// operator of the current owner.354 /// @param approved The new approved NFT controller355 /// @param tokenId The NFT to approve356 #[weight(<SelfWeightOf<T>>::approve())]357 fn approve(358 &mut self,359 caller: caller,360 approved: address,361 token_id: uint256,362 _value: value,363 ) -> Result<void> {364 let caller = T::CrossAccountId::from_eth(caller);365 let approved = T::CrossAccountId::from_eth(approved);366 let token = token_id.try_into()?;367368 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))369 .map_err(dispatch_to_evm::<T>)?;370 Ok(())371 }372373 /// @dev Not implemented374 fn set_approval_for_all(375 &mut self,376 _caller: caller,377 _operator: address,378 _approved: bool,379 ) -> Result<void> {380 // TODO: Not implemetable381 Err("not implemented".into())382 }383384 /// @dev Not implemented385 fn get_approved(&self, _token_id: uint256) -> Result<address> {386 // TODO: Not implemetable387 Err("not implemented".into())388 }389390 /// @dev Not implemented391 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {392 // TODO: Not implemetable393 Err("not implemented".into())394 }395}396397/// @title ERC721 Token that can be irreversibly burned (destroyed).398#[solidity_interface(name = "ERC721Burnable")]399impl<T: Config> NonfungibleHandle<T> {400 /// @notice Burns a specific ERC721 token.401 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized402 /// operator of the current owner.403 /// @param tokenId The NFT to approve404 #[weight(<SelfWeightOf<T>>::burn_item())]405 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {406 let caller = T::CrossAccountId::from_eth(caller);407 let token = token_id.try_into()?;408409 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;410 Ok(())411 }412}413414/// @title ERC721 minting logic.415#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]416impl<T: Config> NonfungibleHandle<T> {417 fn minting_finished(&self) -> Result<bool> {418 Ok(false)419 }420421 /// @notice Function to mint token.422 /// @dev `tokenId` should be obtained with `nextTokenId` method,423 /// unlike standard, you can't specify it manually424 /// @param to The new owner425 /// @param tokenId ID of the minted NFT426 #[weight(<SelfWeightOf<T>>::create_item())]427 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {428 let caller = T::CrossAccountId::from_eth(caller);429 let to = T::CrossAccountId::from_eth(to);430 let token_id: u32 = token_id.try_into()?;431 let budget = self432 .recorder433 .weight_calls_budget(<StructureWeight<T>>::find_parent());434435 if <TokensMinted<T>>::get(self.id)436 .checked_add(1)437 .ok_or("item id overflow")?438 != token_id439 {440 return Err("item id should be next".into());441 }442443 <Pallet<T>>::create_item(444 self,445 &caller,446 CreateItemData::<T> {447 properties: BoundedVec::default(),448 owner: to,449 },450 &budget,451 )452 .map_err(dispatch_to_evm::<T>)?;453454 Ok(true)455 }456457 /// @notice Function to mint token with the given tokenUri.458 /// @dev `tokenId` should be obtained with `nextTokenId` method,459 /// unlike standard, you can't specify it manually460 /// @param to The new owner461 /// @param tokenId ID of the minted NFT462 /// @param tokenUri Token URI that would be stored in the NFT properties463 #[solidity(rename_selector = "mintWithTokenURI")]464 #[weight(<SelfWeightOf<T>>::create_item())]465 fn mint_with_token_uri(466 &mut self,467 caller: caller,468 to: address,469 token_id: uint256,470 token_uri: string,471 ) -> Result<bool> {472 let key = token_uri_key();473 let permission = get_token_permission::<T>(self.id, &key)?;474 if !permission.collection_admin {475 return Err("Operation is not allowed".into());476 }477478 let caller = T::CrossAccountId::from_eth(caller);479 let to = T::CrossAccountId::from_eth(to);480 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;481 let budget = self482 .recorder483 .weight_calls_budget(<StructureWeight<T>>::find_parent());484485 if <TokensMinted<T>>::get(self.id)486 .checked_add(1)487 .ok_or("item id overflow")?488 != token_id489 {490 return Err("item id should be next".into());491 }492493 let mut properties = CollectionPropertiesVec::default();494 properties495 .try_push(Property {496 key,497 value: token_uri498 .into_bytes()499 .try_into()500 .map_err(|_| "token uri is too long")?,501 })502 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;503504 <Pallet<T>>::create_item(505 self,506 &caller,507 CreateItemData::<T> {508 properties,509 owner: to,510 },511 &budget,512 )513 .map_err(dispatch_to_evm::<T>)?;514 Ok(true)515 }516517 /// @dev Not implemented518 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {519 Err("not implementable".into())520 }521}522523fn get_token_permission<T: Config>(524 collection_id: CollectionId,525 key: &PropertyKey,526) -> Result<PropertyPermission> {527 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)528 .map_err(|_| Error::Revert("No permissions for collection".into()))?;529 let a = token_property_permissions530 .get(key)531 .map(|p| p.clone())532 .ok_or_else(|| Error::Revert("No permission".into()))?;533 Ok(a)534}535536fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {537 if let Ok(token_property_permissions) =538 CollectionPropertyPermissions::<T>::try_get(collection_id)539 {540 return token_property_permissions.contains_key(key);541 }542543 false544}545546/// @title Unique extensions for ERC721.547#[solidity_interface(name = "ERC721UniqueExtensions")]548impl<T: Config> NonfungibleHandle<T> {549 /// @notice Transfer ownership of an NFT550 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`551 /// is the zero address. Throws if `tokenId` is not a valid NFT.552 /// @param to The new owner553 /// @param tokenId The NFT to transfer554 /// @param _value Not used for an NFT555 #[weight(<SelfWeightOf<T>>::transfer())]556 fn transfer(557 &mut self,558 caller: caller,559 to: address,560 token_id: uint256,561 _value: value,562 ) -> Result<void> {563 let caller = T::CrossAccountId::from_eth(caller);564 let to = T::CrossAccountId::from_eth(to);565 let token = token_id.try_into()?;566 let budget = self567 .recorder568 .weight_calls_budget(<StructureWeight<T>>::find_parent());569570 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;571 Ok(())572 }573574 /// @notice Burns a specific ERC721 token.575 /// @dev Throws unless `msg.sender` is the current owner or an authorized576 /// operator for this NFT. Throws if `from` is not the current owner. Throws577 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.578 /// @param from The current owner of the NFT579 /// @param tokenId The NFT to transfer580 /// @param _value Not used for an NFT581 #[weight(<SelfWeightOf<T>>::burn_from())]582 fn burn_from(583 &mut self,584 caller: caller,585 from: address,586 token_id: uint256,587 _value: value,588 ) -> Result<void> {589 let caller = T::CrossAccountId::from_eth(caller);590 let from = T::CrossAccountId::from_eth(from);591 let token = token_id.try_into()?;592 let budget = self593 .recorder594 .weight_calls_budget(<StructureWeight<T>>::find_parent());595596 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)597 .map_err(dispatch_to_evm::<T>)?;598 Ok(())599 }600601 /// @notice Returns next free NFT ID.602 fn next_token_id(&self) -> Result<uint256> {603 self.consume_store_reads(1)?;604 Ok(<TokensMinted<T>>::get(self.id)605 .checked_add(1)606 .ok_or("item id overflow")?607 .into())608 }609610 /// @notice Function to mint multiple tokens.611 /// @dev `tokenIds` should be an array of consecutive numbers and first number612 /// should be obtained with `nextTokenId` method613 /// @param to The new owner614 /// @param tokenIds IDs of the minted NFTs615 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]616 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {617 let caller = T::CrossAccountId::from_eth(caller);618 let to = T::CrossAccountId::from_eth(to);619 let mut expected_index = <TokensMinted<T>>::get(self.id)620 .checked_add(1)621 .ok_or("item id overflow")?;622 let budget = self623 .recorder624 .weight_calls_budget(<StructureWeight<T>>::find_parent());625626 let total_tokens = token_ids.len();627 for id in token_ids.into_iter() {628 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;629 if id != expected_index {630 return Err("item id should be next".into());631 }632 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;633 }634 let data = (0..total_tokens)635 .map(|_| CreateItemData::<T> {636 properties: BoundedVec::default(),637 owner: to.clone(),638 })639 .collect();640641 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)642 .map_err(dispatch_to_evm::<T>)?;643 Ok(true)644 }645646 /// @notice Function to mint multiple tokens with the given tokenUris.647 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive648 /// numbers and first number should be obtained with `nextTokenId` method649 /// @param to The new owner650 /// @param tokens array of pairs of token ID and token URI for minted tokens651 #[solidity(rename_selector = "mintBulkWithTokenURI")]652 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]653 fn mint_bulk_with_token_uri(654 &mut self,655 caller: caller,656 to: address,657 tokens: Vec<(uint256, string)>,658 ) -> Result<bool> {659 let key = token_uri_key();660 let caller = T::CrossAccountId::from_eth(caller);661 let to = T::CrossAccountId::from_eth(to);662 let mut expected_index = <TokensMinted<T>>::get(self.id)663 .checked_add(1)664 .ok_or("item id overflow")?;665 let budget = self666 .recorder667 .weight_calls_budget(<StructureWeight<T>>::find_parent());668669 let mut data = Vec::with_capacity(tokens.len());670 for (id, token_uri) in tokens {671 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;672 if id != expected_index {673 return Err("item id should be next".into());674 }675 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;676677 let mut properties = CollectionPropertiesVec::default();678 properties679 .try_push(Property {680 key: key.clone(),681 value: token_uri682 .into_bytes()683 .try_into()684 .map_err(|_| "token uri is too long")?,685 })686 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;687688 data.push(CreateItemData::<T> {689 properties,690 owner: to.clone(),691 });692 }693694 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)695 .map_err(dispatch_to_evm::<T>)?;696 Ok(true)697 }698}699700#[solidity_interface(701 name = "UniqueNFT",702 is(703 ERC721,704 ERC721Metadata,705 ERC721Enumerable,706 ERC721UniqueExtensions,707 ERC721Mintable,708 ERC721Burnable,709 via("CollectionHandle<T>", common_mut, Collection),710 TokenProperties,711 )712)]713impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> {}714715// Not a tests, but code generators716generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);717generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);718719impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>720where721 T::AccountId: From<[u8; 32]>,722{723 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");724725 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {726 call::<T, UniqueNFTCall<T>, _, _>(handle, self)727 }728}pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -17,18 +17,18 @@
//! Implementation of CollectionHelpers contract.
use core::marker::PhantomData;
-use evm_coder::{execution::*, generate_stubgen, solidity_interface, weight, types::*};
+use evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};
use ethereum as _;
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
use pallet_evm::{OnMethodCall, PrecompileResult, account::CrossAccountId, PrecompileHandle};
use up_data_structs::{
- CreateCollectionData, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
- MAX_COLLECTION_NAME_LENGTH,
+ CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,
+ CollectionMode, PropertyValue,
};
use frame_support::traits::Get;
use pallet_common::{
CollectionById,
- erc::{token_uri_key, CollectionHelpersEvents},
+ erc::{static_property_key_value::*, CollectionHelpersEvents},
};
use crate::{SelfWeightOf, Config, weights::WeightInfo};
@@ -47,6 +47,116 @@
}
}
+fn convert_data<T: Config>(
+ caller: caller,
+ name: string,
+ description: string,
+ token_prefix: string,
+ base_uri: string,
+) -> Result<(
+ T::CrossAccountId,
+ CollectionName,
+ CollectionDescription,
+ CollectionTokenPrefix,
+ PropertyValue,
+)> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ let name = name
+ .encode_utf16()
+ .collect::<Vec<u16>>()
+ .try_into()
+ .map_err(|_| error_feild_too_long(stringify!(name), CollectionName::bound()))?;
+ let description = description
+ .encode_utf16()
+ .collect::<Vec<u16>>()
+ .try_into()
+ .map_err(|_| {
+ error_feild_too_long(stringify!(description), CollectionDescription::bound())
+ })?;
+ let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {
+ error_feild_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())
+ })?;
+ let base_uri_value = base_uri
+ .into_bytes()
+ .try_into()
+ .map_err(|_| error_feild_too_long(stringify!(token_prefix), PropertyValue::bound()))?;
+ Ok((caller, name, description, token_prefix, base_uri_value))
+}
+
+fn make_data<T: Config>(
+ name: CollectionName,
+ mode: CollectionMode,
+ description: CollectionDescription,
+ token_prefix: CollectionTokenPrefix,
+ base_uri_value: PropertyValue,
+ add_properties: bool,
+) -> Result<CreateCollectionData<T::AccountId>> {
+ let mut collection_properties = up_data_structs::CollectionPropertiesVec::default();
+ let mut token_property_permissions =
+ up_data_structs::CollectionPropertiesPermissionsVec::default();
+
+ if add_properties {
+ token_property_permissions
+ .try_push(up_data_structs::PropertyKeyPermission {
+ key: token_uri_key(),
+ permission: up_data_structs::PropertyPermission {
+ mutable: true,
+ collection_admin: true,
+ token_owner: false,
+ },
+ })
+ .map_err(|e| Error::Revert(format!("{:?}", e)))?;
+
+ token_property_permissions
+ .try_push(up_data_structs::PropertyKeyPermission {
+ key: u_key(),
+ permission: up_data_structs::PropertyPermission {
+ mutable: false,
+ collection_admin: true,
+ token_owner: false,
+ },
+ })
+ .map_err(|e| Error::Revert(format!("{:?}", e)))?;
+
+ token_property_permissions
+ .try_push(up_data_structs::PropertyKeyPermission {
+ key: s_key(),
+ permission: up_data_structs::PropertyPermission {
+ mutable: false,
+ collection_admin: true,
+ token_owner: false,
+ },
+ })
+ .map_err(|e| Error::Revert(format!("{:?}", e)))?;
+
+ collection_properties
+ .try_push(up_data_structs::Property {
+ key: schema_name_key(),
+ value: erc721_value(),
+ })
+ .map_err(|e| Error::Revert(format!("{:?}", e)))?;
+
+ if !base_uri_value.is_empty() {
+ collection_properties
+ .try_push(up_data_structs::Property {
+ key: base_uri_key(),
+ value: base_uri_value,
+ })
+ .map_err(|e| Error::Revert(format!("{:?}", e)))?;
+ }
+ }
+
+ let data = CreateCollectionData {
+ name,
+ mode,
+ description,
+ token_prefix,
+ token_property_permissions,
+ ..Default::default()
+ };
+ Ok(data)
+}
+
/// @title Contract, which allows users to operate with collections
#[solidity_interface(name = "CollectionHelpers", events(CollectionHelpersEvents))]
impl<T: Config + pallet_nonfungible::Config> EvmCollectionHelpers<T> {
@@ -63,44 +173,30 @@
description: string,
token_prefix: string,
) -> Result<address> {
- let caller = T::CrossAccountId::from_eth(caller);
- let name = name
- .encode_utf16()
- .collect::<Vec<u16>>()
- .try_into()
- .map_err(|_| error_feild_too_long(stringify!(name), MAX_COLLECTION_NAME_LENGTH))?;
- let description = description
- .encode_utf16()
- .collect::<Vec<u16>>()
- .try_into()
- .map_err(|_| {
- error_feild_too_long(stringify!(description), MAX_COLLECTION_DESCRIPTION_LENGTH)
- })?;
- let token_prefix = token_prefix
- .into_bytes()
- .try_into()
- .map_err(|_| error_feild_too_long(stringify!(token_prefix), MAX_TOKEN_PREFIX_LENGTH))?;
+ let (caller, name, description, token_prefix, _base_uri_value) =
+ convert_data::<T>(caller, name, description, token_prefix, "".into())?;
+ let data = make_data::<T>(name, CollectionMode::NFT, description, token_prefix, Default::default(), false)?;
+ let collection_id =
+ <pallet_nonfungible::Pallet<T>>::init_collection(caller.clone(), data, false)
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
- let key = token_uri_key();
- let permission = up_data_structs::PropertyPermission {
- mutable: true,
- collection_admin: true,
- token_owner: false,
- };
- let mut token_property_permissions =
- up_data_structs::CollectionPropertiesPermissionsVec::default();
- token_property_permissions
- .try_push(up_data_structs::PropertyKeyPermission { key, permission })
- .map_err(|e| Error::Revert(format!("{:?}", e)))?;
+ let address = pallet_common::eth::collection_id_to_address(collection_id);
+ Ok(address)
+ }
- let data = CreateCollectionData {
- name,
- description,
- token_prefix,
- token_property_permissions,
- ..Default::default()
- };
-
+ #[weight(<SelfWeightOf<T>>::create_collection())]
+ #[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]
+ fn create_nonfungible_collection_with_properties(
+ &mut self,
+ caller: caller,
+ name: string,
+ description: string,
+ token_prefix: string,
+ base_uri: string,
+ ) -> Result<address> {
+ let (caller, name, description, token_prefix, base_uri_value) =
+ convert_data::<T>(caller, name, description, token_prefix, base_uri)?;
+ let data = make_data::<T>(name, CollectionMode::NFT, description, token_prefix, base_uri_value, true)?;
let collection_id =
<pallet_nonfungible::Pallet<T>>::init_collection(caller.clone(), data, false)
.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
@@ -152,6 +248,6 @@
generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);
generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);
-fn error_feild_too_long(feild: &str, bound: u32) -> Error {
+fn error_feild_too_long(feild: &str, bound: usize) -> Error {
Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))
}
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -286,6 +286,10 @@
}
}
+pub type CollectionName = BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>;
+pub type CollectionDescription = BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>;
+pub type CollectionTokenPrefix = BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>;
+
/// Collection parameters, used in storage (see [`RpcCollection`] for the RPC version).
#[struct_versioning::versioned(version = 2, upper)]
#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]