difftreelog
chore add check in `supports_metadata`
in: master
9 files changed
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -225,10 +225,6 @@
/// @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")?;
match get_token_property(self, token_id_u32, &key::url()).as_deref() {
@@ -714,13 +710,17 @@
impl<T: Config> NonfungibleHandle<T> {
pub fn supports_metadata(&self) -> bool {
- if let Some(erc721_metadata) =
+ let has_metadata_support_enabled = 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
- }
+ };
+
+ let has_url_property_permissions = get_token_permission::<T>(self.id, &key::url()).is_ok();
+
+ has_metadata_support_enabled && has_url_property_permissions
}
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -108,7 +108,6 @@
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_common::{
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
- erc::static_property::{key, value},
eth::collection_id_to_address,
};
use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
pallets/refungible/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//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use core::{25 char::{REPLACEMENT_CHARACTER, decode_utf16},26 convert::TryInto,27};28use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};29use frame_support::{BoundedBTreeMap, BoundedVec};30use pallet_common::{31 CollectionHandle, CollectionPropertyPermissions,32 erc::{CommonEvmHandler, CollectionCall, static_property::key, static_property::value},33};34use pallet_evm::{account::CrossAccountId, PrecompileHandle};35use pallet_evm_coder_substrate::{call, dispatch_to_evm};36use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};37use sp_core::H160;38use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};39use up_data_structs::{40 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,41 PropertyKeyPermission, PropertyPermission, TokenId,42};4344use crate::{45 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,46 TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,47};4849pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);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> RefungibleHandle<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_token_property_permissions(70 self,71 &caller,72 vec![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 event emits when NFTs are created (`from` == 0) and destroyed159 /// (`to` == 0). Exception: during contract creation, any number of RFTs160 /// may be created and assigned without emitting Transfer.161 Transfer {162 #[indexed]163 from: address,164 #[indexed]165 to: address,166 #[indexed]167 token_id: uint256,168 },169 /// @dev Not supported170 Approval {171 #[indexed]172 owner: address,173 #[indexed]174 approved: address,175 #[indexed]176 token_id: uint256,177 },178 /// @dev Not supported179 #[allow(dead_code)]180 ApprovalForAll {181 #[indexed]182 owner: address,183 #[indexed]184 operator: address,185 approved: bool,186 },187}188189#[derive(ToLog)]190pub enum ERC721MintableEvents {191 /// @dev Not supported192 #[allow(dead_code)]193 MintingFinished {},194}195196#[solidity_interface(name = ERC721Metadata)]197impl<T: Config> RefungibleHandle<T> {198 /// @notice A descriptive name for a collection of RFTs in this contract199 fn name(&self) -> Result<string> {200 Ok(decode_utf16(self.name.iter().copied())201 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))202 .collect::<string>())203 }204205 /// @notice An abbreviated name for RFTs in this contract206 fn symbol(&self) -> Result<string> {207 Ok(string::from_utf8_lossy(&self.token_prefix).into())208 }209210 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.211 ///212 /// @dev If the token has a `url` property and it is not empty, it is returned.213 /// 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`.214 /// If the collection property `baseURI` is empty or absent, return "" (empty string)215 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix216 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).217 ///218 /// @return token's const_metadata219 #[solidity(rename_selector = "tokenURI")]220 fn token_uri(&self, token_id: uint256) -> Result<string> {221 if !self.supports_metadata() {222 return Ok("".into());223 }224225 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;226227 match get_token_property(self, token_id_u32, &key::url()).as_deref() {228 Err(_) | Ok("") => (),229 Ok(url) => {230 return Ok(url.into());231 }232 };233234 let base_uri =235 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())236 .map(BoundedVec::into_inner)237 .map(string::from_utf8)238 .transpose()239 .map_err(|e| {240 Error::Revert(alloc::format!(241 "Can not convert value \"baseURI\" to string with error \"{}\"",242 e243 ))244 })?;245246 let base_uri = match base_uri.as_deref() {247 None | Some("") => {248 return Ok("".into());249 }250 Some(base_uri) => base_uri.into(),251 };252253 Ok(254 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {255 Err(_) | Ok("") => base_uri,256 Ok(suffix) => base_uri + suffix,257 },258 )259 }260}261262/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension263/// @dev See https://eips.ethereum.org/EIPS/eip-721264#[solidity_interface(name = ERC721Enumerable)]265impl<T: Config> RefungibleHandle<T> {266 /// @notice Enumerate valid RFTs267 /// @param index A counter less than `totalSupply()`268 /// @return The token identifier for the `index`th NFT,269 /// (sort order not specified)270 fn token_by_index(&self, index: uint256) -> Result<uint256> {271 Ok(index)272 }273274 /// Not implemented275 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {276 // TODO: Not implemetable277 Err("not implemented".into())278 }279280 /// @notice Count RFTs tracked by this contract281 /// @return A count of valid RFTs tracked by this contract, where each one of282 /// them has an assigned and queryable owner not equal to the zero address283 fn total_supply(&self) -> Result<uint256> {284 self.consume_store_reads(1)?;285 Ok(<Pallet<T>>::total_supply(self).into())286 }287}288289/// @title ERC-721 Non-Fungible Token Standard290/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md291#[solidity_interface(name = ERC721, events(ERC721Events))]292impl<T: Config> RefungibleHandle<T> {293 /// @notice Count all RFTs assigned to an owner294 /// @dev RFTs assigned to the zero address are considered invalid, and this295 /// function throws for queries about the zero address.296 /// @param owner An address for whom to query the balance297 /// @return The number of RFTs owned by `owner`, possibly zero298 fn balance_of(&self, owner: address) -> Result<uint256> {299 self.consume_store_reads(1)?;300 let owner = T::CrossAccountId::from_eth(owner);301 let balance = <AccountBalance<T>>::get((self.id, owner));302 Ok(balance.into())303 }304305 /// @notice Find the owner of an RFT306 /// @dev RFTs assigned to zero address are considered invalid, and queries307 /// about them do throw.308 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for309 /// the tokens that are partially owned.310 /// @param tokenId The identifier for an RFT311 /// @return The address of the owner of the RFT312 fn owner_of(&self, token_id: uint256) -> Result<address> {313 self.consume_store_reads(2)?;314 let token = token_id.try_into()?;315 let owner = <Pallet<T>>::token_owner(self.id, token);316 Ok(owner317 .map(|address| *address.as_eth())318 .unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))319 }320321 /// @dev Not implemented322 fn safe_transfer_from_with_data(323 &mut self,324 _from: address,325 _to: address,326 _token_id: uint256,327 _data: bytes,328 ) -> Result<void> {329 // TODO: Not implemetable330 Err("not implemented".into())331 }332333 /// @dev Not implemented334 fn safe_transfer_from(335 &mut self,336 _from: address,337 _to: address,338 _token_id: uint256,339 ) -> Result<void> {340 // TODO: Not implemetable341 Err("not implemented".into())342 }343344 /// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE345 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE346 /// THEY MAY BE PERMANENTLY LOST347 /// @dev Throws unless `msg.sender` is the current owner or an authorized348 /// operator for this RFT. Throws if `from` is not the current owner. Throws349 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.350 /// Throws if RFT pieces have multiple owners.351 /// @param from The current owner of the NFT352 /// @param to The new owner353 /// @param tokenId The NFT to transfer354 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]355 fn transfer_from(356 &mut self,357 caller: caller,358 from: address,359 to: address,360 token_id: uint256,361 ) -> Result<void> {362 let caller = T::CrossAccountId::from_eth(caller);363 let from = T::CrossAccountId::from_eth(from);364 let to = T::CrossAccountId::from_eth(to);365 let token = token_id.try_into()?;366 let budget = self367 .recorder368 .weight_calls_budget(<StructureWeight<T>>::find_parent());369370 let balance = balance(&self, token, &from)?;371 ensure_single_owner(&self, token, balance)?;372373 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)374 .map_err(dispatch_to_evm::<T>)?;375376 Ok(())377 }378379 /// @dev Not implemented380 fn approve(&mut self, _caller: caller, _approved: address, _token_id: uint256) -> Result<void> {381 Err("not implemented".into())382 }383384 /// @dev Not implemented385 fn set_approval_for_all(386 &mut self,387 _caller: caller,388 _operator: address,389 _approved: bool,390 ) -> Result<void> {391 // TODO: Not implemetable392 Err("not implemented".into())393 }394395 /// @dev Not implemented396 fn get_approved(&self, _token_id: uint256) -> Result<address> {397 // TODO: Not implemetable398 Err("not implemented".into())399 }400401 /// @dev Not implemented402 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {403 // TODO: Not implemetable404 Err("not implemented".into())405 }406}407408/// Returns amount of pieces of `token` that `owner` have409pub fn balance<T: Config>(410 collection: &RefungibleHandle<T>,411 token: TokenId,412 owner: &T::CrossAccountId,413) -> Result<u128> {414 collection.consume_store_reads(1)?;415 let balance = <Balance<T>>::get((collection.id, token, &owner));416 Ok(balance)417}418419/// Throws if `owner_balance` is lower than total amount of `token` pieces420pub fn ensure_single_owner<T: Config>(421 collection: &RefungibleHandle<T>,422 token: TokenId,423 owner_balance: u128,424) -> Result<()> {425 collection.consume_store_reads(1)?;426 let total_supply = <TotalSupply<T>>::get((collection.id, token));427 if total_supply != owner_balance {428 return Err("token has multiple owners".into());429 }430 Ok(())431}432433/// @title ERC721 Token that can be irreversibly burned (destroyed).434#[solidity_interface(name = ERC721Burnable)]435impl<T: Config> RefungibleHandle<T> {436 /// @notice Burns a specific ERC721 token.437 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized438 /// operator of the current owner.439 /// @param tokenId The RFT to approve440 #[weight(<SelfWeightOf<T>>::burn_item_fully())]441 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {442 let caller = T::CrossAccountId::from_eth(caller);443 let token = token_id.try_into()?;444445 let balance = balance(&self, token, &caller)?;446 ensure_single_owner(&self, token, balance)?;447448 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;449 Ok(())450 }451}452453/// @title ERC721 minting logic.454#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]455impl<T: Config> RefungibleHandle<T> {456 fn minting_finished(&self) -> Result<bool> {457 Ok(false)458 }459460 /// @notice Function to mint token.461 /// @dev `tokenId` should be obtained with `nextTokenId` method,462 /// unlike standard, you can't specify it manually463 /// @param to The new owner464 /// @param tokenId ID of the minted RFT465 #[weight(<SelfWeightOf<T>>::create_item())]466 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {467 let caller = T::CrossAccountId::from_eth(caller);468 let to = T::CrossAccountId::from_eth(to);469 let token_id: u32 = token_id.try_into()?;470 let budget = self471 .recorder472 .weight_calls_budget(<StructureWeight<T>>::find_parent());473474 if <TokensMinted<T>>::get(self.id)475 .checked_add(1)476 .ok_or("item id overflow")?477 != token_id478 {479 return Err("item id should be next".into());480 }481482 let users = [(to.clone(), 1)]483 .into_iter()484 .collect::<BTreeMap<_, _>>()485 .try_into()486 .unwrap();487 <Pallet<T>>::create_item(488 self,489 &caller,490 CreateItemData::<T::CrossAccountId> {491 users,492 properties: CollectionPropertiesVec::default(),493 },494 &budget,495 )496 .map_err(dispatch_to_evm::<T>)?;497498 Ok(true)499 }500501 /// @notice Function to mint token with the given tokenUri.502 /// @dev `tokenId` should be obtained with `nextTokenId` method,503 /// unlike standard, you can't specify it manually504 /// @param to The new owner505 /// @param tokenId ID of the minted RFT506 /// @param tokenUri Token URI that would be stored in the RFT properties507 #[solidity(rename_selector = "mintWithTokenURI")]508 #[weight(<SelfWeightOf<T>>::create_item())]509 fn mint_with_token_uri(510 &mut self,511 caller: caller,512 to: address,513 token_id: uint256,514 token_uri: string,515 ) -> Result<bool> {516 let key = key::url();517 let permission = get_token_permission::<T>(self.id, &key)?;518 if !permission.collection_admin {519 return Err("Operation is not allowed".into());520 }521522 let caller = T::CrossAccountId::from_eth(caller);523 let to = T::CrossAccountId::from_eth(to);524 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;525 let budget = self526 .recorder527 .weight_calls_budget(<StructureWeight<T>>::find_parent());528529 if <TokensMinted<T>>::get(self.id)530 .checked_add(1)531 .ok_or("item id overflow")?532 != token_id533 {534 return Err("item id should be next".into());535 }536537 let mut properties = CollectionPropertiesVec::default();538 properties539 .try_push(Property {540 key,541 value: token_uri542 .into_bytes()543 .try_into()544 .map_err(|_| "token uri is too long")?,545 })546 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;547548 let users = [(to.clone(), 1)]549 .into_iter()550 .collect::<BTreeMap<_, _>>()551 .try_into()552 .unwrap();553 <Pallet<T>>::create_item(554 self,555 &caller,556 CreateItemData::<T::CrossAccountId> { users, properties },557 &budget,558 )559 .map_err(dispatch_to_evm::<T>)?;560 Ok(true)561 }562563 /// @dev Not implemented564 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {565 Err("not implementable".into())566 }567}568569fn get_token_property<T: Config>(570 collection: &CollectionHandle<T>,571 token_id: u32,572 key: &up_data_structs::PropertyKey,573) -> Result<string> {574 collection.consume_store_reads(1)?;575 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))576 .map_err(|_| Error::Revert("Token properties not found".into()))?;577 if let Some(property) = properties.get(key) {578 return Ok(string::from_utf8_lossy(property).into());579 }580581 Err("Property tokenURI not found".into())582}583584fn get_token_permission<T: Config>(585 collection_id: CollectionId,586 key: &PropertyKey,587) -> Result<PropertyPermission> {588 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)589 .map_err(|_| Error::Revert("No permissions for collection".into()))?;590 let a = token_property_permissions591 .get(key)592 .map(Clone::clone)593 .ok_or_else(|| {594 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();595 Error::Revert(alloc::format!("No permission for key {}", key))596 })?;597 Ok(a)598}599600/// @title Unique extensions for ERC721.601#[solidity_interface(name = ERC721UniqueExtensions)]602impl<T: Config> RefungibleHandle<T> {603 /// @notice Transfer ownership of an RFT604 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`605 /// is the zero address. Throws if `tokenId` is not a valid RFT.606 /// Throws if RFT pieces have multiple owners.607 /// @param to The new owner608 /// @param tokenId The RFT to transfer609 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]610 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {611 let caller = T::CrossAccountId::from_eth(caller);612 let to = T::CrossAccountId::from_eth(to);613 let token = token_id.try_into()?;614 let budget = self615 .recorder616 .weight_calls_budget(<StructureWeight<T>>::find_parent());617618 let balance = balance(&self, token, &caller)?;619 ensure_single_owner(&self, token, balance)?;620621 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)622 .map_err(dispatch_to_evm::<T>)?;623 Ok(())624 }625626 /// @notice Burns a specific ERC721 token.627 /// @dev Throws unless `msg.sender` is the current owner or an authorized628 /// operator for this RFT. Throws if `from` is not the current owner. Throws629 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.630 /// Throws if RFT pieces have multiple owners.631 /// @param from The current owner of the RFT632 /// @param tokenId The RFT to transfer633 #[weight(<SelfWeightOf<T>>::burn_from())]634 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {635 let caller = T::CrossAccountId::from_eth(caller);636 let from = T::CrossAccountId::from_eth(from);637 let token = token_id.try_into()?;638 let budget = self639 .recorder640 .weight_calls_budget(<StructureWeight<T>>::find_parent());641642 let balance = balance(&self, token, &caller)?;643 ensure_single_owner(&self, token, balance)?;644645 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)646 .map_err(dispatch_to_evm::<T>)?;647 Ok(())648 }649650 /// @notice Returns next free RFT ID.651 fn next_token_id(&self) -> Result<uint256> {652 self.consume_store_reads(1)?;653 Ok(<TokensMinted<T>>::get(self.id)654 .checked_add(1)655 .ok_or("item id overflow")?656 .into())657 }658659 /// @notice Function to mint multiple tokens.660 /// @dev `tokenIds` should be an array of consecutive numbers and first number661 /// should be obtained with `nextTokenId` method662 /// @param to The new owner663 /// @param tokenIds IDs of the minted RFTs664 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]665 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {666 let caller = T::CrossAccountId::from_eth(caller);667 let to = T::CrossAccountId::from_eth(to);668 let mut expected_index = <TokensMinted<T>>::get(self.id)669 .checked_add(1)670 .ok_or("item id overflow")?;671 let budget = self672 .recorder673 .weight_calls_budget(<StructureWeight<T>>::find_parent());674675 let total_tokens = token_ids.len();676 for id in token_ids.into_iter() {677 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;678 if id != expected_index {679 return Err("item id should be next".into());680 }681 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;682 }683 let users = [(to.clone(), 1)]684 .into_iter()685 .collect::<BTreeMap<_, _>>()686 .try_into()687 .unwrap();688 let create_item_data = CreateItemData::<T::CrossAccountId> {689 users,690 properties: CollectionPropertiesVec::default(),691 };692 let data = (0..total_tokens)693 .map(|_| create_item_data.clone())694 .collect();695696 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)697 .map_err(dispatch_to_evm::<T>)?;698 Ok(true)699 }700701 /// @notice Function to mint multiple tokens with the given tokenUris.702 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive703 /// numbers and first number should be obtained with `nextTokenId` method704 /// @param to The new owner705 /// @param tokens array of pairs of token ID and token URI for minted tokens706 #[solidity(rename_selector = "mintBulkWithTokenURI")]707 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]708 fn mint_bulk_with_token_uri(709 &mut self,710 caller: caller,711 to: address,712 tokens: Vec<(uint256, string)>,713 ) -> Result<bool> {714 let key = key::url();715 let caller = T::CrossAccountId::from_eth(caller);716 let to = T::CrossAccountId::from_eth(to);717 let mut expected_index = <TokensMinted<T>>::get(self.id)718 .checked_add(1)719 .ok_or("item id overflow")?;720 let budget = self721 .recorder722 .weight_calls_budget(<StructureWeight<T>>::find_parent());723724 let mut data = Vec::with_capacity(tokens.len());725 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]726 .into_iter()727 .collect::<BTreeMap<_, _>>()728 .try_into()729 .unwrap();730 for (id, token_uri) in tokens {731 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;732 if id != expected_index {733 return Err("item id should be next".into());734 }735 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;736737 let mut properties = CollectionPropertiesVec::default();738 properties739 .try_push(Property {740 key: key.clone(),741 value: token_uri742 .into_bytes()743 .try_into()744 .map_err(|_| "token uri is too long")?,745 })746 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;747748 let create_item_data = CreateItemData::<T::CrossAccountId> {749 users: users.clone(),750 properties,751 };752 data.push(create_item_data);753 }754755 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)756 .map_err(dispatch_to_evm::<T>)?;757 Ok(true)758 }759760 /// Returns EVM address for refungible token761 ///762 /// @param token ID of the token763 fn token_contract_address(&self, token: uint256) -> Result<address> {764 Ok(T::EvmTokenAddressMapping::token_to_address(765 self.id,766 token.try_into().map_err(|_| "token id overflow")?,767 ))768 }769}770771impl<T: Config> RefungibleHandle<T> {772 pub fn supports_metadata(&self) -> bool {773 if let Some(erc721_metadata) =774 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::erc721_metadata())775 {776 *erc721_metadata.into_inner() == *value::ERC721_METADATA_SUPPORTED777 } else {778 false779 }780 }781}782783#[solidity_interface(784 name = UniqueRefungible,785 is(786 ERC721,787 ERC721Enumerable,788 ERC721UniqueExtensions,789 ERC721Mintable,790 ERC721Burnable,791 Collection(via(common_mut returns CollectionHandle<T>)),792 TokenProperties,793 ERC721Metadata(if(this.supports_metadata())),794 )795)]796impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}797798// Not a tests, but code generators799generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);800generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);801802impl<T: Config> CommonEvmHandler for RefungibleHandle<T>803where804 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,805{806 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");807 fn call(808 self,809 handle: &mut impl PrecompileHandle,810 ) -> Option<pallet_common::erc::PrecompileResult> {811 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)812 }813}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//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use core::{25 char::{REPLACEMENT_CHARACTER, decode_utf16},26 convert::TryInto,27};28use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};29use frame_support::{BoundedBTreeMap, BoundedVec};30use pallet_common::{31 CollectionHandle, CollectionPropertyPermissions,32 erc::{CommonEvmHandler, CollectionCall, static_property::key, static_property::value},33};34use pallet_evm::{account::CrossAccountId, PrecompileHandle};35use pallet_evm_coder_substrate::{call, dispatch_to_evm};36use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};37use sp_core::H160;38use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};39use up_data_structs::{40 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,41 PropertyKeyPermission, PropertyPermission, TokenId,42};4344use crate::{45 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,46 TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,47};4849pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);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> RefungibleHandle<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_token_property_permissions(70 self,71 &caller,72 vec![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 event emits when NFTs are created (`from` == 0) and destroyed159 /// (`to` == 0). Exception: during contract creation, any number of RFTs160 /// may be created and assigned without emitting Transfer.161 Transfer {162 #[indexed]163 from: address,164 #[indexed]165 to: address,166 #[indexed]167 token_id: uint256,168 },169 /// @dev Not supported170 Approval {171 #[indexed]172 owner: address,173 #[indexed]174 approved: address,175 #[indexed]176 token_id: uint256,177 },178 /// @dev Not supported179 #[allow(dead_code)]180 ApprovalForAll {181 #[indexed]182 owner: address,183 #[indexed]184 operator: address,185 approved: bool,186 },187}188189#[derive(ToLog)]190pub enum ERC721MintableEvents {191 /// @dev Not supported192 #[allow(dead_code)]193 MintingFinished {},194}195196#[solidity_interface(name = ERC721Metadata)]197impl<T: Config> RefungibleHandle<T> {198 /// @notice A descriptive name for a collection of RFTs in this contract199 fn name(&self) -> Result<string> {200 Ok(decode_utf16(self.name.iter().copied())201 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))202 .collect::<string>())203 }204205 /// @notice An abbreviated name for RFTs in this contract206 fn symbol(&self) -> Result<string> {207 Ok(string::from_utf8_lossy(&self.token_prefix).into())208 }209210 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.211 ///212 /// @dev If the token has a `url` property and it is not empty, it is returned.213 /// 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`.214 /// If the collection property `baseURI` is empty or absent, return "" (empty string)215 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix216 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).217 ///218 /// @return token's const_metadata219 #[solidity(rename_selector = "tokenURI")]220 fn token_uri(&self, token_id: uint256) -> Result<string> {221 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;222223 match get_token_property(self, token_id_u32, &key::url()).as_deref() {224 Err(_) | Ok("") => (),225 Ok(url) => {226 return Ok(url.into());227 }228 };229230 let base_uri =231 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())232 .map(BoundedVec::into_inner)233 .map(string::from_utf8)234 .transpose()235 .map_err(|e| {236 Error::Revert(alloc::format!(237 "Can not convert value \"baseURI\" to string with error \"{}\"",238 e239 ))240 })?;241242 let base_uri = match base_uri.as_deref() {243 None | Some("") => {244 return Ok("".into());245 }246 Some(base_uri) => base_uri.into(),247 };248249 Ok(250 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {251 Err(_) | Ok("") => base_uri,252 Ok(suffix) => base_uri + suffix,253 },254 )255 }256}257258/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension259/// @dev See https://eips.ethereum.org/EIPS/eip-721260#[solidity_interface(name = ERC721Enumerable)]261impl<T: Config> RefungibleHandle<T> {262 /// @notice Enumerate valid RFTs263 /// @param index A counter less than `totalSupply()`264 /// @return The token identifier for the `index`th NFT,265 /// (sort order not specified)266 fn token_by_index(&self, index: uint256) -> Result<uint256> {267 Ok(index)268 }269270 /// Not implemented271 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {272 // TODO: Not implemetable273 Err("not implemented".into())274 }275276 /// @notice Count RFTs tracked by this contract277 /// @return A count of valid RFTs tracked by this contract, where each one of278 /// them has an assigned and queryable owner not equal to the zero address279 fn total_supply(&self) -> Result<uint256> {280 self.consume_store_reads(1)?;281 Ok(<Pallet<T>>::total_supply(self).into())282 }283}284285/// @title ERC-721 Non-Fungible Token Standard286/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md287#[solidity_interface(name = ERC721, events(ERC721Events))]288impl<T: Config> RefungibleHandle<T> {289 /// @notice Count all RFTs assigned to an owner290 /// @dev RFTs assigned to the zero address are considered invalid, and this291 /// function throws for queries about the zero address.292 /// @param owner An address for whom to query the balance293 /// @return The number of RFTs owned by `owner`, possibly zero294 fn balance_of(&self, owner: address) -> Result<uint256> {295 self.consume_store_reads(1)?;296 let owner = T::CrossAccountId::from_eth(owner);297 let balance = <AccountBalance<T>>::get((self.id, owner));298 Ok(balance.into())299 }300301 /// @notice Find the owner of an RFT302 /// @dev RFTs assigned to zero address are considered invalid, and queries303 /// about them do throw.304 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for305 /// the tokens that are partially owned.306 /// @param tokenId The identifier for an RFT307 /// @return The address of the owner of the RFT308 fn owner_of(&self, token_id: uint256) -> Result<address> {309 self.consume_store_reads(2)?;310 let token = token_id.try_into()?;311 let owner = <Pallet<T>>::token_owner(self.id, token);312 Ok(owner313 .map(|address| *address.as_eth())314 .unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))315 }316317 /// @dev Not implemented318 fn safe_transfer_from_with_data(319 &mut self,320 _from: address,321 _to: address,322 _token_id: uint256,323 _data: bytes,324 ) -> Result<void> {325 // TODO: Not implemetable326 Err("not implemented".into())327 }328329 /// @dev Not implemented330 fn safe_transfer_from(331 &mut self,332 _from: address,333 _to: address,334 _token_id: uint256,335 ) -> Result<void> {336 // TODO: Not implemetable337 Err("not implemented".into())338 }339340 /// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE341 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE342 /// THEY MAY BE PERMANENTLY LOST343 /// @dev Throws unless `msg.sender` is the current owner or an authorized344 /// operator for this RFT. Throws if `from` is not the current owner. Throws345 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.346 /// Throws if RFT pieces have multiple owners.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_creating_removing())]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 let balance = balance(&self, token, &from)?;367 ensure_single_owner(&self, token, balance)?;368369 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)370 .map_err(dispatch_to_evm::<T>)?;371372 Ok(())373 }374375 /// @dev Not implemented376 fn approve(&mut self, _caller: caller, _approved: address, _token_id: uint256) -> Result<void> {377 Err("not implemented".into())378 }379380 /// @dev Not implemented381 fn set_approval_for_all(382 &mut self,383 _caller: caller,384 _operator: address,385 _approved: bool,386 ) -> Result<void> {387 // TODO: Not implemetable388 Err("not implemented".into())389 }390391 /// @dev Not implemented392 fn get_approved(&self, _token_id: uint256) -> Result<address> {393 // TODO: Not implemetable394 Err("not implemented".into())395 }396397 /// @dev Not implemented398 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {399 // TODO: Not implemetable400 Err("not implemented".into())401 }402}403404/// Returns amount of pieces of `token` that `owner` have405pub fn balance<T: Config>(406 collection: &RefungibleHandle<T>,407 token: TokenId,408 owner: &T::CrossAccountId,409) -> Result<u128> {410 collection.consume_store_reads(1)?;411 let balance = <Balance<T>>::get((collection.id, token, &owner));412 Ok(balance)413}414415/// Throws if `owner_balance` is lower than total amount of `token` pieces416pub fn ensure_single_owner<T: Config>(417 collection: &RefungibleHandle<T>,418 token: TokenId,419 owner_balance: u128,420) -> Result<()> {421 collection.consume_store_reads(1)?;422 let total_supply = <TotalSupply<T>>::get((collection.id, token));423 if total_supply != owner_balance {424 return Err("token has multiple owners".into());425 }426 Ok(())427}428429/// @title ERC721 Token that can be irreversibly burned (destroyed).430#[solidity_interface(name = ERC721Burnable)]431impl<T: Config> RefungibleHandle<T> {432 /// @notice Burns a specific ERC721 token.433 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized434 /// operator of the current owner.435 /// @param tokenId The RFT to approve436 #[weight(<SelfWeightOf<T>>::burn_item_fully())]437 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {438 let caller = T::CrossAccountId::from_eth(caller);439 let token = token_id.try_into()?;440441 let balance = balance(&self, token, &caller)?;442 ensure_single_owner(&self, token, balance)?;443444 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;445 Ok(())446 }447}448449/// @title ERC721 minting logic.450#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]451impl<T: Config> RefungibleHandle<T> {452 fn minting_finished(&self) -> Result<bool> {453 Ok(false)454 }455456 /// @notice Function to mint token.457 /// @dev `tokenId` should be obtained with `nextTokenId` method,458 /// unlike standard, you can't specify it manually459 /// @param to The new owner460 /// @param tokenId ID of the minted RFT461 #[weight(<SelfWeightOf<T>>::create_item())]462 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {463 let caller = T::CrossAccountId::from_eth(caller);464 let to = T::CrossAccountId::from_eth(to);465 let token_id: u32 = token_id.try_into()?;466 let budget = self467 .recorder468 .weight_calls_budget(<StructureWeight<T>>::find_parent());469470 if <TokensMinted<T>>::get(self.id)471 .checked_add(1)472 .ok_or("item id overflow")?473 != token_id474 {475 return Err("item id should be next".into());476 }477478 let users = [(to.clone(), 1)]479 .into_iter()480 .collect::<BTreeMap<_, _>>()481 .try_into()482 .unwrap();483 <Pallet<T>>::create_item(484 self,485 &caller,486 CreateItemData::<T::CrossAccountId> {487 users,488 properties: CollectionPropertiesVec::default(),489 },490 &budget,491 )492 .map_err(dispatch_to_evm::<T>)?;493494 Ok(true)495 }496497 /// @notice Function to mint token with the given tokenUri.498 /// @dev `tokenId` should be obtained with `nextTokenId` method,499 /// unlike standard, you can't specify it manually500 /// @param to The new owner501 /// @param tokenId ID of the minted RFT502 /// @param tokenUri Token URI that would be stored in the RFT properties503 #[solidity(rename_selector = "mintWithTokenURI")]504 #[weight(<SelfWeightOf<T>>::create_item())]505 fn mint_with_token_uri(506 &mut self,507 caller: caller,508 to: address,509 token_id: uint256,510 token_uri: string,511 ) -> Result<bool> {512 let key = key::url();513 let permission = get_token_permission::<T>(self.id, &key)?;514 if !permission.collection_admin {515 return Err("Operation is not allowed".into());516 }517518 let caller = T::CrossAccountId::from_eth(caller);519 let to = T::CrossAccountId::from_eth(to);520 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;521 let budget = self522 .recorder523 .weight_calls_budget(<StructureWeight<T>>::find_parent());524525 if <TokensMinted<T>>::get(self.id)526 .checked_add(1)527 .ok_or("item id overflow")?528 != token_id529 {530 return Err("item id should be next".into());531 }532533 let mut properties = CollectionPropertiesVec::default();534 properties535 .try_push(Property {536 key,537 value: token_uri538 .into_bytes()539 .try_into()540 .map_err(|_| "token uri is too long")?,541 })542 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;543544 let users = [(to.clone(), 1)]545 .into_iter()546 .collect::<BTreeMap<_, _>>()547 .try_into()548 .unwrap();549 <Pallet<T>>::create_item(550 self,551 &caller,552 CreateItemData::<T::CrossAccountId> { users, properties },553 &budget,554 )555 .map_err(dispatch_to_evm::<T>)?;556 Ok(true)557 }558559 /// @dev Not implemented560 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {561 Err("not implementable".into())562 }563}564565fn get_token_property<T: Config>(566 collection: &CollectionHandle<T>,567 token_id: u32,568 key: &up_data_structs::PropertyKey,569) -> Result<string> {570 collection.consume_store_reads(1)?;571 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))572 .map_err(|_| Error::Revert("Token properties not found".into()))?;573 if let Some(property) = properties.get(key) {574 return Ok(string::from_utf8_lossy(property).into());575 }576577 Err("Property tokenURI not found".into())578}579580fn get_token_permission<T: Config>(581 collection_id: CollectionId,582 key: &PropertyKey,583) -> Result<PropertyPermission> {584 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)585 .map_err(|_| Error::Revert("No permissions for collection".into()))?;586 let a = token_property_permissions587 .get(key)588 .map(Clone::clone)589 .ok_or_else(|| {590 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();591 Error::Revert(alloc::format!("No permission for key {}", key))592 })?;593 Ok(a)594}595596/// @title Unique extensions for ERC721.597#[solidity_interface(name = ERC721UniqueExtensions)]598impl<T: Config> RefungibleHandle<T> {599 /// @notice Transfer ownership of an RFT600 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`601 /// is the zero address. Throws if `tokenId` is not a valid RFT.602 /// Throws if RFT pieces have multiple owners.603 /// @param to The new owner604 /// @param tokenId The RFT to transfer605 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]606 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {607 let caller = T::CrossAccountId::from_eth(caller);608 let to = T::CrossAccountId::from_eth(to);609 let token = token_id.try_into()?;610 let budget = self611 .recorder612 .weight_calls_budget(<StructureWeight<T>>::find_parent());613614 let balance = balance(&self, token, &caller)?;615 ensure_single_owner(&self, token, balance)?;616617 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)618 .map_err(dispatch_to_evm::<T>)?;619 Ok(())620 }621622 /// @notice Burns a specific ERC721 token.623 /// @dev Throws unless `msg.sender` is the current owner or an authorized624 /// operator for this RFT. Throws if `from` is not the current owner. Throws625 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.626 /// Throws if RFT pieces have multiple owners.627 /// @param from The current owner of the RFT628 /// @param tokenId The RFT to transfer629 #[weight(<SelfWeightOf<T>>::burn_from())]630 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {631 let caller = T::CrossAccountId::from_eth(caller);632 let from = T::CrossAccountId::from_eth(from);633 let token = token_id.try_into()?;634 let budget = self635 .recorder636 .weight_calls_budget(<StructureWeight<T>>::find_parent());637638 let balance = balance(&self, token, &caller)?;639 ensure_single_owner(&self, token, balance)?;640641 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)642 .map_err(dispatch_to_evm::<T>)?;643 Ok(())644 }645646 /// @notice Returns next free RFT ID.647 fn next_token_id(&self) -> Result<uint256> {648 self.consume_store_reads(1)?;649 Ok(<TokensMinted<T>>::get(self.id)650 .checked_add(1)651 .ok_or("item id overflow")?652 .into())653 }654655 /// @notice Function to mint multiple tokens.656 /// @dev `tokenIds` should be an array of consecutive numbers and first number657 /// should be obtained with `nextTokenId` method658 /// @param to The new owner659 /// @param tokenIds IDs of the minted RFTs660 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]661 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {662 let caller = T::CrossAccountId::from_eth(caller);663 let to = T::CrossAccountId::from_eth(to);664 let mut expected_index = <TokensMinted<T>>::get(self.id)665 .checked_add(1)666 .ok_or("item id overflow")?;667 let budget = self668 .recorder669 .weight_calls_budget(<StructureWeight<T>>::find_parent());670671 let total_tokens = token_ids.len();672 for id in token_ids.into_iter() {673 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;674 if id != expected_index {675 return Err("item id should be next".into());676 }677 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;678 }679 let users = [(to.clone(), 1)]680 .into_iter()681 .collect::<BTreeMap<_, _>>()682 .try_into()683 .unwrap();684 let create_item_data = CreateItemData::<T::CrossAccountId> {685 users,686 properties: CollectionPropertiesVec::default(),687 };688 let data = (0..total_tokens)689 .map(|_| create_item_data.clone())690 .collect();691692 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)693 .map_err(dispatch_to_evm::<T>)?;694 Ok(true)695 }696697 /// @notice Function to mint multiple tokens with the given tokenUris.698 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive699 /// numbers and first number should be obtained with `nextTokenId` method700 /// @param to The new owner701 /// @param tokens array of pairs of token ID and token URI for minted tokens702 #[solidity(rename_selector = "mintBulkWithTokenURI")]703 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]704 fn mint_bulk_with_token_uri(705 &mut self,706 caller: caller,707 to: address,708 tokens: Vec<(uint256, string)>,709 ) -> Result<bool> {710 let key = key::url();711 let caller = T::CrossAccountId::from_eth(caller);712 let to = T::CrossAccountId::from_eth(to);713 let mut expected_index = <TokensMinted<T>>::get(self.id)714 .checked_add(1)715 .ok_or("item id overflow")?;716 let budget = self717 .recorder718 .weight_calls_budget(<StructureWeight<T>>::find_parent());719720 let mut data = Vec::with_capacity(tokens.len());721 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]722 .into_iter()723 .collect::<BTreeMap<_, _>>()724 .try_into()725 .unwrap();726 for (id, token_uri) in tokens {727 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;728 if id != expected_index {729 return Err("item id should be next".into());730 }731 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;732733 let mut properties = CollectionPropertiesVec::default();734 properties735 .try_push(Property {736 key: key.clone(),737 value: token_uri738 .into_bytes()739 .try_into()740 .map_err(|_| "token uri is too long")?,741 })742 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;743744 let create_item_data = CreateItemData::<T::CrossAccountId> {745 users: users.clone(),746 properties,747 };748 data.push(create_item_data);749 }750751 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)752 .map_err(dispatch_to_evm::<T>)?;753 Ok(true)754 }755756 /// Returns EVM address for refungible token757 ///758 /// @param token ID of the token759 fn token_contract_address(&self, token: uint256) -> Result<address> {760 Ok(T::EvmTokenAddressMapping::token_to_address(761 self.id,762 token.try_into().map_err(|_| "token id overflow")?,763 ))764 }765}766767impl<T: Config> RefungibleHandle<T> {768 pub fn supports_metadata(&self) -> bool {769 let has_metadata_support_enabled = if let Some(erc721_metadata) =770 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::erc721_metadata())771 {772 *erc721_metadata.into_inner() == *value::ERC721_METADATA_SUPPORTED773 } else {774 false775 };776777 let has_url_property_permissions = get_token_permission::<T>(self.id, &key::url()).is_ok();778779 has_metadata_support_enabled && has_url_property_permissions780 }781}782783#[solidity_interface(784 name = UniqueRefungible,785 is(786 ERC721,787 ERC721Enumerable,788 ERC721UniqueExtensions,789 ERC721Mintable,790 ERC721Burnable,791 Collection(via(common_mut returns CollectionHandle<T>)),792 TokenProperties,793 ERC721Metadata(if(this.supports_metadata())),794 )795)]796impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}797798// Not a tests, but code generators799generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);800generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);801802impl<T: Config> CommonEvmHandler for RefungibleHandle<T>803where804 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,805{806 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");807 fn call(808 self,809 handle: &mut impl PrecompileHandle,810 ) -> Option<pallet_common::erc::PrecompileResult> {811 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)812 }813}pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -101,10 +101,7 @@
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_evm_coder_substrate::WithRecorder;
use pallet_common::{
- CommonCollectionOperations,
- erc::static_property::{key, value},
- Error as CommonError,
- eth::collection_id_to_address,
+ CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,
Event as CommonEvent, Pallet as PalletCommon,
};
use pallet_structure::Pallet as PalletStructure;
tests/src/eth/base.test.tsdiffbeforeafterboth--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -80,7 +80,23 @@
await usingEthPlaygrounds(async (helper, privateKey) => {
const donor = privateKey('//Alice');
const [alice] = await helper.arrange.createAccounts([10n], donor);
- ({collectionId: collection} = await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test', properties: [{key: 'ERC721Metadata', value: '1'}]}));
+ ({collectionId: collection} = await helper.nft.mintCollection(
+ alice,
+ {
+ name: 'test',
+ description: 'test',
+ tokenPrefix: 'test',
+ properties: [{key: 'ERC721Metadata', value: '1'}],
+ tokenPropertyPermissions: [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }],
+ },
+ ));
minter = helper.eth.createAccount();
});
});
tests/src/eth/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/eth/collectionProperties.test.ts
+++ b/tests/src/eth/collectionProperties.test.ts
@@ -67,7 +67,15 @@
itEth('ERC721Metadata property can be set for NFT collection', async({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.nft.mintCollection(donor, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const tokenPropertyPermissions = [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }];
+ const collection = await helper.nft.mintCollection(donor, {name: 'col', description: 'descr', tokenPrefix: 'COL', tokenPropertyPermissions});
await collection.addAdmin(donor, {Ethereum: caller});
const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
@@ -83,7 +91,15 @@
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'});
+ const tokenPropertyPermissions = [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }];
+ const collection = await helper.rft.mintCollection(donor, {name: 'col', description: 'descr', tokenPrefix: 'COL', tokenPropertyPermissions});
await collection.addAdmin(donor, {Ethereum: caller});
tests/src/eth/nonFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -501,7 +501,23 @@
itEth('Returns collection name', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.nft.mintCollection(alice, {name: 'oh River', tokenPrefix: 'CHANGE', properties: [{key: 'ERC721Metadata', value: '1'}]});
+ const tokenPropertyPermissions = [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }];
+ const collection = await helper.nft.mintCollection(
+ alice,
+ {
+ name: 'oh River',
+ tokenPrefix: 'CHANGE',
+ properties: [{key: 'ERC721Metadata', value: '1'}],
+ tokenPropertyPermissions,
+ },
+ );
const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
const name = await contract.methods.name().call();
@@ -510,7 +526,23 @@
itEth('Returns symbol name', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const collection = await helper.nft.mintCollection(alice, {name: 'oh River', tokenPrefix: 'CHANGE', properties: [{key: 'ERC721Metadata', value: '1'}]});
+ const tokenPropertyPermissions = [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }];
+ const collection = await helper.nft.mintCollection(
+ alice,
+ {
+ name: 'oh River',
+ tokenPrefix: 'CHANGE',
+ properties: [{key: 'ERC721Metadata', value: '1'}],
+ tokenPropertyPermissions,
+ },
+ );
const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
const symbol = await contract.methods.symbol().call();
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -377,7 +377,23 @@
itEth('Returns collection name', async ({helper}) => {
const caller = helper.eth.createAccount();
- const collection = await helper.rft.mintCollection(alice, {name: 'Leviathan', tokenPrefix: '11', properties: [{key: 'ERC721Metadata', value: '1'}]});
+ const tokenPropertyPermissions = [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }];
+ const collection = await helper.rft.mintCollection(
+ alice,
+ {
+ name: 'Leviathan',
+ tokenPrefix: '11',
+ properties: [{key: 'ERC721Metadata', value: '1'}],
+ tokenPropertyPermissions,
+ },
+ );
const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'rft', caller);
const name = await contract.methods.name().call();
@@ -386,7 +402,24 @@
itEth('Returns symbol name', async ({helper}) => {
const caller = await helper.eth.createAccountWithBalance(donor);
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'Leviathan', tokenPrefix: '12', properties: [{key: 'ERC721Metadata', value: '1'}]});
+ const tokenPropertyPermissions = [{
+ key: 'URI',
+ permission: {
+ mutable: true,
+ collectionAdmin: true,
+ tokenOwner: false,
+ },
+ }];
+ const {collectionId} = await helper.rft.mintCollection(
+ alice,
+ {
+ name: 'Leviathan',
+ tokenPrefix: '12',
+ properties: [{key: 'ERC721Metadata', value: '1'}],
+ tokenPropertyPermissions,
+ },
+ );
+
const contract = helper.ethNativeContract.collectionById(collectionId, 'rft', caller);
const symbol = await contract.methods.symbol().call();
expect(symbol).to.equal('12');
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -213,7 +213,7 @@
async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {
const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();
const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
-
+
const result = await collectionHelper.methods.createERC721MetadataCompatibleRFTCollection(name, description, tokenPrefix, baseUri).send({value: Number(collectionCreationPrice)});
const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);