difftreelog
fix PR
in: master
9 files changed
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -55,10 +55,8 @@
pub enum ERC721TokenEvent {
/// The token has been changed.
TokenChanged {
- /// Collection ID.
+ /// Token ID.
#[indexed]
- collection_id: Address,
- /// Token ID.
token_id: U256,
},
}
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -19,7 +19,7 @@
/// @dev inlined interface
contract ERC721TokenEvent {
- event TokenChanged(address indexed collectionId, uint256 tokenId);
+ event TokenChanged(uint256 indexed tokenId);
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
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::{abi::AbiType, ToLog, generate_stubgen, solidity_interface, types::*};29use frame_support::{BoundedBTreeMap, BoundedVec};30use pallet_common::{31 CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,32 Error as CommonError,33 erc::{CommonEvmHandler, CollectionCall, static_property::key},34 eth::{self, TokenUri},35};36use pallet_evm::{account::CrossAccountId, PrecompileHandle};37use pallet_evm_coder_substrate::{38 call, dispatch_to_evm,39 execution::{PreDispatch, Result, Error},40 frontier_contract,41};42use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};43use sp_core::{H160, U256, Get};44use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};45use up_data_structs::{46 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,47 PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,48};4950use crate::{51 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, TokenProperties,52 TokensMinted, TotalSupply, SelfWeightOf, weights::WeightInfo,53};5455frontier_contract! {56 macro_rules! RefungibleHandle_result {...}57 impl<T: Config> Contract for RefungibleHandle<T> {...}58}5960pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);6162/// Rft events.63#[derive(ToLog)]64pub enum ERC721TokenEvent {65 /// The token has been changed.66 TokenChanged {67 /// Collection ID.68 #[indexed]69 collection_id: Address,70 /// Token ID.71 token_id: U256,72 },73}7475/// @title A contract that allows to set and delete token properties and change token property permissions.76#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]77impl<T: Config> RefungibleHandle<T> {78 /// @notice Set permissions for token property.79 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.80 /// @param key Property key.81 /// @param isMutable Permission to mutate property.82 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.83 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.84 #[solidity(hide)]85 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]86 fn set_token_property_permission(87 &mut self,88 caller: Caller,89 key: String,90 is_mutable: bool,91 collection_admin: bool,92 token_owner: bool,93 ) -> Result<()> {94 let caller = T::CrossAccountId::from_eth(caller);95 <Pallet<T>>::set_token_property_permissions(96 self,97 &caller,98 vec![PropertyKeyPermission {99 key: <Vec<u8>>::from(key)100 .try_into()101 .map_err(|_| "too long key")?,102 permission: PropertyPermission {103 mutable: is_mutable,104 collection_admin,105 token_owner,106 },107 }],108 )109 .map_err(dispatch_to_evm::<T>)110 }111112 /// @notice Set permissions for token property.113 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.114 /// @param permissions Permissions for keys.115 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]116 fn set_token_property_permissions(117 &mut self,118 caller: Caller,119 permissions: Vec<eth::TokenPropertyPermission>,120 ) -> Result<()> {121 let caller = T::CrossAccountId::from_eth(caller);122 let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;123124 <Pallet<T>>::set_token_property_permissions(self, &caller, perms)125 .map_err(dispatch_to_evm::<T>)126 }127128 /// @notice Get permissions for token properties.129 fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {130 let perms = <Pallet<T>>::token_property_permission(self.id);131 Ok(perms132 .into_iter()133 .map(eth::TokenPropertyPermission::from)134 .collect())135 }136137 /// @notice Set token property value.138 /// @dev Throws error if `msg.sender` has no permission to edit the property.139 /// @param tokenId ID of the token.140 /// @param key Property key.141 /// @param value Property value.142 #[solidity(hide)]143 #[weight(<SelfWeightOf<T>>::set_token_properties(1))]144 fn set_property(145 &mut self,146 caller: Caller,147 token_id: U256,148 key: String,149 value: Bytes,150 ) -> Result<()> {151 let caller = T::CrossAccountId::from_eth(caller);152 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;153 let key = <Vec<u8>>::from(key)154 .try_into()155 .map_err(|_| "key too long")?;156 let value = value.0.try_into().map_err(|_| "value too long")?;157158 let nesting_budget = self159 .recorder160 .weight_calls_budget(<StructureWeight<T>>::find_parent());161162 <Pallet<T>>::set_token_property(163 self,164 &caller,165 TokenId(token_id),166 Property { key, value },167 &nesting_budget,168 )169 .map_err(dispatch_to_evm::<T>)170 }171172 /// @notice Set token properties value.173 /// @dev Throws error if `msg.sender` has no permission to edit the property.174 /// @param tokenId ID of the token.175 /// @param properties settable properties176 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]177 fn set_properties(178 &mut self,179 caller: Caller,180 token_id: U256,181 properties: Vec<eth::Property>,182 ) -> Result<()> {183 let caller = T::CrossAccountId::from_eth(caller);184 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;185186 let nesting_budget = self187 .recorder188 .weight_calls_budget(<StructureWeight<T>>::find_parent());189190 let properties = properties191 .into_iter()192 .map(eth::Property::try_into)193 .collect::<Result<Vec<_>>>()?;194195 <Pallet<T>>::set_token_properties(196 self,197 &caller,198 TokenId(token_id),199 properties.into_iter(),200 false,201 &nesting_budget,202 )203 .map_err(dispatch_to_evm::<T>)204 }205206 /// @notice Delete token property value.207 /// @dev Throws error if `msg.sender` has no permission to edit the property.208 /// @param tokenId ID of the token.209 /// @param key Property key.210 #[solidity(hide)]211 #[weight(<SelfWeightOf<T>>::delete_token_properties(1))]212 fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {213 let caller = T::CrossAccountId::from_eth(caller);214 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;215 let key = <Vec<u8>>::from(key)216 .try_into()217 .map_err(|_| "key too long")?;218219 let nesting_budget = self220 .recorder221 .weight_calls_budget(<StructureWeight<T>>::find_parent());222223 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)224 .map_err(dispatch_to_evm::<T>)225 }226227 /// @notice Delete token properties value.228 /// @dev Throws error if `msg.sender` has no permission to edit the property.229 /// @param tokenId ID of the token.230 /// @param keys Properties key.231 #[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]232 fn delete_properties(233 &mut self,234 token_id: U256,235 caller: Caller,236 keys: Vec<String>,237 ) -> Result<()> {238 let caller = T::CrossAccountId::from_eth(caller);239 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;240 let keys = keys241 .into_iter()242 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))243 .collect::<Result<Vec<_>>>()?;244245 let nesting_budget = self246 .recorder247 .weight_calls_budget(<StructureWeight<T>>::find_parent());248249 <Pallet<T>>::delete_token_properties(250 self,251 &caller,252 TokenId(token_id),253 keys.into_iter(),254 &nesting_budget,255 )256 .map_err(dispatch_to_evm::<T>)257 }258259 /// @notice Get token property value.260 /// @dev Throws error if key not found261 /// @param tokenId ID of the token.262 /// @param key Property key.263 /// @return Property value bytes264 fn property(&self, token_id: U256, key: String) -> Result<Bytes> {265 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;266 let key = <Vec<u8>>::from(key)267 .try_into()268 .map_err(|_| "key too long")?;269270 let props = <TokenProperties<T>>::get((self.id, token_id));271 let prop = props.get(&key).ok_or("key not found")?;272273 Ok(prop.to_vec().into())274 }275}276277#[derive(ToLog)]278pub enum ERC721Events {279 /// @dev This event emits when NFTs are created (`from` == 0) and destroyed280 /// (`to` == 0). Exception: during contract creation, any number of RFTs281 /// may be created and assigned without emitting Transfer.282 Transfer {283 #[indexed]284 from: Address,285 #[indexed]286 to: Address,287 #[indexed]288 token_id: U256,289 },290 /// @dev Not supported291 Approval {292 #[indexed]293 owner: Address,294 #[indexed]295 approved: Address,296 #[indexed]297 token_id: U256,298 },299 /// @dev Not supported300 #[allow(dead_code)]301 ApprovalForAll {302 #[indexed]303 owner: Address,304 #[indexed]305 operator: Address,306 approved: bool,307 },308}309310/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension311/// @dev See https://eips.ethereum.org/EIPS/eip-721312#[solidity_interface(name = ERC721Metadata, enum(derive(PreDispatch)), expect_selector = 0x5b5e139f)]313impl<T: Config> RefungibleHandle<T>314where315 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,316{317 /// @notice A descriptive name for a collection of NFTs in this contract318 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`319 #[solidity(hide, rename_selector = "name")]320 fn name_proxy(&self) -> Result<String> {321 self.name()322 }323324 /// @notice An abbreviated name for NFTs in this contract325 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`326 #[solidity(hide, rename_selector = "symbol")]327 fn symbol_proxy(&self) -> Result<String> {328 self.symbol()329 }330331 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.332 ///333 /// @dev If the token has a `url` property and it is not empty, it is returned.334 /// 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`.335 /// If the collection property `baseURI` is empty or absent, return "" (empty string)336 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix337 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).338 ///339 /// @return token's const_metadata340 #[solidity(rename_selector = "tokenURI")]341 fn token_uri(&self, token_id: U256) -> Result<String> {342 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;343344 match get_token_property(self, token_id_u32, &key::url()).as_deref() {345 Err(_) | Ok("") => (),346 Ok(url) => {347 return Ok(url.into());348 }349 };350351 let base_uri =352 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())353 .map(BoundedVec::into_inner)354 .map(String::from_utf8)355 .transpose()356 .map_err(|e| {357 Error::Revert(alloc::format!(358 "Can not convert value \"baseURI\" to string with error \"{}\"",359 e360 ))361 })?;362363 let base_uri = match base_uri.as_deref() {364 None | Some("") => {365 return Ok("".into());366 }367 Some(base_uri) => base_uri.into(),368 };369370 Ok(371 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {372 Err(_) | Ok("") => base_uri,373 Ok(suffix) => base_uri + suffix,374 },375 )376 }377}378379/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension380/// @dev See https://eips.ethereum.org/EIPS/eip-721381#[solidity_interface(name = ERC721Enumerable, enum(derive(PreDispatch)), expect_selector = 0x780e9d63)]382impl<T: Config> RefungibleHandle<T> {383 /// @notice Enumerate valid RFTs384 /// @param index A counter less than `totalSupply()`385 /// @return The token identifier for the `index`th NFT,386 /// (sort order not specified)387 fn token_by_index(&self, index: U256) -> U256 {388 index389 }390391 /// Not implemented392 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {393 // TODO: Not implemetable394 Err("not implemented".into())395 }396397 /// @notice Count RFTs tracked by this contract398 /// @return A count of valid RFTs tracked by this contract, where each one of399 /// them has an assigned and queryable owner not equal to the zero address400 fn total_supply(&self) -> Result<U256> {401 self.consume_store_reads(1)?;402 Ok(<Pallet<T>>::total_supply(self).into())403 }404}405406/// @title ERC-721 Non-Fungible Token Standard407/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md408#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]409impl<T: Config> RefungibleHandle<T> {410 /// @notice Count all RFTs assigned to an owner411 /// @dev RFTs assigned to the zero address are considered invalid, and this412 /// function throws for queries about the zero address.413 /// @param owner An address for whom to query the balance414 /// @return The number of RFTs owned by `owner`, possibly zero415 fn balance_of(&self, owner: Address) -> Result<U256> {416 self.consume_store_reads(1)?;417 let owner = T::CrossAccountId::from_eth(owner);418 let balance = <AccountBalance<T>>::get((self.id, owner));419 Ok(balance.into())420 }421422 /// @notice Find the owner of an RFT423 /// @dev RFTs assigned to zero address are considered invalid, and queries424 /// about them do throw.425 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for426 /// the tokens that are partially owned.427 /// @param tokenId The identifier for an RFT428 /// @return The address of the owner of the RFT429 fn owner_of(&self, token_id: U256) -> Result<Address> {430 self.consume_store_reads(2)?;431 let token = token_id.try_into()?;432 let owner = <Pallet<T>>::token_owner(self.id, token);433 owner434 .map(|address| *address.as_eth())435 .or_else(|err| match err {436 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),437 TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),438 })439 }440441 /// @dev Not implemented442 #[solidity(rename_selector = "safeTransferFrom")]443 fn safe_transfer_from_with_data(444 &mut self,445 _from: Address,446 _to: Address,447 _token_id: U256,448 _data: Bytes,449 ) -> Result<()> {450 // TODO: Not implemetable451 Err("not implemented".into())452 }453454 /// @dev Not implemented455 #[solidity(rename_selector = "safeTransferFrom")]456 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {457 // TODO: Not implemetable458 Err("not implemented".into())459 }460461 /// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE462 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE463 /// THEY MAY BE PERMANENTLY LOST464 /// @dev Throws unless `msg.sender` is the current owner or an authorized465 /// operator for this RFT. Throws if `from` is not the current owner. Throws466 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.467 /// Throws if RFT pieces have multiple owners.468 /// @param from The current owner of the NFT469 /// @param to The new owner470 /// @param tokenId The NFT to transfer471 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]472 fn transfer_from(473 &mut self,474 caller: Caller,475 from: Address,476 to: Address,477 token_id: U256,478 ) -> Result<()> {479 let caller = T::CrossAccountId::from_eth(caller);480 let from = T::CrossAccountId::from_eth(from);481 let to = T::CrossAccountId::from_eth(to);482 let token = token_id.try_into()?;483 let budget = self484 .recorder485 .weight_calls_budget(<StructureWeight<T>>::find_parent());486487 let balance = balance(&self, token, &from)?;488 ensure_single_owner(&self, token, balance)?;489490 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)491 .map_err(dispatch_to_evm::<T>)?;492493 Ok(())494 }495496 /// @dev Not implemented497 fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {498 Err("not implemented".into())499 }500501 /// @notice Sets or unsets the approval of a given operator.502 /// The `operator` is allowed to transfer all token pieces of the `caller` on their behalf.503 /// @param operator Operator504 /// @param approved Should operator status be granted or revoked?505 #[weight(<SelfWeightOf<T>>::set_allowance_for_all())]506 fn set_approval_for_all(507 &mut self,508 caller: Caller,509 operator: Address,510 approved: bool,511 ) -> Result<()> {512 let caller = T::CrossAccountId::from_eth(caller);513 let operator = T::CrossAccountId::from_eth(operator);514515 <Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)516 .map_err(dispatch_to_evm::<T>)?;517 Ok(())518 }519520 /// @dev Not implemented521 fn get_approved(&self, _token_id: U256) -> Result<Address> {522 // TODO: Not implemetable523 Err("not implemented".into())524 }525526 /// @notice Tells whether the given `owner` approves the `operator`.527 #[weight(<SelfWeightOf<T>>::allowance_for_all())]528 fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {529 let owner = T::CrossAccountId::from_eth(owner);530 let operator = T::CrossAccountId::from_eth(operator);531532 Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))533 }534}535536/// Returns amount of pieces of `token` that `owner` have537pub fn balance<T: Config>(538 collection: &RefungibleHandle<T>,539 token: TokenId,540 owner: &T::CrossAccountId,541) -> Result<u128> {542 collection.consume_store_reads(1)?;543 let balance = <Balance<T>>::get((collection.id, token, &owner));544 Ok(balance)545}546547/// Throws if `owner_balance` is lower than total amount of `token` pieces548pub fn ensure_single_owner<T: Config>(549 collection: &RefungibleHandle<T>,550 token: TokenId,551 owner_balance: u128,552) -> Result<()> {553 collection.consume_store_reads(1)?;554 let total_supply = <TotalSupply<T>>::get((collection.id, token));555556 if owner_balance == 0 {557 return Err(dispatch_to_evm::<T>(558 <CommonError<T>>::MustBeTokenOwner.into(),559 ));560 }561562 if total_supply != owner_balance {563 return Err("token has multiple owners".into());564 }565 Ok(())566}567568/// @title ERC721 Token that can be irreversibly burned (destroyed).569#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]570impl<T: Config> RefungibleHandle<T> {571 /// @notice Burns a specific ERC721 token.572 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized573 /// operator of the current owner.574 /// @param tokenId The RFT to approve575 #[weight(<SelfWeightOf<T>>::burn_item_fully())]576 fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {577 let caller = T::CrossAccountId::from_eth(caller);578 let token = token_id.try_into()?;579580 let balance = balance(&self, token, &caller)?;581 ensure_single_owner(&self, token, balance)?;582583 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;584 Ok(())585 }586}587588/// @title ERC721 minting logic.589#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]590impl<T: Config> RefungibleHandle<T> {591 /// @notice Function to mint a token.592 /// @param to The new owner593 /// @return uint256 The id of the newly minted token594 #[weight(<SelfWeightOf<T>>::create_item())]595 fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {596 let token_id: U256 = <TokensMinted<T>>::get(self.id)597 .checked_add(1)598 .ok_or("item id overflow")?599 .into();600 self.mint_check_id(caller, to, token_id)?;601 Ok(token_id)602 }603604 /// @notice Function to mint a token.605 /// @dev `tokenId` should be obtained with `nextTokenId` method,606 /// unlike standard, you can't specify it manually607 /// @param to The new owner608 /// @param tokenId ID of the minted RFT609 #[solidity(hide, rename_selector = "mint")]610 #[weight(<SelfWeightOf<T>>::create_item())]611 fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {612 let caller = T::CrossAccountId::from_eth(caller);613 let to = T::CrossAccountId::from_eth(to);614 let token_id: u32 = token_id.try_into()?;615 let budget = self616 .recorder617 .weight_calls_budget(<StructureWeight<T>>::find_parent());618619 if <TokensMinted<T>>::get(self.id)620 .checked_add(1)621 .ok_or("item id overflow")?622 != token_id623 {624 return Err("item id should be next".into());625 }626627 let users = [(to.clone(), 1)]628 .into_iter()629 .collect::<BTreeMap<_, _>>()630 .try_into()631 .unwrap();632 <Pallet<T>>::create_item(633 self,634 &caller,635 CreateItemData::<T> {636 users,637 properties: CollectionPropertiesVec::default(),638 },639 &budget,640 )641 .map_err(dispatch_to_evm::<T>)?;642643 Ok(true)644 }645646 /// @notice Function to mint token with the given tokenUri.647 /// @param to The new owner648 /// @param tokenUri Token URI that would be stored in the NFT properties649 /// @return uint256 The id of the newly minted token650 #[solidity(rename_selector = "mintWithTokenURI")]651 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]652 fn mint_with_token_uri(653 &mut self,654 caller: Caller,655 to: Address,656 token_uri: String,657 ) -> Result<U256> {658 let token_id: U256 = <TokensMinted<T>>::get(self.id)659 .checked_add(1)660 .ok_or("item id overflow")?661 .into();662 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;663 Ok(token_id)664 }665666 /// @notice Function to mint token with the given tokenUri.667 /// @dev `tokenId` should be obtained with `nextTokenId` method,668 /// unlike standard, you can't specify it manually669 /// @param to The new owner670 /// @param tokenId ID of the minted RFT671 /// @param tokenUri Token URI that would be stored in the RFT properties672 #[solidity(hide, rename_selector = "mintWithTokenURI")]673 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]674 fn mint_with_token_uri_check_id(675 &mut self,676 caller: Caller,677 to: Address,678 token_id: U256,679 token_uri: String,680 ) -> Result<bool> {681 let key = key::url();682 let permission = get_token_permission::<T>(self.id, &key)?;683 if !permission.collection_admin {684 return Err("Operation is not allowed".into());685 }686687 let caller = T::CrossAccountId::from_eth(caller);688 let to = T::CrossAccountId::from_eth(to);689 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;690 let budget = self691 .recorder692 .weight_calls_budget(<StructureWeight<T>>::find_parent());693694 if <TokensMinted<T>>::get(self.id)695 .checked_add(1)696 .ok_or("item id overflow")?697 != token_id698 {699 return Err("item id should be next".into());700 }701702 let mut properties = CollectionPropertiesVec::default();703 properties704 .try_push(Property {705 key,706 value: token_uri707 .into_bytes()708 .try_into()709 .map_err(|_| "token uri is too long")?,710 })711 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;712713 let users = [(to.clone(), 1)]714 .into_iter()715 .collect::<BTreeMap<_, _>>()716 .try_into()717 .unwrap();718 <Pallet<T>>::create_item(719 self,720 &caller,721 CreateItemData::<T> { users, properties },722 &budget,723 )724 .map_err(dispatch_to_evm::<T>)?;725 Ok(true)726 }727}728729fn get_token_property<T: Config>(730 collection: &CollectionHandle<T>,731 token_id: u32,732 key: &up_data_structs::PropertyKey,733) -> Result<String> {734 collection.consume_store_reads(1)?;735 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))736 .map_err(|_| Error::Revert("Token properties not found".into()))?;737 if let Some(property) = properties.get(key) {738 return Ok(String::from_utf8_lossy(property).into());739 }740741 Err("Property tokenURI not found".into())742}743744fn get_token_permission<T: Config>(745 collection_id: CollectionId,746 key: &PropertyKey,747) -> Result<PropertyPermission> {748 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)749 .map_err(|_| Error::Revert("No permissions for collection".into()))?;750 let a = token_property_permissions751 .get(key)752 .map(Clone::clone)753 .ok_or_else(|| {754 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();755 Error::Revert(alloc::format!("No permission for key {}", key))756 })?;757 Ok(a)758}759760/// @title Unique extensions for ERC721.761#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]762impl<T: Config> RefungibleHandle<T>763where764 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,765{766 /// @notice A descriptive name for a collection of NFTs in this contract767 fn name(&self) -> Result<String> {768 Ok(decode_utf16(self.name.iter().copied())769 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))770 .collect::<String>())771 }772773 /// @notice An abbreviated name for NFTs in this contract774 fn symbol(&self) -> Result<String> {775 Ok(String::from_utf8_lossy(&self.token_prefix).into())776 }777778 /// @notice A description for the collection.779 fn description(&self) -> Result<String> {780 Ok(decode_utf16(self.description.iter().copied())781 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))782 .collect::<String>())783 }784785 /// Returns the owner (in cross format) of the token.786 ///787 /// @param tokenId Id for the token.788 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {789 Self::token_owner(&self, token_id.try_into()?)790 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))791 .or_else(|err| match err {792 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),793 TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(794 ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,795 )),796 })797 }798799 /// Returns the token properties.800 ///801 /// @param tokenId Id for the token.802 /// @param keys Properties keys. Empty keys for all propertyes.803 /// @return Vector of properties key/value pairs.804 fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {805 let keys = keys806 .into_iter()807 .map(|key| {808 <Vec<u8>>::from(key)809 .try_into()810 .map_err(|_| Error::Revert("key too large".into()))811 })812 .collect::<Result<Vec<_>>>()?;813814 <Self as CommonCollectionOperations<T>>::token_properties(815 &self,816 token_id.try_into()?,817 if keys.is_empty() { None } else { Some(keys) },818 )819 .into_iter()820 .map(eth::Property::try_from)821 .collect::<Result<Vec<_>>>()822 }823 /// @notice Transfer ownership of an RFT824 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`825 /// is the zero address. Throws if `tokenId` is not a valid RFT.826 /// Throws if RFT pieces have multiple owners.827 /// @param to The new owner828 /// @param tokenId The RFT to transfer829 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]830 fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {831 let caller = T::CrossAccountId::from_eth(caller);832 let to = T::CrossAccountId::from_eth(to);833 let token = token_id.try_into()?;834 let budget = self835 .recorder836 .weight_calls_budget(<StructureWeight<T>>::find_parent());837838 let balance = balance(self, token, &caller)?;839 ensure_single_owner(self, token, balance)?;840841 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)842 .map_err(dispatch_to_evm::<T>)?;843 Ok(())844 }845846 /// @notice Transfer ownership of an RFT847 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`848 /// is the zero address. Throws if `tokenId` is not a valid RFT.849 /// Throws if RFT pieces have multiple owners.850 /// @param to The new owner851 /// @param tokenId The RFT to transfer852 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]853 fn transfer_cross(854 &mut self,855 caller: Caller,856 to: eth::CrossAddress,857 token_id: U256,858 ) -> Result<()> {859 let caller = T::CrossAccountId::from_eth(caller);860 let to = to.into_sub_cross_account::<T>()?;861 let token = token_id.try_into()?;862 let budget = self863 .recorder864 .weight_calls_budget(<StructureWeight<T>>::find_parent());865866 let balance = balance(self, token, &caller)?;867 ensure_single_owner(self, token, balance)?;868869 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)870 .map_err(dispatch_to_evm::<T>)?;871 Ok(())872 }873874 /// @notice Transfer ownership of an RFT875 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`876 /// is the zero address. Throws if `tokenId` is not a valid RFT.877 /// Throws if RFT pieces have multiple owners.878 /// @param to The new owner879 /// @param tokenId The RFT to transfer880 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]881 fn transfer_from_cross(882 &mut self,883 caller: Caller,884 from: eth::CrossAddress,885 to: eth::CrossAddress,886 token_id: U256,887 ) -> Result<()> {888 let caller = T::CrossAccountId::from_eth(caller);889 let from = from.into_sub_cross_account::<T>()?;890 let to = to.into_sub_cross_account::<T>()?;891 let token_id = token_id.try_into()?;892 let budget = self893 .recorder894 .weight_calls_budget(<StructureWeight<T>>::find_parent());895896 let balance = balance(self, token_id, &from)?;897 ensure_single_owner(self, token_id, balance)?;898899 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)900 .map_err(dispatch_to_evm::<T>)?;901 Ok(())902 }903904 /// @notice Burns a specific ERC721 token.905 /// @dev Throws unless `msg.sender` is the current owner or an authorized906 /// operator for this RFT. Throws if `from` is not the current owner. Throws907 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.908 /// Throws if RFT pieces have multiple owners.909 /// @param from The current owner of the RFT910 /// @param tokenId The RFT to transfer911 #[solidity(hide)]912 #[weight(<SelfWeightOf<T>>::burn_from())]913 fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {914 let caller = T::CrossAccountId::from_eth(caller);915 let from = T::CrossAccountId::from_eth(from);916 let token = token_id.try_into()?;917 let budget = self918 .recorder919 .weight_calls_budget(<StructureWeight<T>>::find_parent());920921 let balance = balance(self, token, &from)?;922 ensure_single_owner(self, token, balance)?;923924 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)925 .map_err(dispatch_to_evm::<T>)?;926 Ok(())927 }928929 /// @notice Burns a specific ERC721 token.930 /// @dev Throws unless `msg.sender` is the current owner or an authorized931 /// operator for this RFT. Throws if `from` is not the current owner. Throws932 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.933 /// Throws if RFT pieces have multiple owners.934 /// @param from The current owner of the RFT935 /// @param tokenId The RFT to transfer936 #[weight(<SelfWeightOf<T>>::burn_from())]937 fn burn_from_cross(938 &mut self,939 caller: Caller,940 from: eth::CrossAddress,941 token_id: U256,942 ) -> Result<()> {943 let caller = T::CrossAccountId::from_eth(caller);944 let from = from.into_sub_cross_account::<T>()?;945 let token = token_id.try_into()?;946 let budget = self947 .recorder948 .weight_calls_budget(<StructureWeight<T>>::find_parent());949950 let balance = balance(self, token, &from)?;951 ensure_single_owner(self, token, balance)?;952953 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)954 .map_err(dispatch_to_evm::<T>)?;955 Ok(())956 }957958 /// @notice Returns next free RFT ID.959 fn next_token_id(&self) -> Result<U256> {960 self.consume_store_reads(1)?;961 Ok(<TokensMinted<T>>::get(self.id)962 .checked_add(1)963 .ok_or("item id overflow")?964 .into())965 }966967 /// @notice Function to mint multiple tokens.968 /// @dev `tokenIds` should be an array of consecutive numbers and first number969 /// should be obtained with `nextTokenId` method970 /// @param to The new owner971 /// @param tokenIds IDs of the minted RFTs972 #[solidity(hide)]973 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]974 fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {975 let caller = T::CrossAccountId::from_eth(caller);976 let to = T::CrossAccountId::from_eth(to);977 let mut expected_index = <TokensMinted<T>>::get(self.id)978 .checked_add(1)979 .ok_or("item id overflow")?;980 let budget = self981 .recorder982 .weight_calls_budget(<StructureWeight<T>>::find_parent());983984 let total_tokens = token_ids.len();985 for id in token_ids.into_iter() {986 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;987 if id != expected_index {988 return Err("item id should be next".into());989 }990 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;991 }992 let users = [(to.clone(), 1)]993 .into_iter()994 .collect::<BTreeMap<_, _>>()995 .try_into()996 .unwrap();997 let create_item_data = CreateItemData::<T> {998 users,999 properties: CollectionPropertiesVec::default(),1000 };1001 let data = (0..total_tokens)1002 .map(|_| create_item_data.clone())1003 .collect();10041005 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1006 .map_err(dispatch_to_evm::<T>)?;1007 Ok(true)1008 }10091010 /// @notice Function to mint multiple tokens with the given tokenUris.1011 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive1012 /// numbers and first number should be obtained with `nextTokenId` method1013 /// @param to The new owner1014 /// @param tokens array of pairs of token ID and token URI for minted tokens1015 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1016 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]1017 fn mint_bulk_with_token_uri(1018 &mut self,1019 caller: Caller,1020 to: Address,1021 tokens: Vec<TokenUri>,1022 ) -> Result<bool> {1023 let key = key::url();1024 let caller = T::CrossAccountId::from_eth(caller);1025 let to = T::CrossAccountId::from_eth(to);1026 let mut expected_index = <TokensMinted<T>>::get(self.id)1027 .checked_add(1)1028 .ok_or("item id overflow")?;1029 let budget = self1030 .recorder1031 .weight_calls_budget(<StructureWeight<T>>::find_parent());10321033 let mut data = Vec::with_capacity(tokens.len());1034 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]1035 .into_iter()1036 .collect::<BTreeMap<_, _>>()1037 .try_into()1038 .unwrap();1039 for TokenUri { id, uri } in tokens {1040 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1041 if id != expected_index {1042 return Err("item id should be next".into());1043 }1044 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10451046 let mut properties = CollectionPropertiesVec::default();1047 properties1048 .try_push(Property {1049 key: key.clone(),1050 value: uri1051 .into_bytes()1052 .try_into()1053 .map_err(|_| "token uri is too long")?,1054 })1055 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;10561057 let create_item_data = CreateItemData::<T> {1058 users: users.clone(),1059 properties,1060 };1061 data.push(create_item_data);1062 }10631064 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1065 .map_err(dispatch_to_evm::<T>)?;1066 Ok(true)1067 }10681069 /// @notice Function to mint a token.1070 /// @param to The new owner crossAccountId1071 /// @param properties Properties of minted token1072 /// @return uint256 The id of the newly minted token1073 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1074 fn mint_cross(1075 &mut self,1076 caller: Caller,1077 to: eth::CrossAddress,1078 properties: Vec<eth::Property>,1079 ) -> Result<U256> {1080 let token_id = <TokensMinted<T>>::get(self.id)1081 .checked_add(1)1082 .ok_or("item id overflow")?;10831084 let to = to.into_sub_cross_account::<T>()?;10851086 let properties = properties1087 .into_iter()1088 .map(eth::Property::try_into)1089 .collect::<Result<Vec<_>>>()?1090 .try_into()1091 .map_err(|_| Error::Revert(alloc::format!("too many properties")))?;10921093 let caller = T::CrossAccountId::from_eth(caller);10941095 let budget = self1096 .recorder1097 .weight_calls_budget(<StructureWeight<T>>::find_parent());10981099 let users = [(to, 1)]1100 .into_iter()1101 .collect::<BTreeMap<_, _>>()1102 .try_into()1103 .unwrap();1104 <Pallet<T>>::create_item(1105 self,1106 &caller,1107 CreateItemData::<T> { users, properties },1108 &budget,1109 )1110 .map_err(dispatch_to_evm::<T>)?;11111112 Ok(token_id.into())1113 }11141115 /// Returns EVM address for refungible token1116 ///1117 /// @param token ID of the token1118 fn token_contract_address(&self, token: U256) -> Result<Address> {1119 Ok(T::EvmTokenAddressMapping::token_to_address(1120 self.id,1121 token.try_into().map_err(|_| "token id overflow")?,1122 ))1123 }11241125 /// @notice Returns collection helper contract address1126 fn collection_helper_address(&self) -> Result<Address> {1127 Ok(T::ContractAddress::get())1128 }1129}11301131#[solidity_interface(1132 name = UniqueRefungible,1133 is(1134 ERC721,1135 ERC721Enumerable,1136 ERC721UniqueExtensions,1137 ERC721UniqueMintable,1138 ERC721Burnable,1139 ERC721Metadata(if(this.flags.erc721metadata)),1140 Collection(via(common_mut returns CollectionHandle<T>)),1141 TokenProperties,1142 ),1143 enum(derive(PreDispatch)),1144)]1145impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}11461147// Not a tests, but code generators1148generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1149generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);11501151impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1152where1153 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1154{1155 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1156 fn call(1157 self,1158 handle: &mut impl PrecompileHandle,1159 ) -> Option<pallet_common::erc::PrecompileResult> {1160 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1161 }1162}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::{abi::AbiType, ToLog, generate_stubgen, solidity_interface, types::*};29use frame_support::{BoundedBTreeMap, BoundedVec};30use pallet_common::{31 CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,32 Error as CommonError,33 erc::{CommonEvmHandler, CollectionCall, static_property::key},34 eth::{self, TokenUri},35};36use pallet_evm::{account::CrossAccountId, PrecompileHandle};37use pallet_evm_coder_substrate::{38 call, dispatch_to_evm,39 execution::{PreDispatch, Result, Error},40 frontier_contract,41};42use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};43use sp_core::{H160, U256, Get};44use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};45use up_data_structs::{46 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,47 PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,48};4950use crate::{51 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, TokenProperties,52 TokensMinted, TotalSupply, SelfWeightOf, weights::WeightInfo,53};5455frontier_contract! {56 macro_rules! RefungibleHandle_result {...}57 impl<T: Config> Contract for RefungibleHandle<T> {...}58}5960pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);6162/// Rft events.63#[derive(ToLog)]64pub enum ERC721TokenEvent {65 /// The token has been changed.66 TokenChanged {67 /// Token ID.68 #[indexed]69 token_id: U256,70 },71}7273/// @title A contract that allows to set and delete token properties and change token property permissions.74#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]75impl<T: Config> RefungibleHandle<T> {76 /// @notice Set permissions for token property.77 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.78 /// @param key Property key.79 /// @param isMutable Permission to mutate property.80 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.81 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.82 #[solidity(hide)]83 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]84 fn set_token_property_permission(85 &mut self,86 caller: Caller,87 key: String,88 is_mutable: bool,89 collection_admin: bool,90 token_owner: bool,91 ) -> Result<()> {92 let caller = T::CrossAccountId::from_eth(caller);93 <Pallet<T>>::set_token_property_permissions(94 self,95 &caller,96 vec![PropertyKeyPermission {97 key: <Vec<u8>>::from(key)98 .try_into()99 .map_err(|_| "too long key")?,100 permission: PropertyPermission {101 mutable: is_mutable,102 collection_admin,103 token_owner,104 },105 }],106 )107 .map_err(dispatch_to_evm::<T>)108 }109110 /// @notice Set permissions for token property.111 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.112 /// @param permissions Permissions for keys.113 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]114 fn set_token_property_permissions(115 &mut self,116 caller: Caller,117 permissions: Vec<eth::TokenPropertyPermission>,118 ) -> Result<()> {119 let caller = T::CrossAccountId::from_eth(caller);120 let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;121122 <Pallet<T>>::set_token_property_permissions(self, &caller, perms)123 .map_err(dispatch_to_evm::<T>)124 }125126 /// @notice Get permissions for token properties.127 fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {128 let perms = <Pallet<T>>::token_property_permission(self.id);129 Ok(perms130 .into_iter()131 .map(eth::TokenPropertyPermission::from)132 .collect())133 }134135 /// @notice Set token property value.136 /// @dev Throws error if `msg.sender` has no permission to edit the property.137 /// @param tokenId ID of the token.138 /// @param key Property key.139 /// @param value Property value.140 #[solidity(hide)]141 #[weight(<SelfWeightOf<T>>::set_token_properties(1))]142 fn set_property(143 &mut self,144 caller: Caller,145 token_id: U256,146 key: String,147 value: Bytes,148 ) -> Result<()> {149 let caller = T::CrossAccountId::from_eth(caller);150 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;151 let key = <Vec<u8>>::from(key)152 .try_into()153 .map_err(|_| "key too long")?;154 let value = value.0.try_into().map_err(|_| "value too long")?;155156 let nesting_budget = self157 .recorder158 .weight_calls_budget(<StructureWeight<T>>::find_parent());159160 <Pallet<T>>::set_token_property(161 self,162 &caller,163 TokenId(token_id),164 Property { key, value },165 &nesting_budget,166 )167 .map_err(dispatch_to_evm::<T>)168 }169170 /// @notice Set token properties value.171 /// @dev Throws error if `msg.sender` has no permission to edit the property.172 /// @param tokenId ID of the token.173 /// @param properties settable properties174 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]175 fn set_properties(176 &mut self,177 caller: Caller,178 token_id: U256,179 properties: Vec<eth::Property>,180 ) -> Result<()> {181 let caller = T::CrossAccountId::from_eth(caller);182 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;183184 let nesting_budget = self185 .recorder186 .weight_calls_budget(<StructureWeight<T>>::find_parent());187188 let properties = properties189 .into_iter()190 .map(eth::Property::try_into)191 .collect::<Result<Vec<_>>>()?;192193 <Pallet<T>>::set_token_properties(194 self,195 &caller,196 TokenId(token_id),197 properties.into_iter(),198 false,199 &nesting_budget,200 )201 .map_err(dispatch_to_evm::<T>)202 }203204 /// @notice Delete token property value.205 /// @dev Throws error if `msg.sender` has no permission to edit the property.206 /// @param tokenId ID of the token.207 /// @param key Property key.208 #[solidity(hide)]209 #[weight(<SelfWeightOf<T>>::delete_token_properties(1))]210 fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {211 let caller = T::CrossAccountId::from_eth(caller);212 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;213 let key = <Vec<u8>>::from(key)214 .try_into()215 .map_err(|_| "key too long")?;216217 let nesting_budget = self218 .recorder219 .weight_calls_budget(<StructureWeight<T>>::find_parent());220221 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)222 .map_err(dispatch_to_evm::<T>)223 }224225 /// @notice Delete token properties value.226 /// @dev Throws error if `msg.sender` has no permission to edit the property.227 /// @param tokenId ID of the token.228 /// @param keys Properties key.229 #[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]230 fn delete_properties(231 &mut self,232 token_id: U256,233 caller: Caller,234 keys: Vec<String>,235 ) -> Result<()> {236 let caller = T::CrossAccountId::from_eth(caller);237 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;238 let keys = keys239 .into_iter()240 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))241 .collect::<Result<Vec<_>>>()?;242243 let nesting_budget = self244 .recorder245 .weight_calls_budget(<StructureWeight<T>>::find_parent());246247 <Pallet<T>>::delete_token_properties(248 self,249 &caller,250 TokenId(token_id),251 keys.into_iter(),252 &nesting_budget,253 )254 .map_err(dispatch_to_evm::<T>)255 }256257 /// @notice Get token property value.258 /// @dev Throws error if key not found259 /// @param tokenId ID of the token.260 /// @param key Property key.261 /// @return Property value bytes262 fn property(&self, token_id: U256, key: String) -> Result<Bytes> {263 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;264 let key = <Vec<u8>>::from(key)265 .try_into()266 .map_err(|_| "key too long")?;267268 let props = <TokenProperties<T>>::get((self.id, token_id));269 let prop = props.get(&key).ok_or("key not found")?;270271 Ok(prop.to_vec().into())272 }273}274275#[derive(ToLog)]276pub enum ERC721Events {277 /// @dev This event emits when NFTs are created (`from` == 0) and destroyed278 /// (`to` == 0). Exception: during contract creation, any number of RFTs279 /// may be created and assigned without emitting Transfer.280 Transfer {281 #[indexed]282 from: Address,283 #[indexed]284 to: Address,285 #[indexed]286 token_id: U256,287 },288 /// @dev Not supported289 Approval {290 #[indexed]291 owner: Address,292 #[indexed]293 approved: Address,294 #[indexed]295 token_id: U256,296 },297 /// @dev Not supported298 #[allow(dead_code)]299 ApprovalForAll {300 #[indexed]301 owner: Address,302 #[indexed]303 operator: Address,304 approved: bool,305 },306}307308/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension309/// @dev See https://eips.ethereum.org/EIPS/eip-721310#[solidity_interface(name = ERC721Metadata, enum(derive(PreDispatch)), expect_selector = 0x5b5e139f)]311impl<T: Config> RefungibleHandle<T>312where313 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,314{315 /// @notice A descriptive name for a collection of NFTs in this contract316 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`317 #[solidity(hide, rename_selector = "name")]318 fn name_proxy(&self) -> Result<String> {319 self.name()320 }321322 /// @notice An abbreviated name for NFTs in this contract323 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`324 #[solidity(hide, rename_selector = "symbol")]325 fn symbol_proxy(&self) -> Result<String> {326 self.symbol()327 }328329 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.330 ///331 /// @dev If the token has a `url` property and it is not empty, it is returned.332 /// 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`.333 /// If the collection property `baseURI` is empty or absent, return "" (empty string)334 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix335 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).336 ///337 /// @return token's const_metadata338 #[solidity(rename_selector = "tokenURI")]339 fn token_uri(&self, token_id: U256) -> Result<String> {340 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;341342 match get_token_property(self, token_id_u32, &key::url()).as_deref() {343 Err(_) | Ok("") => (),344 Ok(url) => {345 return Ok(url.into());346 }347 };348349 let base_uri =350 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())351 .map(BoundedVec::into_inner)352 .map(String::from_utf8)353 .transpose()354 .map_err(|e| {355 Error::Revert(alloc::format!(356 "Can not convert value \"baseURI\" to string with error \"{}\"",357 e358 ))359 })?;360361 let base_uri = match base_uri.as_deref() {362 None | Some("") => {363 return Ok("".into());364 }365 Some(base_uri) => base_uri.into(),366 };367368 Ok(369 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {370 Err(_) | Ok("") => base_uri,371 Ok(suffix) => base_uri + suffix,372 },373 )374 }375}376377/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension378/// @dev See https://eips.ethereum.org/EIPS/eip-721379#[solidity_interface(name = ERC721Enumerable, enum(derive(PreDispatch)), expect_selector = 0x780e9d63)]380impl<T: Config> RefungibleHandle<T> {381 /// @notice Enumerate valid RFTs382 /// @param index A counter less than `totalSupply()`383 /// @return The token identifier for the `index`th NFT,384 /// (sort order not specified)385 fn token_by_index(&self, index: U256) -> U256 {386 index387 }388389 /// Not implemented390 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {391 // TODO: Not implemetable392 Err("not implemented".into())393 }394395 /// @notice Count RFTs tracked by this contract396 /// @return A count of valid RFTs tracked by this contract, where each one of397 /// them has an assigned and queryable owner not equal to the zero address398 fn total_supply(&self) -> Result<U256> {399 self.consume_store_reads(1)?;400 Ok(<Pallet<T>>::total_supply(self).into())401 }402}403404/// @title ERC-721 Non-Fungible Token Standard405/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md406#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]407impl<T: Config> RefungibleHandle<T> {408 /// @notice Count all RFTs assigned to an owner409 /// @dev RFTs assigned to the zero address are considered invalid, and this410 /// function throws for queries about the zero address.411 /// @param owner An address for whom to query the balance412 /// @return The number of RFTs owned by `owner`, possibly zero413 fn balance_of(&self, owner: Address) -> Result<U256> {414 self.consume_store_reads(1)?;415 let owner = T::CrossAccountId::from_eth(owner);416 let balance = <AccountBalance<T>>::get((self.id, owner));417 Ok(balance.into())418 }419420 /// @notice Find the owner of an RFT421 /// @dev RFTs assigned to zero address are considered invalid, and queries422 /// about them do throw.423 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for424 /// the tokens that are partially owned.425 /// @param tokenId The identifier for an RFT426 /// @return The address of the owner of the RFT427 fn owner_of(&self, token_id: U256) -> Result<Address> {428 self.consume_store_reads(2)?;429 let token = token_id.try_into()?;430 let owner = <Pallet<T>>::token_owner(self.id, token);431 owner432 .map(|address| *address.as_eth())433 .or_else(|err| match err {434 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),435 TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),436 })437 }438439 /// @dev Not implemented440 #[solidity(rename_selector = "safeTransferFrom")]441 fn safe_transfer_from_with_data(442 &mut self,443 _from: Address,444 _to: Address,445 _token_id: U256,446 _data: Bytes,447 ) -> Result<()> {448 // TODO: Not implemetable449 Err("not implemented".into())450 }451452 /// @dev Not implemented453 #[solidity(rename_selector = "safeTransferFrom")]454 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {455 // TODO: Not implemetable456 Err("not implemented".into())457 }458459 /// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE460 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE461 /// THEY MAY BE PERMANENTLY LOST462 /// @dev Throws unless `msg.sender` is the current owner or an authorized463 /// operator for this RFT. Throws if `from` is not the current owner. Throws464 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.465 /// Throws if RFT pieces have multiple owners.466 /// @param from The current owner of the NFT467 /// @param to The new owner468 /// @param tokenId The NFT to transfer469 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]470 fn transfer_from(471 &mut self,472 caller: Caller,473 from: Address,474 to: Address,475 token_id: U256,476 ) -> Result<()> {477 let caller = T::CrossAccountId::from_eth(caller);478 let from = T::CrossAccountId::from_eth(from);479 let to = T::CrossAccountId::from_eth(to);480 let token = token_id.try_into()?;481 let budget = self482 .recorder483 .weight_calls_budget(<StructureWeight<T>>::find_parent());484485 let balance = balance(&self, token, &from)?;486 ensure_single_owner(&self, token, balance)?;487488 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)489 .map_err(dispatch_to_evm::<T>)?;490491 Ok(())492 }493494 /// @dev Not implemented495 fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {496 Err("not implemented".into())497 }498499 /// @notice Sets or unsets the approval of a given operator.500 /// The `operator` is allowed to transfer all token pieces of the `caller` on their behalf.501 /// @param operator Operator502 /// @param approved Should operator status be granted or revoked?503 #[weight(<SelfWeightOf<T>>::set_allowance_for_all())]504 fn set_approval_for_all(505 &mut self,506 caller: Caller,507 operator: Address,508 approved: bool,509 ) -> Result<()> {510 let caller = T::CrossAccountId::from_eth(caller);511 let operator = T::CrossAccountId::from_eth(operator);512513 <Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)514 .map_err(dispatch_to_evm::<T>)?;515 Ok(())516 }517518 /// @dev Not implemented519 fn get_approved(&self, _token_id: U256) -> Result<Address> {520 // TODO: Not implemetable521 Err("not implemented".into())522 }523524 /// @notice Tells whether the given `owner` approves the `operator`.525 #[weight(<SelfWeightOf<T>>::allowance_for_all())]526 fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {527 let owner = T::CrossAccountId::from_eth(owner);528 let operator = T::CrossAccountId::from_eth(operator);529530 Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))531 }532}533534/// Returns amount of pieces of `token` that `owner` have535pub fn balance<T: Config>(536 collection: &RefungibleHandle<T>,537 token: TokenId,538 owner: &T::CrossAccountId,539) -> Result<u128> {540 collection.consume_store_reads(1)?;541 let balance = <Balance<T>>::get((collection.id, token, &owner));542 Ok(balance)543}544545/// Throws if `owner_balance` is lower than total amount of `token` pieces546pub fn ensure_single_owner<T: Config>(547 collection: &RefungibleHandle<T>,548 token: TokenId,549 owner_balance: u128,550) -> Result<()> {551 collection.consume_store_reads(1)?;552 let total_supply = <TotalSupply<T>>::get((collection.id, token));553554 if owner_balance == 0 {555 return Err(dispatch_to_evm::<T>(556 <CommonError<T>>::MustBeTokenOwner.into(),557 ));558 }559560 if total_supply != owner_balance {561 return Err("token has multiple owners".into());562 }563 Ok(())564}565566/// @title ERC721 Token that can be irreversibly burned (destroyed).567#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]568impl<T: Config> RefungibleHandle<T> {569 /// @notice Burns a specific ERC721 token.570 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized571 /// operator of the current owner.572 /// @param tokenId The RFT to approve573 #[weight(<SelfWeightOf<T>>::burn_item_fully())]574 fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {575 let caller = T::CrossAccountId::from_eth(caller);576 let token = token_id.try_into()?;577578 let balance = balance(&self, token, &caller)?;579 ensure_single_owner(&self, token, balance)?;580581 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;582 Ok(())583 }584}585586/// @title ERC721 minting logic.587#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]588impl<T: Config> RefungibleHandle<T> {589 /// @notice Function to mint a token.590 /// @param to The new owner591 /// @return uint256 The id of the newly minted token592 #[weight(<SelfWeightOf<T>>::create_item())]593 fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {594 let token_id: U256 = <TokensMinted<T>>::get(self.id)595 .checked_add(1)596 .ok_or("item id overflow")?597 .into();598 self.mint_check_id(caller, to, token_id)?;599 Ok(token_id)600 }601602 /// @notice Function to mint a token.603 /// @dev `tokenId` should be obtained with `nextTokenId` method,604 /// unlike standard, you can't specify it manually605 /// @param to The new owner606 /// @param tokenId ID of the minted RFT607 #[solidity(hide, rename_selector = "mint")]608 #[weight(<SelfWeightOf<T>>::create_item())]609 fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {610 let caller = T::CrossAccountId::from_eth(caller);611 let to = T::CrossAccountId::from_eth(to);612 let token_id: u32 = token_id.try_into()?;613 let budget = self614 .recorder615 .weight_calls_budget(<StructureWeight<T>>::find_parent());616617 if <TokensMinted<T>>::get(self.id)618 .checked_add(1)619 .ok_or("item id overflow")?620 != token_id621 {622 return Err("item id should be next".into());623 }624625 let users = [(to.clone(), 1)]626 .into_iter()627 .collect::<BTreeMap<_, _>>()628 .try_into()629 .unwrap();630 <Pallet<T>>::create_item(631 self,632 &caller,633 CreateItemData::<T> {634 users,635 properties: CollectionPropertiesVec::default(),636 },637 &budget,638 )639 .map_err(dispatch_to_evm::<T>)?;640641 Ok(true)642 }643644 /// @notice Function to mint token with the given tokenUri.645 /// @param to The new owner646 /// @param tokenUri Token URI that would be stored in the NFT properties647 /// @return uint256 The id of the newly minted token648 #[solidity(rename_selector = "mintWithTokenURI")]649 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]650 fn mint_with_token_uri(651 &mut self,652 caller: Caller,653 to: Address,654 token_uri: String,655 ) -> Result<U256> {656 let token_id: U256 = <TokensMinted<T>>::get(self.id)657 .checked_add(1)658 .ok_or("item id overflow")?659 .into();660 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;661 Ok(token_id)662 }663664 /// @notice Function to mint token with the given tokenUri.665 /// @dev `tokenId` should be obtained with `nextTokenId` method,666 /// unlike standard, you can't specify it manually667 /// @param to The new owner668 /// @param tokenId ID of the minted RFT669 /// @param tokenUri Token URI that would be stored in the RFT properties670 #[solidity(hide, rename_selector = "mintWithTokenURI")]671 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]672 fn mint_with_token_uri_check_id(673 &mut self,674 caller: Caller,675 to: Address,676 token_id: U256,677 token_uri: String,678 ) -> Result<bool> {679 let key = key::url();680 let permission = get_token_permission::<T>(self.id, &key)?;681 if !permission.collection_admin {682 return Err("Operation is not allowed".into());683 }684685 let caller = T::CrossAccountId::from_eth(caller);686 let to = T::CrossAccountId::from_eth(to);687 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;688 let budget = self689 .recorder690 .weight_calls_budget(<StructureWeight<T>>::find_parent());691692 if <TokensMinted<T>>::get(self.id)693 .checked_add(1)694 .ok_or("item id overflow")?695 != token_id696 {697 return Err("item id should be next".into());698 }699700 let mut properties = CollectionPropertiesVec::default();701 properties702 .try_push(Property {703 key,704 value: token_uri705 .into_bytes()706 .try_into()707 .map_err(|_| "token uri is too long")?,708 })709 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;710711 let users = [(to.clone(), 1)]712 .into_iter()713 .collect::<BTreeMap<_, _>>()714 .try_into()715 .unwrap();716 <Pallet<T>>::create_item(717 self,718 &caller,719 CreateItemData::<T> { users, properties },720 &budget,721 )722 .map_err(dispatch_to_evm::<T>)?;723 Ok(true)724 }725}726727fn get_token_property<T: Config>(728 collection: &CollectionHandle<T>,729 token_id: u32,730 key: &up_data_structs::PropertyKey,731) -> Result<String> {732 collection.consume_store_reads(1)?;733 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))734 .map_err(|_| Error::Revert("Token properties not found".into()))?;735 if let Some(property) = properties.get(key) {736 return Ok(String::from_utf8_lossy(property).into());737 }738739 Err("Property tokenURI not found".into())740}741742fn get_token_permission<T: Config>(743 collection_id: CollectionId,744 key: &PropertyKey,745) -> Result<PropertyPermission> {746 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)747 .map_err(|_| Error::Revert("No permissions for collection".into()))?;748 let a = token_property_permissions749 .get(key)750 .map(Clone::clone)751 .ok_or_else(|| {752 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();753 Error::Revert(alloc::format!("No permission for key {}", key))754 })?;755 Ok(a)756}757758/// @title Unique extensions for ERC721.759#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]760impl<T: Config> RefungibleHandle<T>761where762 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,763{764 /// @notice A descriptive name for a collection of NFTs in this contract765 fn name(&self) -> Result<String> {766 Ok(decode_utf16(self.name.iter().copied())767 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))768 .collect::<String>())769 }770771 /// @notice An abbreviated name for NFTs in this contract772 fn symbol(&self) -> Result<String> {773 Ok(String::from_utf8_lossy(&self.token_prefix).into())774 }775776 /// @notice A description for the collection.777 fn description(&self) -> Result<String> {778 Ok(decode_utf16(self.description.iter().copied())779 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))780 .collect::<String>())781 }782783 /// Returns the owner (in cross format) of the token.784 ///785 /// @param tokenId Id for the token.786 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {787 Self::token_owner(&self, token_id.try_into()?)788 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))789 .or_else(|err| match err {790 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),791 TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(792 ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,793 )),794 })795 }796797 /// Returns the token properties.798 ///799 /// @param tokenId Id for the token.800 /// @param keys Properties keys. Empty keys for all propertyes.801 /// @return Vector of properties key/value pairs.802 fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {803 let keys = keys804 .into_iter()805 .map(|key| {806 <Vec<u8>>::from(key)807 .try_into()808 .map_err(|_| Error::Revert("key too large".into()))809 })810 .collect::<Result<Vec<_>>>()?;811812 <Self as CommonCollectionOperations<T>>::token_properties(813 &self,814 token_id.try_into()?,815 if keys.is_empty() { None } else { Some(keys) },816 )817 .into_iter()818 .map(eth::Property::try_from)819 .collect::<Result<Vec<_>>>()820 }821 /// @notice Transfer ownership of an RFT822 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`823 /// is the zero address. Throws if `tokenId` is not a valid RFT.824 /// Throws if RFT pieces have multiple owners.825 /// @param to The new owner826 /// @param tokenId The RFT to transfer827 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]828 fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {829 let caller = T::CrossAccountId::from_eth(caller);830 let to = T::CrossAccountId::from_eth(to);831 let token = token_id.try_into()?;832 let budget = self833 .recorder834 .weight_calls_budget(<StructureWeight<T>>::find_parent());835836 let balance = balance(self, token, &caller)?;837 ensure_single_owner(self, token, balance)?;838839 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)840 .map_err(dispatch_to_evm::<T>)?;841 Ok(())842 }843844 /// @notice Transfer ownership of an RFT845 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`846 /// is the zero address. Throws if `tokenId` is not a valid RFT.847 /// Throws if RFT pieces have multiple owners.848 /// @param to The new owner849 /// @param tokenId The RFT to transfer850 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]851 fn transfer_cross(852 &mut self,853 caller: Caller,854 to: eth::CrossAddress,855 token_id: U256,856 ) -> Result<()> {857 let caller = T::CrossAccountId::from_eth(caller);858 let to = to.into_sub_cross_account::<T>()?;859 let token = token_id.try_into()?;860 let budget = self861 .recorder862 .weight_calls_budget(<StructureWeight<T>>::find_parent());863864 let balance = balance(self, token, &caller)?;865 ensure_single_owner(self, token, balance)?;866867 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)868 .map_err(dispatch_to_evm::<T>)?;869 Ok(())870 }871872 /// @notice Transfer ownership of an RFT873 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`874 /// is the zero address. Throws if `tokenId` is not a valid RFT.875 /// Throws if RFT pieces have multiple owners.876 /// @param to The new owner877 /// @param tokenId The RFT to transfer878 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]879 fn transfer_from_cross(880 &mut self,881 caller: Caller,882 from: eth::CrossAddress,883 to: eth::CrossAddress,884 token_id: U256,885 ) -> Result<()> {886 let caller = T::CrossAccountId::from_eth(caller);887 let from = from.into_sub_cross_account::<T>()?;888 let to = to.into_sub_cross_account::<T>()?;889 let token_id = token_id.try_into()?;890 let budget = self891 .recorder892 .weight_calls_budget(<StructureWeight<T>>::find_parent());893894 let balance = balance(self, token_id, &from)?;895 ensure_single_owner(self, token_id, balance)?;896897 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)898 .map_err(dispatch_to_evm::<T>)?;899 Ok(())900 }901902 /// @notice Burns a specific ERC721 token.903 /// @dev Throws unless `msg.sender` is the current owner or an authorized904 /// operator for this RFT. Throws if `from` is not the current owner. Throws905 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.906 /// Throws if RFT pieces have multiple owners.907 /// @param from The current owner of the RFT908 /// @param tokenId The RFT to transfer909 #[solidity(hide)]910 #[weight(<SelfWeightOf<T>>::burn_from())]911 fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {912 let caller = T::CrossAccountId::from_eth(caller);913 let from = T::CrossAccountId::from_eth(from);914 let token = token_id.try_into()?;915 let budget = self916 .recorder917 .weight_calls_budget(<StructureWeight<T>>::find_parent());918919 let balance = balance(self, token, &from)?;920 ensure_single_owner(self, token, balance)?;921922 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)923 .map_err(dispatch_to_evm::<T>)?;924 Ok(())925 }926927 /// @notice Burns a specific ERC721 token.928 /// @dev Throws unless `msg.sender` is the current owner or an authorized929 /// operator for this RFT. Throws if `from` is not the current owner. Throws930 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.931 /// Throws if RFT pieces have multiple owners.932 /// @param from The current owner of the RFT933 /// @param tokenId The RFT to transfer934 #[weight(<SelfWeightOf<T>>::burn_from())]935 fn burn_from_cross(936 &mut self,937 caller: Caller,938 from: eth::CrossAddress,939 token_id: U256,940 ) -> Result<()> {941 let caller = T::CrossAccountId::from_eth(caller);942 let from = from.into_sub_cross_account::<T>()?;943 let token = token_id.try_into()?;944 let budget = self945 .recorder946 .weight_calls_budget(<StructureWeight<T>>::find_parent());947948 let balance = balance(self, token, &from)?;949 ensure_single_owner(self, token, balance)?;950951 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)952 .map_err(dispatch_to_evm::<T>)?;953 Ok(())954 }955956 /// @notice Returns next free RFT ID.957 fn next_token_id(&self) -> Result<U256> {958 self.consume_store_reads(1)?;959 Ok(<TokensMinted<T>>::get(self.id)960 .checked_add(1)961 .ok_or("item id overflow")?962 .into())963 }964965 /// @notice Function to mint multiple tokens.966 /// @dev `tokenIds` should be an array of consecutive numbers and first number967 /// should be obtained with `nextTokenId` method968 /// @param to The new owner969 /// @param tokenIds IDs of the minted RFTs970 #[solidity(hide)]971 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]972 fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {973 let caller = T::CrossAccountId::from_eth(caller);974 let to = T::CrossAccountId::from_eth(to);975 let mut expected_index = <TokensMinted<T>>::get(self.id)976 .checked_add(1)977 .ok_or("item id overflow")?;978 let budget = self979 .recorder980 .weight_calls_budget(<StructureWeight<T>>::find_parent());981982 let total_tokens = token_ids.len();983 for id in token_ids.into_iter() {984 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;985 if id != expected_index {986 return Err("item id should be next".into());987 }988 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;989 }990 let users = [(to.clone(), 1)]991 .into_iter()992 .collect::<BTreeMap<_, _>>()993 .try_into()994 .unwrap();995 let create_item_data = CreateItemData::<T> {996 users,997 properties: CollectionPropertiesVec::default(),998 };999 let data = (0..total_tokens)1000 .map(|_| create_item_data.clone())1001 .collect();10021003 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1004 .map_err(dispatch_to_evm::<T>)?;1005 Ok(true)1006 }10071008 /// @notice Function to mint multiple tokens with the given tokenUris.1009 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive1010 /// numbers and first number should be obtained with `nextTokenId` method1011 /// @param to The new owner1012 /// @param tokens array of pairs of token ID and token URI for minted tokens1013 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1014 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]1015 fn mint_bulk_with_token_uri(1016 &mut self,1017 caller: Caller,1018 to: Address,1019 tokens: Vec<TokenUri>,1020 ) -> Result<bool> {1021 let key = key::url();1022 let caller = T::CrossAccountId::from_eth(caller);1023 let to = T::CrossAccountId::from_eth(to);1024 let mut expected_index = <TokensMinted<T>>::get(self.id)1025 .checked_add(1)1026 .ok_or("item id overflow")?;1027 let budget = self1028 .recorder1029 .weight_calls_budget(<StructureWeight<T>>::find_parent());10301031 let mut data = Vec::with_capacity(tokens.len());1032 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]1033 .into_iter()1034 .collect::<BTreeMap<_, _>>()1035 .try_into()1036 .unwrap();1037 for TokenUri { id, uri } in tokens {1038 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1039 if id != expected_index {1040 return Err("item id should be next".into());1041 }1042 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10431044 let mut properties = CollectionPropertiesVec::default();1045 properties1046 .try_push(Property {1047 key: key.clone(),1048 value: uri1049 .into_bytes()1050 .try_into()1051 .map_err(|_| "token uri is too long")?,1052 })1053 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;10541055 let create_item_data = CreateItemData::<T> {1056 users: users.clone(),1057 properties,1058 };1059 data.push(create_item_data);1060 }10611062 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1063 .map_err(dispatch_to_evm::<T>)?;1064 Ok(true)1065 }10661067 /// @notice Function to mint a token.1068 /// @param to The new owner crossAccountId1069 /// @param properties Properties of minted token1070 /// @return uint256 The id of the newly minted token1071 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1072 fn mint_cross(1073 &mut self,1074 caller: Caller,1075 to: eth::CrossAddress,1076 properties: Vec<eth::Property>,1077 ) -> Result<U256> {1078 let token_id = <TokensMinted<T>>::get(self.id)1079 .checked_add(1)1080 .ok_or("item id overflow")?;10811082 let to = to.into_sub_cross_account::<T>()?;10831084 let properties = properties1085 .into_iter()1086 .map(eth::Property::try_into)1087 .collect::<Result<Vec<_>>>()?1088 .try_into()1089 .map_err(|_| Error::Revert(alloc::format!("too many properties")))?;10901091 let caller = T::CrossAccountId::from_eth(caller);10921093 let budget = self1094 .recorder1095 .weight_calls_budget(<StructureWeight<T>>::find_parent());10961097 let users = [(to, 1)]1098 .into_iter()1099 .collect::<BTreeMap<_, _>>()1100 .try_into()1101 .unwrap();1102 <Pallet<T>>::create_item(1103 self,1104 &caller,1105 CreateItemData::<T> { users, properties },1106 &budget,1107 )1108 .map_err(dispatch_to_evm::<T>)?;11091110 Ok(token_id.into())1111 }11121113 /// Returns EVM address for refungible token1114 ///1115 /// @param token ID of the token1116 fn token_contract_address(&self, token: U256) -> Result<Address> {1117 Ok(T::EvmTokenAddressMapping::token_to_address(1118 self.id,1119 token.try_into().map_err(|_| "token id overflow")?,1120 ))1121 }11221123 /// @notice Returns collection helper contract address1124 fn collection_helper_address(&self) -> Result<Address> {1125 Ok(T::ContractAddress::get())1126 }1127}11281129#[solidity_interface(1130 name = UniqueRefungible,1131 is(1132 ERC721,1133 ERC721Enumerable,1134 ERC721UniqueExtensions,1135 ERC721UniqueMintable,1136 ERC721Burnable,1137 ERC721Metadata(if(this.flags.erc721metadata)),1138 Collection(via(common_mut returns CollectionHandle<T>)),1139 TokenProperties,1140 ),1141 enum(derive(PreDispatch)),1142)]1143impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}11441145// Not a tests, but code generators1146generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1147generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);11481149impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1150where1151 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1152{1153 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1154 fn call(1155 self,1156 handle: &mut impl PrecompileHandle,1157 ) -> Option<pallet_common::erc::PrecompileResult> {1158 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1159 }1160}pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -19,7 +19,7 @@
/// @dev inlined interface
contract ERC721TokenEvent {
- event TokenChanged(address indexed collectionId, uint256 tokenId);
+ event TokenChanged(uint256 indexed tokenId);
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
tests/src/eth/abi/nonFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/nonFungible.json
+++ b/tests/src/eth/abi/nonFungible.json
@@ -54,12 +54,6 @@
"inputs": [
{
"indexed": true,
- "internalType": "address",
- "name": "collectionId",
- "type": "address"
- },
- {
- "indexed": false,
"internalType": "uint256",
"name": "tokenId",
"type": "uint256"
tests/src/eth/abi/reFungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungible.json
+++ b/tests/src/eth/abi/reFungible.json
@@ -54,12 +54,6 @@
"inputs": [
{
"indexed": true,
- "internalType": "address",
- "name": "collectionId",
- "type": "address"
- },
- {
- "indexed": false,
"internalType": "uint256",
"name": "tokenId",
"type": "uint256"
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -14,7 +14,7 @@
/// @dev inlined interface
interface ERC721TokenEvent {
- event TokenChanged(address indexed collectionId, uint256 tokenId);
+ event TokenChanged(uint256 indexed tokenId);
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -14,7 +14,7 @@
/// @dev inlined interface
interface ERC721TokenEvent {
- event TokenChanged(address indexed collectionId, uint256 tokenId);
+ event TokenChanged(uint256 indexed tokenId);
}
/// @title A contract that allows to set and delete token properties and change token property permissions.
tests/src/eth/events.test.tsdiffbeforeafterboth--- a/tests/src/eth/events.test.ts
+++ b/tests/src/eth/events.test.ts
@@ -393,7 +393,6 @@
expect(result.events.TokenChanged).to.be.like({
event: 'TokenChanged',
returnValues: {
- collectionId: collectionAddress,
tokenId: tokenId,
},
});
@@ -406,7 +405,6 @@
expect(result.events.TokenChanged).to.be.like({
event: 'TokenChanged',
returnValues: {
- collectionId: collectionAddress,
tokenId: tokenId,
},
});