12345678910111213141516171819202122extern crate alloc;2324use alloc::string::ToString;25use core::{26 char::{REPLACEMENT_CHARACTER, decode_utf16},27 convert::TryInto,28};29use evm_coder::{abi::AbiType, ToLog, generate_stubgen, solidity_interface, types::*};30use frame_support::{BoundedBTreeMap, BoundedVec};31use pallet_common::{32 CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,33 Error as CommonError,34 erc::{CommonEvmHandler, CollectionCall, static_property::key},35 eth::{self, TokenUri},36};37use pallet_evm::{account::CrossAccountId, PrecompileHandle};38use pallet_evm_coder_substrate::{39 call, dispatch_to_evm,40 execution::{PreDispatch, Result, Error},41 frontier_contract,42};43use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};44use sp_core::{H160, U256, Get};45use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};46use up_data_structs::{47 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,48 PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,49};5051use crate::{52 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, TokenProperties,53 TokensMinted, TotalSupply, SelfWeightOf, weights::WeightInfo,54};5556frontier_contract! {57 macro_rules! RefungibleHandle_result {...}58 impl<T: Config> Contract for RefungibleHandle<T> {...}59}6061pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);626364#[derive(ToLog)]65pub enum ERC721TokenEvent {66 67 TokenChanged {68 69 #[indexed]70 token_id: U256,71 },72}737475#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]76impl<T: Config> RefungibleHandle<T> {77 78 79 80 81 82 83 #[solidity(hide)]84 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]85 fn set_token_property_permission(86 &mut self,87 caller: Caller,88 key: String,89 is_mutable: bool,90 collection_admin: bool,91 token_owner: bool,92 ) -> Result<()> {93 let caller = T::CrossAccountId::from_eth(caller);94 <Pallet<T>>::set_token_property_permissions(95 self,96 &caller,97 vec![PropertyKeyPermission {98 key: <Vec<u8>>::from(key)99 .try_into()100 .map_err(|_| "too long key")?,101 permission: PropertyPermission {102 mutable: is_mutable,103 collection_admin,104 token_owner,105 },106 }],107 )108 .map_err(dispatch_to_evm::<T>)109 }110111 112 113 114 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]115 fn set_token_property_permissions(116 &mut self,117 caller: Caller,118 permissions: Vec<eth::TokenPropertyPermission>,119 ) -> Result<()> {120 let caller = T::CrossAccountId::from_eth(caller);121 let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;122123 <Pallet<T>>::set_token_property_permissions(self, &caller, perms)124 .map_err(dispatch_to_evm::<T>)125 }126127 128 fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {129 let perms = <Pallet<T>>::token_property_permission(self.id);130 Ok(perms131 .into_iter()132 .map(eth::TokenPropertyPermission::from)133 .collect())134 }135136 137 138 139 140 141 #[solidity(hide)]142 #[weight(<SelfWeightOf<T>>::set_token_properties(1))]143 fn set_property(144 &mut self,145 caller: Caller,146 token_id: U256,147 key: String,148 value: Bytes,149 ) -> Result<()> {150 let caller = T::CrossAccountId::from_eth(caller);151 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;152 let key = <Vec<u8>>::from(key)153 .try_into()154 .map_err(|_| "key too long")?;155 let value = value.0.try_into().map_err(|_| "value too long")?;156157 let nesting_budget = self158 .recorder159 .weight_calls_budget(<StructureWeight<T>>::find_parent());160161 <Pallet<T>>::set_token_property(162 self,163 &caller,164 TokenId(token_id),165 Property { key, value },166 &nesting_budget,167 )168 .map_err(dispatch_to_evm::<T>)169 }170171 172 173 174 175 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]176 fn set_properties(177 &mut self,178 caller: Caller,179 token_id: U256,180 properties: Vec<eth::Property>,181 ) -> Result<()> {182 let caller = T::CrossAccountId::from_eth(caller);183 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;184185 let nesting_budget = self186 .recorder187 .weight_calls_budget(<StructureWeight<T>>::find_parent());188189 let properties = properties190 .into_iter()191 .map(eth::Property::try_into)192 .collect::<Result<Vec<_>>>()?;193194 <Pallet<T>>::set_token_properties(195 self,196 &caller,197 TokenId(token_id),198 properties.into_iter(),199 pallet_common::SetPropertyMode::ExistingToken,200 &nesting_budget,201 )202 .map_err(dispatch_to_evm::<T>)203 }204205 206 207 208 209 #[solidity(hide)]210 #[weight(<SelfWeightOf<T>>::delete_token_properties(1))]211 fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {212 let caller = T::CrossAccountId::from_eth(caller);213 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;214 let key = <Vec<u8>>::from(key)215 .try_into()216 .map_err(|_| "key too long")?;217218 let nesting_budget = self219 .recorder220 .weight_calls_budget(<StructureWeight<T>>::find_parent());221222 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)223 .map_err(dispatch_to_evm::<T>)224 }225226 227 228 229 230 #[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]231 fn delete_properties(232 &mut self,233 token_id: U256,234 caller: Caller,235 keys: Vec<String>,236 ) -> Result<()> {237 let caller = T::CrossAccountId::from_eth(caller);238 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;239 let keys = keys240 .into_iter()241 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))242 .collect::<Result<Vec<_>>>()?;243244 let nesting_budget = self245 .recorder246 .weight_calls_budget(<StructureWeight<T>>::find_parent());247248 <Pallet<T>>::delete_token_properties(249 self,250 &caller,251 TokenId(token_id),252 keys.into_iter(),253 &nesting_budget,254 )255 .map_err(dispatch_to_evm::<T>)256 }257258 259 260 261 262 263 fn property(&self, token_id: U256, key: String) -> Result<Bytes> {264 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;265 let key = <Vec<u8>>::from(key)266 .try_into()267 .map_err(|_| "key too long")?;268269 let props = <TokenProperties<T>>::get((self.id, token_id));270 let prop = props.get(&key).ok_or("key not found")?;271272 Ok(prop.to_vec().into())273 }274}275276#[derive(ToLog)]277pub enum ERC721Events {278 279 280 281 Transfer {282 #[indexed]283 from: Address,284 #[indexed]285 to: Address,286 #[indexed]287 token_id: U256,288 },289 290 Approval {291 #[indexed]292 owner: Address,293 #[indexed]294 approved: Address,295 #[indexed]296 token_id: U256,297 },298 299 #[allow(dead_code)]300 ApprovalForAll {301 #[indexed]302 owner: Address,303 #[indexed]304 operator: Address,305 approved: bool,306 },307}308309310311#[solidity_interface(name = ERC721Metadata, enum(derive(PreDispatch)), expect_selector = 0x5b5e139f)]312impl<T: Config> RefungibleHandle<T>313where314 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,315{316 317 318 #[solidity(hide, rename_selector = "name")]319 fn name_proxy(&self) -> Result<String> {320 self.name()321 }322323 324 325 #[solidity(hide, rename_selector = "symbol")]326 fn symbol_proxy(&self) -> Result<String> {327 self.symbol()328 }329330 331 332 333 334 335 336 337 338 339 #[solidity(rename_selector = "tokenURI")]340 fn token_uri(&self, token_id: U256) -> Result<String> {341 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;342343 match get_token_property(self, token_id_u32, &key::url()).as_deref() {344 Err(_) | Ok("") => (),345 Ok(url) => {346 return Ok(url.into());347 }348 };349350 let base_uri =351 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())352 .map(BoundedVec::into_inner)353 .map(String::from_utf8)354 .transpose()355 .map_err(|e| {356 Error::Revert(alloc::format!(357 "Can not convert value \"baseURI\" to string with error \"{e}\""358 ))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}376377378379#[solidity_interface(name = ERC721Enumerable, enum(derive(PreDispatch)), expect_selector = 0x780e9d63)]380impl<T: Config> RefungibleHandle<T> {381 382 383 384 385 fn token_by_index(&self, index: U256) -> U256 {386 index387 }388389 390 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {391 392 Err("not implemented".into())393 }394395 396 397 398 fn total_supply(&self) -> Result<U256> {399 self.consume_store_reads(1)?;400 Ok(<Pallet<T>>::total_supply(self).into())401 }402}403404405406#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]407impl<T: Config> RefungibleHandle<T> {408 409 410 411 412 413 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 421 422 423 424 425 426 427 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 440 #[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 449 Err("not implemented".into())450 }451452 453 #[solidity(rename_selector = "safeTransferFrom")]454 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {455 456 Err("not implemented".into())457 }458459 460 461 462 463 464 465 466 467 468 469 #[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 495 fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {496 Err("not implemented".into())497 }498499 500 501 502 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 519 fn get_approved(&self, _token_id: U256) -> Result<Address> {520 521 Err("not implemented".into())522 }523524 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}533534535pub 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}544545546pub 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}565566567#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]568impl<T: Config> RefungibleHandle<T> {569 570 571 572 573 #[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}585586587#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]588impl<T: Config> RefungibleHandle<T> {589 590 591 592 #[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 603 604 605 606 607 #[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, 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 645 646 647 648 #[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 665 666 667 668 669 670 #[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, 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}757758759#[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 765 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 772 fn symbol(&self) -> Result<String> {773 Ok(String::from_utf8_lossy(&self.token_prefix).into())774 }775776 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 784 785 786 #[solidity(hide)]787 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {788 Self::owner_of_cross(self, token_id)789 }790791 792 793 794 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {795 Self::token_owner(self, token_id.try_into()?)796 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))797 .or_else(|err| match err {798 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),799 TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(800 ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,801 )),802 })803 }804805 806 807 808 fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {809 self.consume_store_reads(1)?;810 let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));811 Ok(balance.into())812 }813814 815 816 817 818 819 fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {820 let keys = keys821 .into_iter()822 .map(|key| {823 <Vec<u8>>::from(key)824 .try_into()825 .map_err(|_| Error::Revert("key too large".into()))826 })827 .collect::<Result<Vec<_>>>()?;828829 <Self as CommonCollectionOperations<T>>::token_properties(830 self,831 token_id.try_into()?,832 if keys.is_empty() { None } else { Some(keys) },833 )834 .into_iter()835 .map(eth::Property::try_from)836 .collect::<Result<Vec<_>>>()837 }838 839 840 841 842 843 844 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]845 fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {846 let caller = T::CrossAccountId::from_eth(caller);847 let to = T::CrossAccountId::from_eth(to);848 let token = token_id.try_into()?;849 let budget = self850 .recorder851 .weight_calls_budget(<StructureWeight<T>>::find_parent());852853 let balance = balance(self, token, &caller)?;854 ensure_single_owner(self, token, balance)?;855856 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)857 .map_err(dispatch_to_evm::<T>)?;858 Ok(())859 }860861 862 863 864 865 866 867 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]868 fn transfer_cross(869 &mut self,870 caller: Caller,871 to: eth::CrossAddress,872 token_id: U256,873 ) -> Result<()> {874 let caller = T::CrossAccountId::from_eth(caller);875 let to = to.into_sub_cross_account::<T>()?;876 let token = token_id.try_into()?;877 let budget = self878 .recorder879 .weight_calls_budget(<StructureWeight<T>>::find_parent());880881 let balance = balance(self, token, &caller)?;882 ensure_single_owner(self, token, balance)?;883884 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)885 .map_err(dispatch_to_evm::<T>)?;886 Ok(())887 }888889 890 891 892 893 894 895 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]896 fn transfer_from_cross(897 &mut self,898 caller: Caller,899 from: eth::CrossAddress,900 to: eth::CrossAddress,901 token_id: U256,902 ) -> Result<()> {903 let caller = T::CrossAccountId::from_eth(caller);904 let from = from.into_sub_cross_account::<T>()?;905 let to = to.into_sub_cross_account::<T>()?;906 let token_id = token_id.try_into()?;907 let budget = self908 .recorder909 .weight_calls_budget(<StructureWeight<T>>::find_parent());910911 let balance = balance(self, token_id, &from)?;912 ensure_single_owner(self, token_id, balance)?;913914 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)915 .map_err(dispatch_to_evm::<T>)?;916 Ok(())917 }918919 920 921 922 923 924 925 926 #[solidity(hide)]927 #[weight(<SelfWeightOf<T>>::burn_from())]928 fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {929 let caller = T::CrossAccountId::from_eth(caller);930 let from = T::CrossAccountId::from_eth(from);931 let token = token_id.try_into()?;932 let budget = self933 .recorder934 .weight_calls_budget(<StructureWeight<T>>::find_parent());935936 let balance = balance(self, token, &from)?;937 ensure_single_owner(self, token, balance)?;938939 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)940 .map_err(dispatch_to_evm::<T>)?;941 Ok(())942 }943944 945 946 947 948 949 950 951 #[weight(<SelfWeightOf<T>>::burn_from())]952 fn burn_from_cross(953 &mut self,954 caller: Caller,955 from: eth::CrossAddress,956 token_id: U256,957 ) -> Result<()> {958 let caller = T::CrossAccountId::from_eth(caller);959 let from = from.into_sub_cross_account::<T>()?;960 let token = token_id.try_into()?;961 let budget = self962 .recorder963 .weight_calls_budget(<StructureWeight<T>>::find_parent());964965 let balance = balance(self, token, &from)?;966 ensure_single_owner(self, token, balance)?;967968 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)969 .map_err(dispatch_to_evm::<T>)?;970 Ok(())971 }972973 974 fn next_token_id(&self) -> Result<U256> {975 self.consume_store_reads(1)?;976 Ok(<Pallet<T>>::next_token_id(self)977 .map_err(dispatch_to_evm::<T>)?978 .into())979 }980981 982 983 984 985 986 #[solidity(hide)]987 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]988 fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {989 let caller = T::CrossAccountId::from_eth(caller);990 let to = T::CrossAccountId::from_eth(to);991 let mut expected_index = <TokensMinted<T>>::get(self.id)992 .checked_add(1)993 .ok_or("item id overflow")?;994 let budget = self995 .recorder996 .weight_calls_budget(<StructureWeight<T>>::find_parent());997998 let total_tokens = token_ids.len();999 for id in token_ids.into_iter() {1000 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1001 if id != expected_index {1002 return Err("item id should be next".into());1003 }1004 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;1005 }1006 let users = [(to, 1)]1007 .into_iter()1008 .collect::<BTreeMap<_, _>>()1009 .try_into()1010 .unwrap();1011 let create_item_data = CreateItemData::<T> {1012 users,1013 properties: CollectionPropertiesVec::default(),1014 };1015 let data = (0..total_tokens)1016 .map(|_| create_item_data.clone())1017 .collect();10181019 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1020 .map_err(dispatch_to_evm::<T>)?;1021 Ok(true)1022 }10231024 1025 1026 1027 1028 1029 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1030 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]1031 fn mint_bulk_with_token_uri(1032 &mut self,1033 caller: Caller,1034 to: Address,1035 tokens: Vec<TokenUri>,1036 ) -> Result<bool> {1037 let key = key::url();1038 let caller = T::CrossAccountId::from_eth(caller);1039 let to = T::CrossAccountId::from_eth(to);1040 let mut expected_index = <TokensMinted<T>>::get(self.id)1041 .checked_add(1)1042 .ok_or("item id overflow")?;1043 let budget = self1044 .recorder1045 .weight_calls_budget(<StructureWeight<T>>::find_parent());10461047 let mut data = Vec::with_capacity(tokens.len());1048 let users: BoundedBTreeMap<_, _, _> = [(to, 1)]1049 .into_iter()1050 .collect::<BTreeMap<_, _>>()1051 .try_into()1052 .unwrap();1053 for TokenUri { id, uri } in tokens {1054 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1055 if id != expected_index {1056 return Err("item id should be next".into());1057 }1058 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10591060 let mut properties = CollectionPropertiesVec::default();1061 properties1062 .try_push(Property {1063 key: key.clone(),1064 value: uri1065 .into_bytes()1066 .try_into()1067 .map_err(|_| "token uri is too long")?,1068 })1069 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;10701071 let create_item_data = CreateItemData::<T> {1072 users: users.clone(),1073 properties,1074 };1075 data.push(create_item_data);1076 }10771078 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1079 .map_err(dispatch_to_evm::<T>)?;1080 Ok(true)1081 }10821083 1084 1085 1086 1087 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1088 fn mint_cross(1089 &mut self,1090 caller: Caller,1091 to: eth::CrossAddress,1092 properties: Vec<eth::Property>,1093 ) -> Result<U256> {1094 let token_id = <TokensMinted<T>>::get(self.id)1095 .checked_add(1)1096 .ok_or("item id overflow")?;10971098 let to = to.into_sub_cross_account::<T>()?;10991100 let properties = properties1101 .into_iter()1102 .map(eth::Property::try_into)1103 .collect::<Result<Vec<_>>>()?1104 .try_into()1105 .map_err(|_| Error::Revert("too many properties".to_string()))?;11061107 let caller = T::CrossAccountId::from_eth(caller);11081109 let budget = self1110 .recorder1111 .weight_calls_budget(<StructureWeight<T>>::find_parent());11121113 let users = [(to, 1)]1114 .into_iter()1115 .collect::<BTreeMap<_, _>>()1116 .try_into()1117 .unwrap();1118 <Pallet<T>>::create_item(1119 self,1120 &caller,1121 CreateItemData::<T> { users, properties },1122 &budget,1123 )1124 .map_err(dispatch_to_evm::<T>)?;11251126 Ok(token_id.into())1127 }11281129 1130 1131 1132 fn token_contract_address(&self, token: U256) -> Result<Address> {1133 Ok(T::EvmTokenAddressMapping::token_to_address(1134 self.id,1135 token.try_into().map_err(|_| "token id overflow")?,1136 ))1137 }11381139 1140 fn collection_helper_address(&self) -> Result<Address> {1141 Ok(T::ContractAddress::get())1142 }1143}11441145#[solidity_interface(1146 name = UniqueRefungible,1147 is(1148 ERC721,1149 ERC721Enumerable,1150 ERC721UniqueExtensions,1151 ERC721UniqueMintable,1152 ERC721Burnable,1153 ERC721Metadata(if(this.flags.erc721metadata)),1154 Collection(via(common_mut returns CollectionHandle<T>)),1155 TokenProperties,1156 ),1157 enum(derive(PreDispatch)),1158)]1159impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}116011611162generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1163generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);11641165impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1166where1167 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1168{1169 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1170 fn call(1171 self,1172 handle: &mut impl PrecompileHandle,1173 ) -> Option<pallet_common::erc::PrecompileResult> {1174 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1175 }1176}