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;31use pallet_common::{32 CollectionHandle, CollectionPropertyPermissions,33 erc::{34 CommonEvmHandler, CollectionCall,35 static_property::{key, value as property_value},36 },37};38use pallet_evm::{account::CrossAccountId, PrecompileHandle};39use pallet_evm_coder_substrate::{call, dispatch_to_evm};40use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};41use sp_core::H160;42use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};43use up_data_structs::{44 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,45 PropertyKeyPermission, PropertyPermission, TokenId,46};4748use crate::{49 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,50 TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,51};5253pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);545556#[solidity_interface(name = "TokenProperties")]57impl<T: Config> RefungibleHandle<T> {58 59 60 61 62 63 64 fn set_token_property_permission(65 &mut self,66 caller: caller,67 key: string,68 is_mutable: bool,69 collection_admin: bool,70 token_owner: bool,71 ) -> Result<()> {72 let caller = T::CrossAccountId::from_eth(caller);73 <Pallet<T>>::set_token_property_permissions(74 self,75 &caller,76 vec![PropertyKeyPermission {77 key: <Vec<u8>>::from(key)78 .try_into()79 .map_err(|_| "too long key")?,80 permission: PropertyPermission {81 mutable: is_mutable,82 collection_admin,83 token_owner,84 },85 }],86 )87 .map_err(dispatch_to_evm::<T>)88 }8990 91 92 93 94 95 fn set_property(96 &mut self,97 caller: caller,98 token_id: uint256,99 key: string,100 value: bytes,101 ) -> Result<()> {102 let caller = T::CrossAccountId::from_eth(caller);103 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;104 let key = <Vec<u8>>::from(key)105 .try_into()106 .map_err(|_| "key too long")?;107 let value = value.try_into().map_err(|_| "value too long")?;108109 let nesting_budget = self110 .recorder111 .weight_calls_budget(<StructureWeight<T>>::find_parent());112113 <Pallet<T>>::set_token_property(114 self,115 &caller,116 TokenId(token_id),117 Property { key, value },118 &nesting_budget,119 )120 .map_err(dispatch_to_evm::<T>)121 }122123 124 125 126 127 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {128 let caller = T::CrossAccountId::from_eth(caller);129 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;130 let key = <Vec<u8>>::from(key)131 .try_into()132 .map_err(|_| "key too long")?;133134 let nesting_budget = self135 .recorder136 .weight_calls_budget(<StructureWeight<T>>::find_parent());137138 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)139 .map_err(dispatch_to_evm::<T>)140 }141142 143 144 145 146 147 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {148 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;149 let key = <Vec<u8>>::from(key)150 .try_into()151 .map_err(|_| "key too long")?;152153 let props = <TokenProperties<T>>::get((self.id, token_id));154 let prop = props.get(&key).ok_or("key not found")?;155156 Ok(prop.to_vec())157 }158}159160#[derive(ToLog)]161pub enum ERC721Events {162 163 164 165 Transfer {166 #[indexed]167 from: address,168 #[indexed]169 to: address,170 #[indexed]171 token_id: uint256,172 },173 174 Approval {175 #[indexed]176 owner: address,177 #[indexed]178 approved: address,179 #[indexed]180 token_id: uint256,181 },182 183 #[allow(dead_code)]184 ApprovalForAll {185 #[indexed]186 owner: address,187 #[indexed]188 operator: address,189 approved: bool,190 },191}192193#[derive(ToLog)]194pub enum ERC721MintableEvents {195 196 #[allow(dead_code)]197 MintingFinished {},198}199200#[solidity_interface(name = "ERC721Metadata")]201impl<T: Config> RefungibleHandle<T> {202 203 fn name(&self) -> Result<string> {204 Ok(decode_utf16(self.name.iter().copied())205 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))206 .collect::<string>())207 }208209 210 fn symbol(&self) -> Result<string> {211 Ok(string::from_utf8_lossy(&self.token_prefix).into())212 }213214 215 216 217 218 219 220 221 222 223 #[solidity(rename_selector = "tokenURI")]224 fn token_uri(&self, token_id: uint256) -> Result<string> {225 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;226227 if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {228 if !url.is_empty() {229 return Ok(url);230 }231 } else if !is_erc721_metadata_compatible::<T>(self.id) {232 return Err("tokenURI not set".into());233 }234235 if let Some(base_uri) =236 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())237 {238 if !base_uri.is_empty() {239 let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {240 Error::Revert(alloc::format!(241 "Can not convert value \"baseURI\" to string with error \"{}\"",242 e243 ))244 })?;245 if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {246 if !suffix.is_empty() {247 return Ok(base_uri + suffix.as_str());248 }249 }250251 return Ok(base_uri + token_id.to_string().as_str());252 }253 }254255 Ok("".into())256 }257}258259260261#[solidity_interface(name = "ERC721Enumerable")]262impl<T: Config> RefungibleHandle<T> {263 264 265 266 267 fn token_by_index(&self, index: uint256) -> Result<uint256> {268 Ok(index)269 }270271 272 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {273 274 Err("not implemented".into())275 }276277 278 279 280 fn total_supply(&self) -> Result<uint256> {281 self.consume_store_reads(1)?;282 Ok(<Pallet<T>>::total_supply(self).into())283 }284}285286287288#[solidity_interface(name = "ERC721", events(ERC721Events))]289impl<T: Config> RefungibleHandle<T> {290 291 292 293 294 295 fn balance_of(&self, owner: address) -> Result<uint256> {296 self.consume_store_reads(1)?;297 let owner = T::CrossAccountId::from_eth(owner);298 let balance = <AccountBalance<T>>::get((self.id, owner));299 Ok(balance.into())300 }301302 303 304 305 306 307 308 309 fn owner_of(&self, token_id: uint256) -> Result<address> {310 self.consume_store_reads(2)?;311 let token = token_id.try_into()?;312 let owner = <Pallet<T>>::token_owner(self.id, token);313 Ok(owner314 .map(|address| *address.as_eth())315 .unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))316 }317318 319 fn safe_transfer_from_with_data(320 &mut self,321 _from: address,322 _to: address,323 _token_id: uint256,324 _data: bytes,325 _value: value,326 ) -> Result<void> {327 328 Err("not implemented".into())329 }330331 332 fn safe_transfer_from(333 &mut self,334 _from: address,335 _to: address,336 _token_id: uint256,337 _value: value,338 ) -> Result<void> {339 340 Err("not implemented".into())341 }342343 344 345 346 347 348 349 350 351 352 353 354 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]355 fn transfer_from(356 &mut self,357 caller: caller,358 from: address,359 to: address,360 token_id: uint256,361 _value: value,362 ) -> Result<void> {363 let caller = T::CrossAccountId::from_eth(caller);364 let from = T::CrossAccountId::from_eth(from);365 let to = T::CrossAccountId::from_eth(to);366 let token = token_id.try_into()?;367 let budget = self368 .recorder369 .weight_calls_budget(<StructureWeight<T>>::find_parent());370371 let balance = balance(&self, token, &from)?;372 ensure_single_owner(&self, token, balance)?;373374 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)375 .map_err(dispatch_to_evm::<T>)?;376377 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}414415416pub fn 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}425426427pub fn 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 users = [(to.clone(), 1)]490 .into_iter()491 .collect::<BTreeMap<_, _>>()492 .try_into()493 .unwrap();494 <Pallet<T>>::create_item(495 self,496 &caller,497 CreateItemData::<T::CrossAccountId> {498 users,499 properties: CollectionPropertiesVec::default(),500 },501 &budget,502 )503 .map_err(dispatch_to_evm::<T>)?;504505 Ok(true)506 }507508 509 510 511 512 513 514 #[solidity(rename_selector = "mintWithTokenURI")]515 #[weight(<SelfWeightOf<T>>::create_item())]516 fn mint_with_token_uri(517 &mut self,518 caller: caller,519 to: address,520 token_id: uint256,521 token_uri: string,522 ) -> Result<bool> {523 let key = key::url();524 let permission = get_token_permission::<T>(self.id, &key)?;525 if !permission.collection_admin {526 return Err("Operation is not allowed".into());527 }528529 let caller = T::CrossAccountId::from_eth(caller);530 let to = T::CrossAccountId::from_eth(to);531 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;532 let budget = self533 .recorder534 .weight_calls_budget(<StructureWeight<T>>::find_parent());535536 if <TokensMinted<T>>::get(self.id)537 .checked_add(1)538 .ok_or("item id overflow")?539 != token_id540 {541 return Err("item id should be next".into());542 }543544 let mut properties = CollectionPropertiesVec::default();545 properties546 .try_push(Property {547 key,548 value: token_uri549 .into_bytes()550 .try_into()551 .map_err(|_| "token uri is too long")?,552 })553 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;554555 let users = [(to.clone(), 1)]556 .into_iter()557 .collect::<BTreeMap<_, _>>()558 .try_into()559 .unwrap();560 <Pallet<T>>::create_item(561 self,562 &caller,563 CreateItemData::<T::CrossAccountId> { users, properties },564 &budget,565 )566 .map_err(dispatch_to_evm::<T>)?;567 Ok(true)568 }569570 571 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {572 Err("not implementable".into())573 }574}575576fn get_token_property<T: Config>(577 collection: &CollectionHandle<T>,578 token_id: u32,579 key: &up_data_structs::PropertyKey,580) -> Result<string> {581 collection.consume_store_reads(1)?;582 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))583 .map_err(|_| Error::Revert("Token properties not found".into()))?;584 if let Some(property) = properties.get(key) {585 return Ok(string::from_utf8_lossy(property).into());586 }587588 Err("Property tokenURI not found".into())589}590591fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {592 if let Some(shema_name) =593 pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())594 {595 let shema_name = shema_name.into_inner();596 shema_name == property_value::ERC721_METADATA597 } else {598 false599 }600}601602fn get_token_permission<T: Config>(603 collection_id: CollectionId,604 key: &PropertyKey,605) -> Result<PropertyPermission> {606 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)607 .map_err(|_| Error::Revert("No permissions for collection".into()))?;608 let a = token_property_permissions609 .get(key)610 .map(Clone::clone)611 .ok_or_else(|| {612 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();613 Error::Revert(alloc::format!("No permission for key {}", key))614 })?;615 Ok(a)616}617618619#[solidity_interface(name = "ERC721UniqueExtensions")]620impl<T: Config> RefungibleHandle<T> {621 622 623 624 625 626 627 628 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]629 fn transfer(630 &mut self,631 caller: caller,632 to: address,633 token_id: uint256,634 _value: value,635 ) -> Result<void> {636 let caller = T::CrossAccountId::from_eth(caller);637 let to = T::CrossAccountId::from_eth(to);638 let token = token_id.try_into()?;639 let budget = self640 .recorder641 .weight_calls_budget(<StructureWeight<T>>::find_parent());642643 let balance = balance(&self, token, &caller)?;644 ensure_single_owner(&self, token, balance)?;645646 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)647 .map_err(dispatch_to_evm::<T>)?;648 Ok(())649 }650651 652 653 654 655 656 657 658 659 #[weight(<SelfWeightOf<T>>::burn_from())]660 fn burn_from(661 &mut self,662 caller: caller,663 from: address,664 token_id: uint256,665 _value: value,666 ) -> Result<void> {667 let caller = T::CrossAccountId::from_eth(caller);668 let from = T::CrossAccountId::from_eth(from);669 let token = token_id.try_into()?;670 let budget = self671 .recorder672 .weight_calls_budget(<StructureWeight<T>>::find_parent());673674 let balance = balance(&self, token, &caller)?;675 ensure_single_owner(&self, token, balance)?;676677 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)678 .map_err(dispatch_to_evm::<T>)?;679 Ok(())680 }681682 683 fn next_token_id(&self) -> Result<uint256> {684 self.consume_store_reads(1)?;685 Ok(<TokensMinted<T>>::get(self.id)686 .checked_add(1)687 .ok_or("item id overflow")?688 .into())689 }690691 692 693 694 695 696 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]697 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {698 let caller = T::CrossAccountId::from_eth(caller);699 let to = T::CrossAccountId::from_eth(to);700 let mut expected_index = <TokensMinted<T>>::get(self.id)701 .checked_add(1)702 .ok_or("item id overflow")?;703 let budget = self704 .recorder705 .weight_calls_budget(<StructureWeight<T>>::find_parent());706707 let total_tokens = token_ids.len();708 for id in token_ids.into_iter() {709 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;710 if id != expected_index {711 return Err("item id should be next".into());712 }713 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;714 }715 let users = [(to.clone(), 1)]716 .into_iter()717 .collect::<BTreeMap<_, _>>()718 .try_into()719 .unwrap();720 let create_item_data = CreateItemData::<T::CrossAccountId> {721 users,722 properties: CollectionPropertiesVec::default(),723 };724 let data = (0..total_tokens)725 .map(|_| create_item_data.clone())726 .collect();727728 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)729 .map_err(dispatch_to_evm::<T>)?;730 Ok(true)731 }732733 734 735 736 737 738 #[solidity(rename_selector = "mintBulkWithTokenURI")]739 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]740 fn mint_bulk_with_token_uri(741 &mut self,742 caller: caller,743 to: address,744 tokens: Vec<(uint256, string)>,745 ) -> Result<bool> {746 let key = key::url();747 let caller = T::CrossAccountId::from_eth(caller);748 let to = T::CrossAccountId::from_eth(to);749 let mut expected_index = <TokensMinted<T>>::get(self.id)750 .checked_add(1)751 .ok_or("item id overflow")?;752 let budget = self753 .recorder754 .weight_calls_budget(<StructureWeight<T>>::find_parent());755756 let mut data = Vec::with_capacity(tokens.len());757 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]758 .into_iter()759 .collect::<BTreeMap<_, _>>()760 .try_into()761 .unwrap();762 for (id, token_uri) in tokens {763 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;764 if id != expected_index {765 return Err("item id should be next".into());766 }767 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;768769 let mut properties = CollectionPropertiesVec::default();770 properties771 .try_push(Property {772 key: key.clone(),773 value: token_uri774 .into_bytes()775 .try_into()776 .map_err(|_| "token uri is too long")?,777 })778 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;779780 let create_item_data = CreateItemData::<T::CrossAccountId> {781 users: users.clone(),782 properties,783 };784 data.push(create_item_data);785 }786787 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)788 .map_err(dispatch_to_evm::<T>)?;789 Ok(true)790 }791792 793 794 795 fn token_contract_address(&self, token: uint256) -> Result<address> {796 Ok(T::EvmTokenAddressMapping::token_to_address(797 self.id,798 token.try_into().map_err(|_| "token id overflow")?,799 ))800 }801}802803#[solidity_interface(804 name = "UniqueRefungible",805 is(806 ERC721,807 ERC721Metadata,808 ERC721Enumerable,809 ERC721UniqueExtensions,810 ERC721Mintable,811 ERC721Burnable,812 via("CollectionHandle<T>", common_mut, Collection),813 TokenProperties,814 )815)]816impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> {}817818819generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);820generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);821822impl<T: Config> CommonEvmHandler for RefungibleHandle<T>823where824 T::AccountId: From<[u8; 32]>,825{826 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");827 fn call(828 self,829 handle: &mut impl PrecompileHandle,830 ) -> Option<pallet_common::erc::PrecompileResult> {831 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)832 }833}