12345678910111213141516171819202122extern 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);616263#[derive(ToLog)]64pub enum ERC721TokenEvent {65 66 TokenChanged {67 68 #[indexed]69 collection_id: Address,70 71 token_id: U256,72 },73}747576#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]77impl<T: Config> RefungibleHandle<T> {78 79 80 81 82 83 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 113 114 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 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 138 139 140 141 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 173 174 175 176 #[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 207 208 209 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 228 229 230 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 260 261 262 263 264 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 280 281 282 Transfer {283 #[indexed]284 from: Address,285 #[indexed]286 to: Address,287 #[indexed]288 token_id: U256,289 },290 291 Approval {292 #[indexed]293 owner: Address,294 #[indexed]295 approved: Address,296 #[indexed]297 token_id: U256,298 },299 300 #[allow(dead_code)]301 ApprovalForAll {302 #[indexed]303 owner: Address,304 #[indexed]305 operator: Address,306 approved: bool,307 },308}309310311312#[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 318 319 #[solidity(hide, rename_selector = "name")]320 fn name_proxy(&self) -> Result<String> {321 self.name()322 }323324 325 326 #[solidity(hide, rename_selector = "symbol")]327 fn symbol_proxy(&self) -> Result<String> {328 self.symbol()329 }330331 332 333 334 335 336 337 338 339 340 #[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}378379380381#[solidity_interface(name = ERC721Enumerable, enum(derive(PreDispatch)), expect_selector = 0x780e9d63)]382impl<T: Config> RefungibleHandle<T> {383 384 385 386 387 fn token_by_index(&self, index: U256) -> U256 {388 index389 }390391 392 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {393 394 Err("not implemented".into())395 }396397 398 399 400 fn total_supply(&self) -> Result<U256> {401 self.consume_store_reads(1)?;402 Ok(<Pallet<T>>::total_supply(self).into())403 }404}405406407408#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]409impl<T: Config> RefungibleHandle<T> {410 411 412 413 414 415 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 423 424 425 426 427 428 429 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 442 #[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 451 Err("not implemented".into())452 }453454 455 #[solidity(rename_selector = "safeTransferFrom")]456 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {457 458 Err("not implemented".into())459 }460461 462 463 464 465 466 467 468 469 470 471 #[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 497 fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {498 Err("not implemented".into())499 }500501 502 503 504 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 521 fn get_approved(&self, _token_id: U256) -> Result<Address> {522 523 Err("not implemented".into())524 }525526 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}535536537pub 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}546547548pub 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}567568569#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]570impl<T: Config> RefungibleHandle<T> {571 572 573 574 575 #[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}587588589#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]590impl<T: Config> RefungibleHandle<T> {591 592 593 594 #[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 605 606 607 608 609 #[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 647 648 649 650 #[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 667 668 669 670 671 672 #[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}759760761#[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 767 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 774 fn symbol(&self) -> Result<String> {775 Ok(String::from_utf8_lossy(&self.token_prefix).into())776 }777778 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 786 787 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 800 801 802 803 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 824 825 826 827 828 829 #[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 847 848 849 850 851 852 #[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 875 876 877 878 879 880 #[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 905 906 907 908 909 910 911 #[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 930 931 932 933 934 935 936 #[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 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 968 969 970 971 972 #[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 1011 1012 1013 1014 1015 #[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 1070 1071 1072 1073 #[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 1116 1117 1118 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 1126 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]> {}114611471148generate_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}