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, 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,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: uint256,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: uint256,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: uint256, 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: uint256,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: uint256, 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: uint256,270 },271 272 Approval {273 #[indexed]274 owner: address,275 #[indexed]276 approved: address,277 #[indexed]278 token_id: uint256,279 },280 281 #[allow(dead_code)]282 ApprovalForAll {283 #[indexed]284 owner: address,285 #[indexed]286 operator: address,287 approved: bool,288 },289}290291#[derive(ToLog)]292pub enum ERC721UniqueMintableEvents {293 294 #[allow(dead_code)]295 MintingFinished {},296}297298299300#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]301impl<T: Config> RefungibleHandle<T>302where303 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,304{305 306 307 #[solidity(hide, rename_selector = "name")]308 fn name_proxy(&self) -> Result<string> {309 self.name()310 }311312 313 314 #[solidity(hide, rename_selector = "symbol")]315 fn symbol_proxy(&self) -> Result<string> {316 self.symbol()317 }318319 320 321 322 323 324 325 326 327 328 #[solidity(rename_selector = "tokenURI")]329 fn token_uri(&self, token_id: uint256) -> Result<string> {330 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;331332 match get_token_property(self, token_id_u32, &key::url()).as_deref() {333 Err(_) | Ok("") => (),334 Ok(url) => {335 return Ok(url.into());336 }337 };338339 let base_uri =340 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())341 .map(BoundedVec::into_inner)342 .map(string::from_utf8)343 .transpose()344 .map_err(|e| {345 Error::Revert(alloc::format!(346 "Can not convert value \"baseURI\" to string with error \"{}\"",347 e348 ))349 })?;350351 let base_uri = match base_uri.as_deref() {352 None | Some("") => {353 return Ok("".into());354 }355 Some(base_uri) => base_uri.into(),356 };357358 Ok(359 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {360 Err(_) | Ok("") => base_uri,361 Ok(suffix) => base_uri + suffix,362 },363 )364 }365}366367368369#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]370impl<T: Config> RefungibleHandle<T> {371 372 373 374 375 fn token_by_index(&self, index: uint256) -> Result<uint256> {376 Ok(index)377 }378379 380 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {381 382 Err("not implemented".into())383 }384385 386 387 388 fn total_supply(&self) -> Result<uint256> {389 self.consume_store_reads(1)?;390 Ok(<Pallet<T>>::total_supply(self).into())391 }392}393394395396#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]397impl<T: Config> RefungibleHandle<T> {398 399 400 401 402 403 fn balance_of(&self, owner: address) -> Result<uint256> {404 self.consume_store_reads(1)?;405 let owner = T::CrossAccountId::from_eth(owner);406 let balance = <AccountBalance<T>>::get((self.id, owner));407 Ok(balance.into())408 }409410 411 412 413 414 415 416 417 fn owner_of(&self, token_id: uint256) -> Result<address> {418 self.consume_store_reads(2)?;419 let token = token_id.try_into()?;420 let owner = <Pallet<T>>::token_owner(self.id, token);421 Ok(owner422 .map(|address| *address.as_eth())423 .unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))424 }425426 427 #[solidity(rename_selector = "safeTransferFrom")]428 fn safe_transfer_from_with_data(429 &mut self,430 _from: address,431 _to: address,432 _token_id: uint256,433 _data: bytes,434 ) -> Result<void> {435 436 Err("not implemented".into())437 }438439 440 #[solidity(rename_selector = "safeTransferFrom")]441 fn safe_transfer_from(442 &mut self,443 _from: address,444 _to: address,445 _token_id: uint256,446 ) -> Result<void> {447 448 Err("not implemented".into())449 }450451 452 453 454 455 456 457 458 459 460 461 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]462 fn transfer_from(463 &mut self,464 caller: caller,465 from: address,466 to: address,467 token_id: uint256,468 ) -> Result<void> {469 let caller = T::CrossAccountId::from_eth(caller);470 let from = T::CrossAccountId::from_eth(from);471 let to = T::CrossAccountId::from_eth(to);472 let token = token_id.try_into()?;473 let budget = self474 .recorder475 .weight_calls_budget(<StructureWeight<T>>::find_parent());476477 let balance = balance(&self, token, &from)?;478 ensure_single_owner(&self, token, balance)?;479480 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)481 .map_err(dispatch_to_evm::<T>)?;482483 Ok(())484 }485486 487 fn approve(&mut self, _caller: caller, _approved: address, _token_id: uint256) -> Result<void> {488 Err("not implemented".into())489 }490491 492 493 494 495 #[weight(<SelfWeightOf<T>>::set_allowance_for_all())]496 fn set_approval_for_all(497 &mut self,498 caller: caller,499 operator: address,500 approved: bool,501 ) -> Result<void> {502 let caller = T::CrossAccountId::from_eth(caller);503 let operator = T::CrossAccountId::from_eth(operator);504505 <Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)506 .map_err(dispatch_to_evm::<T>)?;507 Ok(())508 }509510 511 fn get_approved(&self, _token_id: uint256) -> Result<address> {512 513 Err("not implemented".into())514 }515516 517 #[weight(<SelfWeightOf<T>>::allowance_for_all())]518 fn is_approved_for_all(&self, owner: address, operator: address) -> Result<bool> {519 let owner = T::CrossAccountId::from_eth(owner);520 let operator = T::CrossAccountId::from_eth(operator);521522 Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))523 }524}525526527pub fn balance<T: Config>(528 collection: &RefungibleHandle<T>,529 token: TokenId,530 owner: &T::CrossAccountId,531) -> Result<u128> {532 collection.consume_store_reads(1)?;533 let balance = <Balance<T>>::get((collection.id, token, &owner));534 Ok(balance)535}536537538pub fn ensure_single_owner<T: Config>(539 collection: &RefungibleHandle<T>,540 token: TokenId,541 owner_balance: u128,542) -> Result<()> {543 collection.consume_store_reads(1)?;544 let total_supply = <TotalSupply<T>>::get((collection.id, token));545546 if owner_balance == 0 {547 return Err(dispatch_to_evm::<T>(548 <CommonError<T>>::MustBeTokenOwner.into(),549 ));550 }551552 if total_supply != owner_balance {553 return Err("token has multiple owners".into());554 }555 Ok(())556}557558559#[solidity_interface(name = ERC721Burnable)]560impl<T: Config> RefungibleHandle<T> {561 562 563 564 565 #[weight(<SelfWeightOf<T>>::burn_item_fully())]566 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {567 let caller = T::CrossAccountId::from_eth(caller);568 let token = token_id.try_into()?;569570 let balance = balance(&self, token, &caller)?;571 ensure_single_owner(&self, token, balance)?;572573 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;574 Ok(())575 }576}577578579#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]580impl<T: Config> RefungibleHandle<T> {581 fn minting_finished(&self) -> Result<bool> {582 Ok(false)583 }584585 586 587 588 #[weight(<SelfWeightOf<T>>::create_item())]589 fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {590 let token_id: uint256 = <TokensMinted<T>>::get(self.id)591 .checked_add(1)592 .ok_or("item id overflow")?593 .into();594 self.mint_check_id(caller, to, token_id)?;595 Ok(token_id)596 }597598 599 600 601 602 603 #[solidity(hide, rename_selector = "mint")]604 #[weight(<SelfWeightOf<T>>::create_item())]605 fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {606 let caller = T::CrossAccountId::from_eth(caller);607 let to = T::CrossAccountId::from_eth(to);608 let token_id: u32 = token_id.try_into()?;609 let budget = self610 .recorder611 .weight_calls_budget(<StructureWeight<T>>::find_parent());612613 if <TokensMinted<T>>::get(self.id)614 .checked_add(1)615 .ok_or("item id overflow")?616 != token_id617 {618 return Err("item id should be next".into());619 }620621 let users = [(to.clone(), 1)]622 .into_iter()623 .collect::<BTreeMap<_, _>>()624 .try_into()625 .unwrap();626 <Pallet<T>>::create_item(627 self,628 &caller,629 CreateItemData::<T> {630 users,631 properties: CollectionPropertiesVec::default(),632 },633 &budget,634 )635 .map_err(dispatch_to_evm::<T>)?;636637 Ok(true)638 }639640 641 642 643 644 #[solidity(rename_selector = "mintWithTokenURI")]645 #[weight(<SelfWeightOf<T>>::create_item())]646 fn mint_with_token_uri(647 &mut self,648 caller: caller,649 to: address,650 token_uri: string,651 ) -> Result<uint256> {652 let token_id: uint256 = <TokensMinted<T>>::get(self.id)653 .checked_add(1)654 .ok_or("item id overflow")?655 .into();656 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;657 Ok(token_id)658 }659660 661 662 663 664 665 666 #[solidity(hide, rename_selector = "mintWithTokenURI")]667 #[weight(<SelfWeightOf<T>>::create_item())]668 fn mint_with_token_uri_check_id(669 &mut self,670 caller: caller,671 to: address,672 token_id: uint256,673 token_uri: string,674 ) -> Result<bool> {675 let key = key::url();676 let permission = get_token_permission::<T>(self.id, &key)?;677 if !permission.collection_admin {678 return Err("Operation is not allowed".into());679 }680681 let caller = T::CrossAccountId::from_eth(caller);682 let to = T::CrossAccountId::from_eth(to);683 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;684 let budget = self685 .recorder686 .weight_calls_budget(<StructureWeight<T>>::find_parent());687688 if <TokensMinted<T>>::get(self.id)689 .checked_add(1)690 .ok_or("item id overflow")?691 != token_id692 {693 return Err("item id should be next".into());694 }695696 let mut properties = CollectionPropertiesVec::default();697 properties698 .try_push(Property {699 key,700 value: token_uri701 .into_bytes()702 .try_into()703 .map_err(|_| "token uri is too long")?,704 })705 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;706707 let users = [(to.clone(), 1)]708 .into_iter()709 .collect::<BTreeMap<_, _>>()710 .try_into()711 .unwrap();712 <Pallet<T>>::create_item(713 self,714 &caller,715 CreateItemData::<T> { users, properties },716 &budget,717 )718 .map_err(dispatch_to_evm::<T>)?;719 Ok(true)720 }721722 723 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {724 Err("not implementable".into())725 }726}727728fn get_token_property<T: Config>(729 collection: &CollectionHandle<T>,730 token_id: u32,731 key: &up_data_structs::PropertyKey,732) -> Result<string> {733 collection.consume_store_reads(1)?;734 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))735 .map_err(|_| Error::Revert("Token properties not found".into()))?;736 if let Some(property) = properties.get(key) {737 return Ok(string::from_utf8_lossy(property).into());738 }739740 Err("Property tokenURI not found".into())741}742743fn get_token_permission<T: Config>(744 collection_id: CollectionId,745 key: &PropertyKey,746) -> Result<PropertyPermission> {747 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)748 .map_err(|_| Error::Revert("No permissions for collection".into()))?;749 let a = token_property_permissions750 .get(key)751 .map(Clone::clone)752 .ok_or_else(|| {753 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();754 Error::Revert(alloc::format!("No permission for key {}", key))755 })?;756 Ok(a)757}758759760#[solidity_interface(name = ERC721UniqueExtensions)]761impl<T: Config> RefungibleHandle<T>762where763 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,764{765 766 fn name(&self) -> Result<string> {767 Ok(decode_utf16(self.name.iter().copied())768 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))769 .collect::<string>())770 }771772 773 fn symbol(&self) -> Result<string> {774 Ok(string::from_utf8_lossy(&self.token_prefix).into())775 }776777 778 fn description(&self) -> Result<string> {779 Ok(decode_utf16(self.description.iter().copied())780 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))781 .collect::<string>())782 }783784 785 786 787 fn cross_owner_of(&self, token_id: uint256) -> Result<eth::CrossAddress> {788 Self::token_owner(&self, token_id.try_into()?)789 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))790 .ok_or(Error::Revert("key too large".into()))791 }792793 794 795 796 797 798 fn properties(&self, token_id: uint256, keys: Vec<string>) -> Result<Vec<eth::Property>> {799 let keys = keys800 .into_iter()801 .map(|key| {802 <Vec<u8>>::from(key)803 .try_into()804 .map_err(|_| Error::Revert("key too large".into()))805 })806 .collect::<Result<Vec<_>>>()?;807808 <Self as CommonCollectionOperations<T>>::token_properties(809 &self,810 token_id.try_into()?,811 if keys.is_empty() { None } else { Some(keys) },812 )813 .into_iter()814 .map(eth::Property::try_from)815 .collect::<Result<Vec<_>>>()816 }817 818 819 820 821 822 823 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]824 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {825 let caller = T::CrossAccountId::from_eth(caller);826 let to = T::CrossAccountId::from_eth(to);827 let token = token_id.try_into()?;828 let budget = self829 .recorder830 .weight_calls_budget(<StructureWeight<T>>::find_parent());831832 let balance = balance(self, token, &caller)?;833 ensure_single_owner(self, token, balance)?;834835 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)836 .map_err(dispatch_to_evm::<T>)?;837 Ok(())838 }839840 841 842 843 844 845 846 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]847 fn transfer_cross(848 &mut self,849 caller: caller,850 to: eth::CrossAddress,851 token_id: uint256,852 ) -> Result<void> {853 let caller = T::CrossAccountId::from_eth(caller);854 let to = to.into_sub_cross_account::<T>()?;855 let token = token_id.try_into()?;856 let budget = self857 .recorder858 .weight_calls_budget(<StructureWeight<T>>::find_parent());859860 let balance = balance(self, token, &caller)?;861 ensure_single_owner(self, token, balance)?;862863 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)864 .map_err(dispatch_to_evm::<T>)?;865 Ok(())866 }867868 869 870 871 872 873 874 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]875 fn transfer_from_cross(876 &mut self,877 caller: caller,878 from: eth::CrossAddress,879 to: eth::CrossAddress,880 token_id: uint256,881 ) -> Result<void> {882 let caller = T::CrossAccountId::from_eth(caller);883 let from = from.into_sub_cross_account::<T>()?;884 let to = to.into_sub_cross_account::<T>()?;885 let token_id = token_id.try_into()?;886 let budget = self887 .recorder888 .weight_calls_budget(<StructureWeight<T>>::find_parent());889890 let balance = balance(self, token_id, &from)?;891 ensure_single_owner(self, token_id, balance)?;892893 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)894 .map_err(dispatch_to_evm::<T>)?;895 Ok(())896 }897898 899 900 901 902 903 904 905 #[solidity(hide)]906 #[weight(<SelfWeightOf<T>>::burn_from())]907 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {908 let caller = T::CrossAccountId::from_eth(caller);909 let from = T::CrossAccountId::from_eth(from);910 let token = token_id.try_into()?;911 let budget = self912 .recorder913 .weight_calls_budget(<StructureWeight<T>>::find_parent());914915 let balance = balance(self, token, &from)?;916 ensure_single_owner(self, token, balance)?;917918 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)919 .map_err(dispatch_to_evm::<T>)?;920 Ok(())921 }922923 924 925 926 927 928 929 930 #[weight(<SelfWeightOf<T>>::burn_from())]931 fn burn_from_cross(932 &mut self,933 caller: caller,934 from: eth::CrossAddress,935 token_id: uint256,936 ) -> Result<void> {937 let caller = T::CrossAccountId::from_eth(caller);938 let from = from.into_sub_cross_account::<T>()?;939 let token = token_id.try_into()?;940 let budget = self941 .recorder942 .weight_calls_budget(<StructureWeight<T>>::find_parent());943944 let balance = balance(self, token, &from)?;945 ensure_single_owner(self, token, balance)?;946947 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)948 .map_err(dispatch_to_evm::<T>)?;949 Ok(())950 }951952 953 fn next_token_id(&self) -> Result<uint256> {954 self.consume_store_reads(1)?;955 Ok(<TokensMinted<T>>::get(self.id)956 .checked_add(1)957 .ok_or("item id overflow")?958 .into())959 }960961 962 963 964 965 966 #[solidity(hide)]967 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]968 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {969 let caller = T::CrossAccountId::from_eth(caller);970 let to = T::CrossAccountId::from_eth(to);971 let mut expected_index = <TokensMinted<T>>::get(self.id)972 .checked_add(1)973 .ok_or("item id overflow")?;974 let budget = self975 .recorder976 .weight_calls_budget(<StructureWeight<T>>::find_parent());977978 let total_tokens = token_ids.len();979 for id in token_ids.into_iter() {980 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;981 if id != expected_index {982 return Err("item id should be next".into());983 }984 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;985 }986 let users = [(to.clone(), 1)]987 .into_iter()988 .collect::<BTreeMap<_, _>>()989 .try_into()990 .unwrap();991 let create_item_data = CreateItemData::<T> {992 users,993 properties: CollectionPropertiesVec::default(),994 };995 let data = (0..total_tokens)996 .map(|_| create_item_data.clone())997 .collect();998999 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1000 .map_err(dispatch_to_evm::<T>)?;1001 Ok(true)1002 }10031004 1005 1006 1007 1008 1009 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1010 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]1011 fn mint_bulk_with_token_uri(1012 &mut self,1013 caller: caller,1014 to: address,1015 tokens: Vec<(uint256, string)>,1016 ) -> Result<bool> {1017 let key = key::url();1018 let caller = T::CrossAccountId::from_eth(caller);1019 let to = T::CrossAccountId::from_eth(to);1020 let mut expected_index = <TokensMinted<T>>::get(self.id)1021 .checked_add(1)1022 .ok_or("item id overflow")?;1023 let budget = self1024 .recorder1025 .weight_calls_budget(<StructureWeight<T>>::find_parent());10261027 let mut data = Vec::with_capacity(tokens.len());1028 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]1029 .into_iter()1030 .collect::<BTreeMap<_, _>>()1031 .try_into()1032 .unwrap();1033 for (id, token_uri) in tokens {1034 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1035 if id != expected_index {1036 return Err("item id should be next".into());1037 }1038 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10391040 let mut properties = CollectionPropertiesVec::default();1041 properties1042 .try_push(Property {1043 key: key.clone(),1044 value: token_uri1045 .into_bytes()1046 .try_into()1047 .map_err(|_| "token uri is too long")?,1048 })1049 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;10501051 let create_item_data = CreateItemData::<T> {1052 users: users.clone(),1053 properties,1054 };1055 data.push(create_item_data);1056 }10571058 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1059 .map_err(dispatch_to_evm::<T>)?;1060 Ok(true)1061 }10621063 1064 1065 1066 1067 #[weight(<SelfWeightOf<T>>::create_item())]1068 fn mint_cross(1069 &mut self,1070 caller: caller,1071 to: eth::CrossAddress,1072 properties: Vec<eth::Property>,1073 ) -> Result<uint256> {1074 let token_id = <TokensMinted<T>>::get(self.id)1075 .checked_add(1)1076 .ok_or("item id overflow")?;10771078 let to = to.into_sub_cross_account::<T>()?;10791080 let properties = properties1081 .into_iter()1082 .map(eth::Property::try_into)1083 .collect::<Result<Vec<_>>>()?1084 .try_into()1085 .map_err(|_| Error::Revert(alloc::format!("too many properties")))?;10861087 let caller = T::CrossAccountId::from_eth(caller);10881089 let budget = self1090 .recorder1091 .weight_calls_budget(<StructureWeight<T>>::find_parent());10921093 let users = [(to, 1)]1094 .into_iter()1095 .collect::<BTreeMap<_, _>>()1096 .try_into()1097 .unwrap();1098 <Pallet<T>>::create_item(1099 self,1100 &caller,1101 CreateItemData::<T> { users, properties },1102 &budget,1103 )1104 .map_err(dispatch_to_evm::<T>)?;11051106 Ok(token_id.into())1107 }11081109 1110 1111 1112 fn token_contract_address(&self, token: uint256) -> Result<address> {1113 Ok(T::EvmTokenAddressMapping::token_to_address(1114 self.id,1115 token.try_into().map_err(|_| "token id overflow")?,1116 ))1117 }11181119 1120 fn collection_helper_address(&self) -> Result<address> {1121 Ok(T::ContractAddress::get())1122 }1123}11241125#[solidity_interface(1126 name = UniqueRefungible,1127 is(1128 ERC721,1129 ERC721Enumerable,1130 ERC721UniqueExtensions,1131 ERC721UniqueMintable,1132 ERC721Burnable,1133 ERC721Metadata(if(this.flags.erc721metadata)),1134 Collection(via(common_mut returns CollectionHandle<T>)),1135 TokenProperties,1136 )1137)]1138impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}113911401141generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);1142generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);11431144impl<T: Config> CommonEvmHandler for RefungibleHandle<T>1145where1146 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1147{1148 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");1149 fn call(1150 self,1151 handle: &mut impl PrecompileHandle,1152 ) -> Option<pallet_common::erc::PrecompileResult> {1153 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)1154 }1155}