12345678910111213141516171819202122extern crate alloc;2324use core::{25 char::{REPLACEMENT_CHARACTER, decode_utf16},26 convert::TryInto,27};28use evm_coder::{29 abi::AbiType, ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*,30 weight,31};32use frame_support::{BoundedBTreeMap, BoundedVec};33use pallet_common::{34 CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,35 Error as CommonError,36 erc::{CommonEvmHandler, CollectionCall, static_property::key},37 eth,38};39use pallet_evm::{account::CrossAccountId, PrecompileHandle};40use pallet_evm_coder_substrate::{call, dispatch_to_evm};41use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};42use sp_core::{H160, U256, Get};43use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};44use up_data_structs::{45 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,46 PropertyKeyPermission, PropertyPermission, TokenId, TokenOwnerError,47};4849use crate::{50 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,51 TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,52};5354pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);555657#[solidity_interface(name = TokenProperties)]58impl<T: Config> RefungibleHandle<T> {59 60 61 62 63 64 65 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]66 #[solidity(hide)]67 fn set_token_property_permission(68 &mut self,69 caller: Caller,70 key: String,71 is_mutable: bool,72 collection_admin: bool,73 token_owner: bool,74 ) -> Result<()> {75 let caller = T::CrossAccountId::from_eth(caller);76 <Pallet<T>>::set_token_property_permissions(77 self,78 &caller,79 vec![PropertyKeyPermission {80 key: <Vec<u8>>::from(key)81 .try_into()82 .map_err(|_| "too long key")?,83 permission: PropertyPermission {84 mutable: is_mutable,85 collection_admin,86 token_owner,87 },88 }],89 )90 .map_err(dispatch_to_evm::<T>)91 }9293 94 95 96 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]97 fn set_token_property_permissions(98 &mut self,99 caller: Caller,100 permissions: Vec<eth::TokenPropertyPermission>,101 ) -> Result<()> {102 let caller = T::CrossAccountId::from_eth(caller);103 let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;104105 <Pallet<T>>::set_token_property_permissions(self, &caller, perms)106 .map_err(dispatch_to_evm::<T>)107 }108109 110 fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {111 let perms = <Pallet<T>>::token_property_permission(self.id);112 Ok(perms113 .into_iter()114 .map(eth::TokenPropertyPermission::from)115 .collect())116 }117118 119 120 121 122 123 #[solidity(hide)]124 #[weight(<SelfWeightOf<T>>::set_token_properties(1))]125 fn set_property(126 &mut self,127 caller: Caller,128 token_id: U256,129 key: String,130 value: Bytes,131 ) -> Result<()> {132 let caller = T::CrossAccountId::from_eth(caller);133 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;134 let key = <Vec<u8>>::from(key)135 .try_into()136 .map_err(|_| "key too long")?;137 let value = value.0.try_into().map_err(|_| "value too long")?;138139 let nesting_budget = self140 .recorder141 .weight_calls_budget(<StructureWeight<T>>::find_parent());142143 <Pallet<T>>::set_token_property(144 self,145 &caller,146 TokenId(token_id),147 Property { key, value },148 &nesting_budget,149 )150 .map_err(dispatch_to_evm::<T>)151 }152153 154 155 156 157 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]158 fn set_properties(159 &mut self,160 caller: Caller,161 token_id: U256,162 properties: Vec<eth::Property>,163 ) -> Result<()> {164 let caller = T::CrossAccountId::from_eth(caller);165 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;166167 let nesting_budget = self168 .recorder169 .weight_calls_budget(<StructureWeight<T>>::find_parent());170171 let properties = properties172 .into_iter()173 .map(eth::Property::try_into)174 .collect::<Result<Vec<_>>>()?;175176 <Pallet<T>>::set_token_properties(177 self,178 &caller,179 TokenId(token_id),180 properties.into_iter(),181 false,182 &nesting_budget,183 )184 .map_err(dispatch_to_evm::<T>)185 }186187 188 189 190 191 #[solidity(hide)]192 #[weight(<SelfWeightOf<T>>::delete_token_properties(1))]193 fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {194 let caller = T::CrossAccountId::from_eth(caller);195 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;196 let key = <Vec<u8>>::from(key)197 .try_into()198 .map_err(|_| "key too long")?;199200 let nesting_budget = self201 .recorder202 .weight_calls_budget(<StructureWeight<T>>::find_parent());203204 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)205 .map_err(dispatch_to_evm::<T>)206 }207208 209 210 211 212 #[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]213 fn delete_properties(214 &mut self,215 token_id: U256,216 caller: Caller,217 keys: Vec<String>,218 ) -> Result<()> {219 let caller = T::CrossAccountId::from_eth(caller);220 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;221 let keys = keys222 .into_iter()223 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))224 .collect::<Result<Vec<_>>>()?;225226 let nesting_budget = self227 .recorder228 .weight_calls_budget(<StructureWeight<T>>::find_parent());229230 <Pallet<T>>::delete_token_properties(231 self,232 &caller,233 TokenId(token_id),234 keys.into_iter(),235 &nesting_budget,236 )237 .map_err(dispatch_to_evm::<T>)238 }239240 241 242 243 244 245 fn property(&self, token_id: U256, key: String) -> Result<Bytes> {246 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;247 let key = <Vec<u8>>::from(key)248 .try_into()249 .map_err(|_| "key too long")?;250251 let props = <TokenProperties<T>>::get((self.id, token_id));252 let prop = props.get(&key).ok_or("key not found")?;253254 Ok(prop.to_vec().into())255 }256}257258#[derive(ToLog)]259pub enum ERC721Events {260 261 262 263 Transfer {264 #[indexed]265 from: Address,266 #[indexed]267 to: Address,268 #[indexed]269 token_id: U256,270 },271 272 Approval {273 #[indexed]274 owner: Address,275 #[indexed]276 approved: Address,277 #[indexed]278 token_id: U256,279 },280 281 #[allow(dead_code)]282 ApprovalForAll {283 #[indexed]284 owner: Address,285 #[indexed]286 operator: Address,287 approved: bool,288 },289}290291292293#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]294impl<T: Config> RefungibleHandle<T>295where296 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,297{298 299 300 #[solidity(hide, rename_selector = "name")]301 fn name_proxy(&self) -> Result<String> {302 self.name()303 }304305 306 307 #[solidity(hide, rename_selector = "symbol")]308 fn symbol_proxy(&self) -> Result<String> {309 self.symbol()310 }311312 313 314 315 316 317 318 319 320 321 #[solidity(rename_selector = "tokenURI")]322 fn token_uri(&self, token_id: U256) -> Result<String> {323 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;324325 match get_token_property(self, token_id_u32, &key::url()).as_deref() {326 Err(_) | Ok("") => (),327 Ok(url) => {328 return Ok(url.into());329 }330 };331332 let base_uri =333 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())334 .map(BoundedVec::into_inner)335 .map(String::from_utf8)336 .transpose()337 .map_err(|e| {338 Error::Revert(alloc::format!(339 "Can not convert value \"baseURI\" to string with error \"{}\"",340 e341 ))342 })?;343344 let base_uri = match base_uri.as_deref() {345 None | Some("") => {346 return Ok("".into());347 }348 Some(base_uri) => base_uri.into(),349 };350351 Ok(352 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {353 Err(_) | Ok("") => base_uri,354 Ok(suffix) => base_uri + suffix,355 },356 )357 }358}359360361362#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]363impl<T: Config> RefungibleHandle<T> {364 365 366 367 368 fn token_by_index(&self, index: U256) -> Result<U256> {369 Ok(index)370 }371372 373 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {374 375 Err("not implemented".into())376 }377378 379 380 381 fn total_supply(&self) -> Result<U256> {382 self.consume_store_reads(1)?;383 Ok(<Pallet<T>>::total_supply(self).into())384 }385}386387388389#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]390impl<T: Config> RefungibleHandle<T> {391 392 393 394 395 396 fn balance_of(&self, owner: Address) -> Result<U256> {397 self.consume_store_reads(1)?;398 let owner = T::CrossAccountId::from_eth(owner);399 let balance = <AccountBalance<T>>::get((self.id, owner));400 Ok(balance.into())401 }402403 404 405 406 407 408 409 410 fn owner_of(&self, token_id: U256) -> Result<Address> {411 self.consume_store_reads(2)?;412 let token = token_id.try_into()?;413 let owner = <Pallet<T>>::token_owner(self.id, token);414 owner415 .map(|address| *address.as_eth())416 .or_else(|err| match err {417 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),418 TokenOwnerError::MultipleOwners => Ok(ADDRESS_FOR_PARTIALLY_OWNED_TOKENS),419 })420 }421422 423 #[solidity(rename_selector = "safeTransferFrom")]424 fn safe_transfer_from_with_data(425 &mut self,426 _from: Address,427 _to: Address,428 _token_id: U256,429 _data: Bytes,430 ) -> Result<()> {431 432 Err("not implemented".into())433 }434435 436 #[solidity(rename_selector = "safeTransferFrom")]437 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {438 439 Err("not implemented".into())440 }441442 443 444 445 446 447 448 449 450 451 452 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]453 fn transfer_from(454 &mut self,455 caller: Caller,456 from: Address,457 to: Address,458 token_id: U256,459 ) -> Result<()> {460 let caller = T::CrossAccountId::from_eth(caller);461 let from = T::CrossAccountId::from_eth(from);462 let to = T::CrossAccountId::from_eth(to);463 let token = token_id.try_into()?;464 let budget = self465 .recorder466 .weight_calls_budget(<StructureWeight<T>>::find_parent());467468 let balance = balance(&self, token, &from)?;469 ensure_single_owner(&self, token, balance)?;470471 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)472 .map_err(dispatch_to_evm::<T>)?;473474 Ok(())475 }476477 478 fn approve(&mut self, _caller: Caller, _approved: Address, _token_id: U256) -> Result<()> {479 Err("not implemented".into())480 }481482 483 484 485 486 #[weight(<SelfWeightOf<T>>::set_allowance_for_all())]487 fn set_approval_for_all(488 &mut self,489 caller: Caller,490 operator: Address,491 approved: bool,492 ) -> Result<()> {493 let caller = T::CrossAccountId::from_eth(caller);494 let operator = T::CrossAccountId::from_eth(operator);495496 <Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)497 .map_err(dispatch_to_evm::<T>)?;498 Ok(())499 }500501 502 fn get_approved(&self, _token_id: U256) -> Result<Address> {503 504 Err("not implemented".into())505 }506507 508 #[weight(<SelfWeightOf<T>>::allowance_for_all())]509 fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {510 let owner = T::CrossAccountId::from_eth(owner);511 let operator = T::CrossAccountId::from_eth(operator);512513 Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))514 }515}516517518pub fn balance<T: Config>(519 collection: &RefungibleHandle<T>,520 token: TokenId,521 owner: &T::CrossAccountId,522) -> Result<u128> {523 collection.consume_store_reads(1)?;524 let balance = <Balance<T>>::get((collection.id, token, &owner));525 Ok(balance)526}527528529pub fn ensure_single_owner<T: Config>(530 collection: &RefungibleHandle<T>,531 token: TokenId,532 owner_balance: u128,533) -> Result<()> {534 collection.consume_store_reads(1)?;535 let total_supply = <TotalSupply<T>>::get((collection.id, token));536537 if owner_balance == 0 {538 return Err(dispatch_to_evm::<T>(539 <CommonError<T>>::MustBeTokenOwner.into(),540 ));541 }542543 if total_supply != owner_balance {544 return Err("token has multiple owners".into());545 }546 Ok(())547}548549550#[solidity_interface(name = ERC721Burnable)]551impl<T: Config> RefungibleHandle<T> {552 553 554 555 556 #[weight(<SelfWeightOf<T>>::burn_item_fully())]557 fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {558 let caller = T::CrossAccountId::from_eth(caller);559 let token = token_id.try_into()?;560561 let balance = balance(&self, token, &caller)?;562 ensure_single_owner(&self, token, balance)?;563564 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;565 Ok(())566 }567}568569570#[solidity_interface(name = ERC721UniqueMintable)]571impl<T: Config> RefungibleHandle<T> {572 573 574 575 #[weight(<SelfWeightOf<T>>::create_item())]576 fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {577 let token_id: U256 = <TokensMinted<T>>::get(self.id)578 .checked_add(1)579 .ok_or("item id overflow")?580 .into();581 self.mint_check_id(caller, to, token_id)?;582 Ok(token_id)583 }584585 586 587 588 589 590 #[solidity(hide, rename_selector = "mint")]591 #[weight(<SelfWeightOf<T>>::create_item())]592 fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {593 let caller = T::CrossAccountId::from_eth(caller);594 let to = T::CrossAccountId::from_eth(to);595 let token_id: u32 = token_id.try_into()?;596 let budget = self597 .recorder598 .weight_calls_budget(<StructureWeight<T>>::find_parent());599600 if <TokensMinted<T>>::get(self.id)601 .checked_add(1)602 .ok_or("item id overflow")?603 != token_id604 {605 return Err("item id should be next".into());606 }607608 let users = [(to.clone(), 1)]609 .into_iter()610 .collect::<BTreeMap<_, _>>()611 .try_into()612 .unwrap();613 <Pallet<T>>::create_item(614 self,615 &caller,616 CreateItemData::<T> {617 users,618 properties: CollectionPropertiesVec::default(),619 },620 &budget,621 )622 .map_err(dispatch_to_evm::<T>)?;623624 Ok(true)625 }626627 628 629 630 631 #[solidity(rename_selector = "mintWithTokenURI")]632 #[weight(<SelfWeightOf<T>>::create_item())]633 fn mint_with_token_uri(634 &mut self,635 caller: Caller,636 to: Address,637 token_uri: String,638 ) -> Result<U256> {639 let token_id: U256 = <TokensMinted<T>>::get(self.id)640 .checked_add(1)641 .ok_or("item id overflow")?642 .into();643 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;644 Ok(token_id)645 }646647 648 649 650 651 652 653 #[solidity(hide, rename_selector = "mintWithTokenURI")]654 #[weight(<SelfWeightOf<T>>::create_item())]655 fn mint_with_token_uri_check_id(656 &mut self,657 caller: Caller,658 to: Address,659 token_id: U256,660 token_uri: String,661 ) -> Result<bool> {662 let key = key::url();663 let permission = get_token_permission::<T>(self.id, &key)?;664 if !permission.collection_admin {665 return Err("Operation is not allowed".into());666 }667668 let caller = T::CrossAccountId::from_eth(caller);669 let to = T::CrossAccountId::from_eth(to);670 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;671 let budget = self672 .recorder673 .weight_calls_budget(<StructureWeight<T>>::find_parent());674675 if <TokensMinted<T>>::get(self.id)676 .checked_add(1)677 .ok_or("item id overflow")?678 != token_id679 {680 return Err("item id should be next".into());681 }682683 let mut properties = CollectionPropertiesVec::default();684 properties685 .try_push(Property {686 key,687 value: token_uri688 .into_bytes()689 .try_into()690 .map_err(|_| "token uri is too long")?,691 })692 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;693694 let users = [(to.clone(), 1)]695 .into_iter()696 .collect::<BTreeMap<_, _>>()697 .try_into()698 .unwrap();699 <Pallet<T>>::create_item(700 self,701 &caller,702 CreateItemData::<T> { users, properties },703 &budget,704 )705 .map_err(dispatch_to_evm::<T>)?;706 Ok(true)707 }708}709710fn get_token_property<T: Config>(711 collection: &CollectionHandle<T>,712 token_id: u32,713 key: &up_data_structs::PropertyKey,714) -> Result<String> {715 collection.consume_store_reads(1)?;716 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))717 .map_err(|_| Error::Revert("Token properties not found".into()))?;718 if let Some(property) = properties.get(key) {719 return Ok(String::from_utf8_lossy(property).into());720 }721722 Err("Property tokenURI not found".into())723}724725fn get_token_permission<T: Config>(726 collection_id: CollectionId,727 key: &PropertyKey,728) -> Result<PropertyPermission> {729 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)730 .map_err(|_| Error::Revert("No permissions for collection".into()))?;731 let a = token_property_permissions732 .get(key)733 .map(Clone::clone)734 .ok_or_else(|| {735 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();736 Error::Revert(alloc::format!("No permission for key {}", key))737 })?;738 Ok(a)739}740741742#[solidity_interface(name = ERC721UniqueExtensions)]743impl<T: Config> RefungibleHandle<T>744where745 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,746{747 748 fn name(&self) -> Result<String> {749 Ok(decode_utf16(self.name.iter().copied())750 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))751 .collect::<String>())752 }753754 755 fn symbol(&self) -> Result<String> {756 Ok(String::from_utf8_lossy(&self.token_prefix).into())757 }758759 760 fn description(&self) -> Result<String> {761 Ok(decode_utf16(self.description.iter().copied())762 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))763 .collect::<String>())764 }765766 767 768 769 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {770 Self::token_owner(&self, token_id.try_into()?)771 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))772 .or_else(|err| match err {773 TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),774 TokenOwnerError::MultipleOwners => Ok(eth::CrossAddress::from_eth(775 ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,776 )),777 })778 }779780 781 782 783 784 785 fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {786 let keys = keys787 .into_iter()788 .map(|key| {789 <Vec<u8>>::from(key)790 .try_into()791 .map_err(|_| Error::Revert("key too large".into()))792 })793 .collect::<Result<Vec<_>>>()?;794795 <Self as CommonCollectionOperations<T>>::token_properties(796 &self,797 token_id.try_into()?,798 if keys.is_empty() { None } else { Some(keys) },799 )800 .into_iter()801 .map(eth::Property::try_from)802 .collect::<Result<Vec<_>>>()803 }804 805 806 807 808 809 810 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]811 fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {812 let caller = T::CrossAccountId::from_eth(caller);813 let to = T::CrossAccountId::from_eth(to);814 let token = token_id.try_into()?;815 let budget = self816 .recorder817 .weight_calls_budget(<StructureWeight<T>>::find_parent());818819 let balance = balance(self, token, &caller)?;820 ensure_single_owner(self, token, balance)?;821822 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)823 .map_err(dispatch_to_evm::<T>)?;824 Ok(())825 }826827 828 829 830 831 832 833 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]834 fn transfer_cross(835 &mut self,836 caller: Caller,837 to: eth::CrossAddress,838 token_id: U256,839 ) -> Result<()> {840 let caller = T::CrossAccountId::from_eth(caller);841 let to = to.into_sub_cross_account::<T>()?;842 let token = token_id.try_into()?;843 let budget = self844 .recorder845 .weight_calls_budget(<StructureWeight<T>>::find_parent());846847 let balance = balance(self, token, &caller)?;848 ensure_single_owner(self, token, balance)?;849850 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)851 .map_err(dispatch_to_evm::<T>)?;852 Ok(())853 }854855 856 857 858 859 860 861 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]862 fn transfer_from_cross(863 &mut self,864 caller: Caller,865 from: eth::CrossAddress,866 to: eth::CrossAddress,867 token_id: U256,868 ) -> Result<()> {869 let caller = T::CrossAccountId::from_eth(caller);870 let from = from.into_sub_cross_account::<T>()?;871 let to = to.into_sub_cross_account::<T>()?;872 let token_id = token_id.try_into()?;873 let budget = self874 .recorder875 .weight_calls_budget(<StructureWeight<T>>::find_parent());876877 let balance = balance(self, token_id, &from)?;878 ensure_single_owner(self, token_id, balance)?;879880 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)881 .map_err(dispatch_to_evm::<T>)?;882 Ok(())883 }884885 886 887 888 889 890 891 892 #[solidity(hide)]893 #[weight(<SelfWeightOf<T>>::burn_from())]894 fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {895 let caller = T::CrossAccountId::from_eth(caller);896 let from = T::CrossAccountId::from_eth(from);897 let token = token_id.try_into()?;898 let budget = self899 .recorder900 .weight_calls_budget(<StructureWeight<T>>::find_parent());901902 let balance = balance(self, token, &from)?;903 ensure_single_owner(self, token, balance)?;904905 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)906 .map_err(dispatch_to_evm::<T>)?;907 Ok(())908 }909910 911 912 913 914 915 916 917 #[weight(<SelfWeightOf<T>>::burn_from())]918 fn burn_from_cross(919 &mut self,920 caller: Caller,921 from: eth::CrossAddress,922 token_id: U256,923 ) -> Result<()> {924 let caller = T::CrossAccountId::from_eth(caller);925 let from = from.into_sub_cross_account::<T>()?;926 let token = token_id.try_into()?;927 let budget = self928 .recorder929 .weight_calls_budget(<StructureWeight<T>>::find_parent());930931 let balance = balance(self, token, &from)?;932 ensure_single_owner(self, token, balance)?;933934 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)935 .map_err(dispatch_to_evm::<T>)?;936 Ok(())937 }938939 940 fn next_token_id(&self) -> Result<U256> {941 self.consume_store_reads(1)?;942 Ok(<TokensMinted<T>>::get(self.id)943 .checked_add(1)944 .ok_or("item id overflow")?945 .into())946 }947948 949 950 951 952 953 #[solidity(hide)]954 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]955 fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {956 let caller = T::CrossAccountId::from_eth(caller);957 let to = T::CrossAccountId::from_eth(to);958 let mut expected_index = <TokensMinted<T>>::get(self.id)959 .checked_add(1)960 .ok_or("item id overflow")?;961 let budget = self962 .recorder963 .weight_calls_budget(<StructureWeight<T>>::find_parent());964965 let total_tokens = token_ids.len();966 for id in token_ids.into_iter() {967 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;968 if id != expected_index {969 return Err("item id should be next".into());970 }971 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;972 }973 let users = [(to.clone(), 1)]974 .into_iter()975 .collect::<BTreeMap<_, _>>()976 .try_into()977 .unwrap();978 let create_item_data = CreateItemData::<T> {979 users,980 properties: CollectionPropertiesVec::default(),981 };982 let data = (0..total_tokens)983 .map(|_| create_item_data.clone())984 .collect();985986 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)987 .map_err(dispatch_to_evm::<T>)?;988 Ok(true)989 }990991 992 993 994 995 996 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]997 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]998 fn mint_bulk_with_token_uri(999 &mut self,1000 caller: Caller,1001 to: Address,1002 tokens: Vec<(U256, String)>,1003 ) -> Result<bool> {1004 let key = key::url();1005 let caller = T::CrossAccountId::from_eth(caller);1006 let to = T::CrossAccountId::from_eth(to);1007 let mut expected_index = <TokensMinted<T>>::get(self.id)1008 .checked_add(1)1009 .ok_or("item id overflow")?;1010 let budget = self1011 .recorder1012 .weight_calls_budget(<StructureWeight<T>>::find_parent());10131014 let mut data = Vec::with_capacity(tokens.len());1015 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]1016 .into_iter()1017 .collect::<BTreeMap<_, _>>()1018 .try_into()1019 .unwrap();1020 for (id, token_uri) in tokens {1021 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1022 if id != expected_index {1023 return Err("item id should be next".into());1024 }1025 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10261027 let mut properties = CollectionPropertiesVec::default();1028 properties1029 .try_push(Property {1030 key: key.clone(),1031 value: token_uri1032 .into_bytes()1033 .try_into()1034 .map_err(|_| "token uri is too long")?,1035 })1036 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;10371038 let create_item_data = CreateItemData::<T> {1039 users: users.clone(),1040 properties,1041 };1042 data.push(create_item_data);1043 }10441045 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1046 .map_err(dispatch_to_evm::<T>)?;1047 Ok(true)1048 }10491050 1051 1052 1053 1054 #[weight(<SelfWeightOf<T>>::create_item())]1055 fn mint_cross(1056 &mut self,1057 caller: Caller,1058 to: eth::CrossAddress,1059 properties: Vec<eth::Property>,1060 ) -> Result<U256> {1061 let token_id = <TokensMinted<T>>::get(self.id)1062 .checked_add(1)1063 .ok_or("item id overflow")?;10641065 let to = to.into_sub_cross_account::<T>()?;10661067 let properties = properties1068 .into_iter()1069 .map(eth::Property::try_into)1070 .collect::<Result<Vec<_>>>()?1071 .try_into()1072 .map_err(|_| Error::Revert(alloc::format!("too many properties")))?;10731074 let caller = T::CrossAccountId::from_eth(caller);10751076 let budget = self1077 .recorder1078 .weight_calls_budget(<StructureWeight<T>>::find_parent());10791080 let users = [(to, 1)]1081 .into_iter()1082 .collect::<BTreeMap<_, _>>()1083 .try_into()1084 .unwrap();1085 <Pallet<T>>::create_item(1086 self,1087 &caller,1088 CreateItemData::<T> { users, properties },1089 &budget,1090 )1091 .map_err(dispatch_to_evm::<T>)?;10921093 Ok(token_id.into())1094 }10951096 1097 1098 1099 fn token_contract_address(&self, token: U256) -> Result<Address> {1100 Ok(T::EvmTokenAddressMapping::token_to_address(1101 self.id,1102 token.try_into().map_err(|_| "token id overflow")?,1103 ))1104 }11051106 1107 fn collection_helper_address(&self) -> Result<Address> {1108 Ok(T::ContractAddress::get())1109 }1110}11111112#[solidity_interface(1113 name = UniqueRefungible,1114 is(1115 ERC721,1116 ERC721Enumerable,1117 ERC721UniqueExtensions,1118 ERC721UniqueMintable,1119 ERC721Burnable,1120 ERC721Metadata(if(this.flags.erc721metadata)),1121 Collection(via(common_mut returns CollectionHandle<T>)),1122 TokenProperties,1123 )1124)]1125impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}112611271128generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1129generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);11301131impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1132where1133 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1134{1135 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1136 fn call(1137 self,1138 handle: &mut impl PrecompileHandle,1139 ) -> Option<pallet_common::erc::PrecompileResult> {1140 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1141 }1142}