12345678910111213141516171819202122extern crate alloc;2324use alloc::string::ToString;25use core::{26 char::{REPLACEMENT_CHARACTER, decode_utf16},27 convert::TryInto,28};29use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};30use frame_support::{BoundedBTreeMap, BoundedVec};31use pallet_common::{32 CollectionHandle, CollectionPropertyPermissions,33 erc::{34 CommonEvmHandler, CollectionCall,35 static_property::{key, value as property_value},36 },37 eth::collection_id_to_address,38};39use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm, PrecompileHandle};40use pallet_evm_coder_substrate::{call, dispatch_to_evm};41use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};42use sp_core::H160;43use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};44use up_data_structs::{45 CollectionId, CollectionPropertiesVec, Property, PropertyKey, PropertyKeyPermission,46 PropertyPermission, TokenId,47};4849use crate::{50 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,51 TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,52};535455#[solidity_interface(name = "TokenProperties")]56impl<T: Config> RefungibleHandle<T> {57 58 59 60 61 62 63 fn set_token_property_permission(64 &mut self,65 caller: caller,66 key: string,67 is_mutable: bool,68 collection_admin: bool,69 token_owner: bool,70 ) -> Result<()> {71 let caller = T::CrossAccountId::from_eth(caller);72 <Pallet<T>>::set_token_property_permissions(73 self,74 &caller,75 vec![PropertyKeyPermission {76 key: <Vec<u8>>::from(key)77 .try_into()78 .map_err(|_| "too long key")?,79 permission: PropertyPermission {80 mutable: is_mutable,81 collection_admin,82 token_owner,83 },84 }],85 )86 .map_err(dispatch_to_evm::<T>)87 }8889 90 91 92 93 94 fn set_property(95 &mut self,96 caller: caller,97 token_id: uint256,98 key: string,99 value: bytes,100 ) -> Result<()> {101 let caller = T::CrossAccountId::from_eth(caller);102 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;103 let key = <Vec<u8>>::from(key)104 .try_into()105 .map_err(|_| "key too long")?;106 let value = value.try_into().map_err(|_| "value too long")?;107108 let nesting_budget = self109 .recorder110 .weight_calls_budget(<StructureWeight<T>>::find_parent());111112 <Pallet<T>>::set_token_property(113 self,114 &caller,115 TokenId(token_id),116 Property { key, value },117 &nesting_budget,118 )119 .map_err(dispatch_to_evm::<T>)120 }121122 123 124 125 126 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {127 let caller = T::CrossAccountId::from_eth(caller);128 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;129 let key = <Vec<u8>>::from(key)130 .try_into()131 .map_err(|_| "key too long")?;132133 let nesting_budget = self134 .recorder135 .weight_calls_budget(<StructureWeight<T>>::find_parent());136137 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)138 .map_err(dispatch_to_evm::<T>)139 }140141 142 143 144 145 146 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {147 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;148 let key = <Vec<u8>>::from(key)149 .try_into()150 .map_err(|_| "key too long")?;151152 let props = <TokenProperties<T>>::get((self.id, token_id));153 let prop = props.get(&key).ok_or("key not found")?;154155 Ok(prop.to_vec())156 }157}158159#[derive(ToLog)]160pub enum ERC721Events {161 162 163 164 Transfer {165 #[indexed]166 from: address,167 #[indexed]168 to: address,169 #[indexed]170 token_id: uint256,171 },172 173 Approval {174 #[indexed]175 owner: address,176 #[indexed]177 approved: address,178 #[indexed]179 token_id: uint256,180 },181 182 #[allow(dead_code)]183 ApprovalForAll {184 #[indexed]185 owner: address,186 #[indexed]187 operator: address,188 approved: bool,189 },190}191192#[derive(ToLog)]193pub enum ERC721MintableEvents {194 195 #[allow(dead_code)]196 MintingFinished {},197}198199#[solidity_interface(name = "ERC721Metadata")]200impl<T: Config> RefungibleHandle<T> {201 202 fn name(&self) -> Result<string> {203 Ok(decode_utf16(self.name.iter().copied())204 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))205 .collect::<string>())206 }207208 209 fn symbol(&self) -> Result<string> {210 Ok(string::from_utf8_lossy(&self.token_prefix).into())211 }212213 214 215 216 217 218 219 220 221 222 #[solidity(rename_selector = "tokenURI")]223 fn token_uri(&self, token_id: uint256) -> Result<string> {224 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;225226 if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {227 if !url.is_empty() {228 return Ok(url);229 }230 } else if !is_erc721_metadata_compatible::<T>(self.id) {231 return Err("tokenURI not set".into());232 }233234 if let Some(base_uri) =235 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())236 {237 if !base_uri.is_empty() {238 let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {239 Error::Revert(alloc::format!(240 "Can not convert value \"baseURI\" to string with error \"{}\"",241 e242 ))243 })?;244 if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {245 if !suffix.is_empty() {246 return Ok(base_uri + suffix.as_str());247 }248 }249250 return Ok(base_uri + token_id.to_string().as_str());251 }252 }253254 Ok("".into())255 }256}257258259260#[solidity_interface(name = "ERC721Enumerable")]261impl<T: Config> RefungibleHandle<T> {262 263 264 265 266 fn token_by_index(&self, index: uint256) -> Result<uint256> {267 Ok(index)268 }269270 271 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {272 273 Err("not implemented".into())274 }275276 277 278 279 fn total_supply(&self) -> Result<uint256> {280 self.consume_store_reads(1)?;281 Ok(<Pallet<T>>::total_supply(self).into())282 }283}284285286287#[solidity_interface(name = "ERC721", events(ERC721Events))]288impl<T: Config> RefungibleHandle<T> {289 290 291 292 293 294 fn balance_of(&self, owner: address) -> Result<uint256> {295 self.consume_store_reads(1)?;296 let owner = T::CrossAccountId::from_eth(owner);297 let balance = <AccountBalance<T>>::get((self.id, owner));298 Ok(balance.into())299 }300301 fn owner_of(&self, token_id: uint256) -> Result<address> {302 self.consume_store_reads(2)?;303 let token = token_id.try_into()?;304 let owner = <Pallet<T>>::token_owner(self.id, token);305 Ok(owner306 .map(|address| *address.as_eth())307 .unwrap_or_else(|| H160::default()))308 }309310 311 fn safe_transfer_from_with_data(312 &mut self,313 _from: address,314 _to: address,315 _token_id: uint256,316 _data: bytes,317 _value: value,318 ) -> Result<void> {319 320 Err("not implemented".into())321 }322323 324 fn safe_transfer_from(325 &mut self,326 _from: address,327 _to: address,328 _token_id: uint256,329 _value: value,330 ) -> Result<void> {331 332 Err("not implemented".into())333 }334335 336 337 338 339 340 341 342 343 344 345 346 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]347 fn transfer_from(348 &mut self,349 caller: caller,350 from: address,351 to: address,352 token_id: uint256,353 _value: value,354 ) -> Result<void> {355 let caller = T::CrossAccountId::from_eth(caller);356 let from = T::CrossAccountId::from_eth(from);357 let to = T::CrossAccountId::from_eth(to);358 let token = token_id.try_into()?;359 let budget = self360 .recorder361 .weight_calls_budget(<StructureWeight<T>>::find_parent());362363 let balance = balance(&self, token, &from)?;364 ensure_single_owner(&self, token, balance)?;365366 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)367 .map_err(dispatch_to_evm::<T>)?;368369 <PalletEvm<T>>::deposit_log(370 ERC721Events::Transfer {371 from: *from.as_eth(),372 to: *to.as_eth(),373 token_id: token_id.into(),374 }375 .to_log(collection_id_to_address(self.id)),376 );377 Ok(())378 }379380 381 fn approve(382 &mut self,383 _caller: caller,384 _approved: address,385 _token_id: uint256,386 _value: value,387 ) -> Result<void> {388 Err("not implemented".into())389 }390391 392 fn set_approval_for_all(393 &mut self,394 _caller: caller,395 _operator: address,396 _approved: bool,397 ) -> Result<void> {398 399 Err("not implemented".into())400 }401402 403 fn get_approved(&self, _token_id: uint256) -> Result<address> {404 405 Err("not implemented".into())406 }407408 409 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {410 411 Err("not implemented".into())412 }413}414415416fn balance<T: Config>(417 collection: &RefungibleHandle<T>,418 token: TokenId,419 owner: &T::CrossAccountId,420) -> Result<u128> {421 collection.consume_store_reads(1)?;422 let balance = <Balance<T>>::get((collection.id, token, &owner));423 Ok(balance)424}425426427fn ensure_single_owner<T: Config>(428 collection: &RefungibleHandle<T>,429 token: TokenId,430 owner_balance: u128,431) -> Result<()> {432 collection.consume_store_reads(1)?;433 let total_supply = <TotalSupply<T>>::get((collection.id, token));434 if total_supply != owner_balance {435 return Err("token has multiple owners".into());436 }437 Ok(())438}439440441#[solidity_interface(name = "ERC721Burnable")]442impl<T: Config> RefungibleHandle<T> {443 444 445 446 447 #[weight(<SelfWeightOf<T>>::burn_item_fully())]448 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {449 let caller = T::CrossAccountId::from_eth(caller);450 let token = token_id.try_into()?;451452 let balance = balance(&self, token, &caller)?;453 ensure_single_owner(&self, token, balance)?;454455 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;456 Ok(())457 }458}459460461#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]462impl<T: Config> RefungibleHandle<T> {463 fn minting_finished(&self) -> Result<bool> {464 Ok(false)465 }466467 468 469 470 471 472 #[weight(<SelfWeightOf<T>>::create_item())]473 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {474 let caller = T::CrossAccountId::from_eth(caller);475 let to = T::CrossAccountId::from_eth(to);476 let token_id: u32 = token_id.try_into()?;477 let budget = self478 .recorder479 .weight_calls_budget(<StructureWeight<T>>::find_parent());480481 if <TokensMinted<T>>::get(self.id)482 .checked_add(1)483 .ok_or("item id overflow")?484 != token_id485 {486 return Err("item id should be next".into());487 }488489 let const_data = BoundedVec::default();490 let users = [(to.clone(), 1)]491 .into_iter()492 .collect::<BTreeMap<_, _>>()493 .try_into()494 .unwrap();495 <Pallet<T>>::create_item(496 self,497 &caller,498 CreateItemData::<T> {499 const_data,500 users,501 properties: CollectionPropertiesVec::default(),502 },503 &budget,504 )505 .map_err(dispatch_to_evm::<T>)?;506507 Ok(true)508 }509510 511 512 513 514 515 516 #[solidity(rename_selector = "mintWithTokenURI")]517 #[weight(<SelfWeightOf<T>>::create_item())]518 fn mint_with_token_uri(519 &mut self,520 caller: caller,521 to: address,522 token_id: uint256,523 token_uri: string,524 ) -> Result<bool> {525 let key = key::url();526 let permission = get_token_permission::<T>(self.id, &key)?;527 if !permission.collection_admin {528 return Err("Operation is not allowed".into());529 }530531 let caller = T::CrossAccountId::from_eth(caller);532 let to = T::CrossAccountId::from_eth(to);533 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;534 let budget = self535 .recorder536 .weight_calls_budget(<StructureWeight<T>>::find_parent());537538 if <TokensMinted<T>>::get(self.id)539 .checked_add(1)540 .ok_or("item id overflow")?541 != token_id542 {543 return Err("item id should be next".into());544 }545546 let mut properties = CollectionPropertiesVec::default();547 properties548 .try_push(Property {549 key,550 value: token_uri551 .into_bytes()552 .try_into()553 .map_err(|_| "token uri is too long")?,554 })555 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;556557 let const_data = BoundedVec::default();558 let users = [(to.clone(), 1)]559 .into_iter()560 .collect::<BTreeMap<_, _>>()561 .try_into()562 .unwrap();563 <Pallet<T>>::create_item(564 self,565 &caller,566 CreateItemData::<T> {567 const_data,568 users,569 properties,570 },571 &budget,572 )573 .map_err(dispatch_to_evm::<T>)?;574 Ok(true)575 }576577 578 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {579 Err("not implementable".into())580 }581}582583fn get_token_property<T: Config>(584 collection: &CollectionHandle<T>,585 token_id: u32,586 key: &up_data_structs::PropertyKey,587) -> Result<string> {588 collection.consume_store_reads(1)?;589 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))590 .map_err(|_| Error::Revert("Token properties not found".into()))?;591 if let Some(property) = properties.get(key) {592 return Ok(string::from_utf8_lossy(property).into());593 }594595 Err("Property tokenURI not found".into())596}597598fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {599 if let Some(shema_name) =600 pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())601 {602 let shema_name = shema_name.into_inner();603 shema_name == property_value::ERC721_METADATA604 } else {605 false606 }607}608609fn get_token_permission<T: Config>(610 collection_id: CollectionId,611 key: &PropertyKey,612) -> Result<PropertyPermission> {613 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)614 .map_err(|_| Error::Revert("No permissions for collection".into()))?;615 let a = token_property_permissions616 .get(key)617 .map(Clone::clone)618 .ok_or_else(|| {619 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();620 Error::Revert(alloc::format!("No permission for key {}", key))621 })?;622 Ok(a)623}624625626#[solidity_interface(name = "ERC721UniqueExtensions")]627impl<T: Config> RefungibleHandle<T> {628 629 630 631 632 633 634 635 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]636 fn transfer(637 &mut self,638 caller: caller,639 to: address,640 token_id: uint256,641 _value: value,642 ) -> Result<void> {643 let caller = T::CrossAccountId::from_eth(caller);644 let to = T::CrossAccountId::from_eth(to);645 let token = token_id.try_into()?;646 let budget = self647 .recorder648 .weight_calls_budget(<StructureWeight<T>>::find_parent());649650 let balance = balance(&self, token, &caller)?;651 ensure_single_owner(&self, token, balance)?;652653 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)654 .map_err(dispatch_to_evm::<T>)?;655 <PalletEvm<T>>::deposit_log(656 ERC721Events::Transfer {657 from: *caller.as_eth(),658 to: *to.as_eth(),659 token_id: token_id.into(),660 }661 .to_log(collection_id_to_address(self.id)),662 );663 Ok(())664 }665666 667 668 669 670 671 672 673 674 #[weight(<SelfWeightOf<T>>::burn_from())]675 fn burn_from(676 &mut self,677 caller: caller,678 from: address,679 token_id: uint256,680 _value: value,681 ) -> Result<void> {682 let caller = T::CrossAccountId::from_eth(caller);683 let from = T::CrossAccountId::from_eth(from);684 let token = token_id.try_into()?;685 let budget = self686 .recorder687 .weight_calls_budget(<StructureWeight<T>>::find_parent());688689 let balance = balance(&self, token, &caller)?;690 ensure_single_owner(&self, token, balance)?;691692 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)693 .map_err(dispatch_to_evm::<T>)?;694 Ok(())695 }696697 698 fn next_token_id(&self) -> Result<uint256> {699 self.consume_store_reads(1)?;700 Ok(<TokensMinted<T>>::get(self.id)701 .checked_add(1)702 .ok_or("item id overflow")?703 .into())704 }705706 707 708 709 710 711 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]712 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {713 let caller = T::CrossAccountId::from_eth(caller);714 let to = T::CrossAccountId::from_eth(to);715 let mut expected_index = <TokensMinted<T>>::get(self.id)716 .checked_add(1)717 .ok_or("item id overflow")?;718 let budget = self719 .recorder720 .weight_calls_budget(<StructureWeight<T>>::find_parent());721722 let total_tokens = token_ids.len();723 for id in token_ids.into_iter() {724 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;725 if id != expected_index {726 return Err("item id should be next".into());727 }728 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;729 }730 let const_data = BoundedVec::default();731 let users = [(to.clone(), 1)]732 .into_iter()733 .collect::<BTreeMap<_, _>>()734 .try_into()735 .unwrap();736 let create_item_data = CreateItemData::<T> {737 const_data,738 users,739 properties: CollectionPropertiesVec::default(),740 };741 let data = (0..total_tokens)742 .map(|_| create_item_data.clone())743 .collect();744745 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)746 .map_err(dispatch_to_evm::<T>)?;747 Ok(true)748 }749750 751 752 753 754 755 #[solidity(rename_selector = "mintBulkWithTokenURI")]756 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]757 fn mint_bulk_with_token_uri(758 &mut self,759 caller: caller,760 to: address,761 tokens: Vec<(uint256, string)>,762 ) -> Result<bool> {763 let key = key::url();764 let caller = T::CrossAccountId::from_eth(caller);765 let to = T::CrossAccountId::from_eth(to);766 let mut expected_index = <TokensMinted<T>>::get(self.id)767 .checked_add(1)768 .ok_or("item id overflow")?;769 let budget = self770 .recorder771 .weight_calls_budget(<StructureWeight<T>>::find_parent());772773 let mut data = Vec::with_capacity(tokens.len());774 let const_data = BoundedVec::default();775 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]776 .into_iter()777 .collect::<BTreeMap<_, _>>()778 .try_into()779 .unwrap();780 for (id, token_uri) in tokens {781 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;782 if id != expected_index {783 return Err("item id should be next".into());784 }785 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;786787 let mut properties = CollectionPropertiesVec::default();788 properties789 .try_push(Property {790 key: key.clone(),791 value: token_uri792 .into_bytes()793 .try_into()794 .map_err(|_| "token uri is too long")?,795 })796 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;797798 let create_item_data = CreateItemData::<T> {799 const_data: const_data.clone(),800 users: users.clone(),801 properties,802 };803 data.push(create_item_data);804 }805806 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)807 .map_err(dispatch_to_evm::<T>)?;808 Ok(true)809 }810}811812#[solidity_interface(813 name = "UniqueRefungible",814 is(815 ERC721,816 ERC721Metadata,817 ERC721Enumerable,818 ERC721UniqueExtensions,819 ERC721Mintable,820 ERC721Burnable,821 via("CollectionHandle<T>", common_mut, Collection),822 TokenProperties,823 )824)]825impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> {}826827828generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);829generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);830831impl<T: Config> CommonEvmHandler for RefungibleHandle<T>832where833 T::AccountId: From<[u8; 32]>,834{835 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");836 fn call(837 self,838 handle: &mut impl PrecompileHandle,839 ) -> Option<pallet_common::erc::PrecompileResult> {840 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)841 }842}