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 !self.supports_metadata() {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 ) -> Result<void> {326 327 Err("not implemented".into())328 }329330 331 fn safe_transfer_from(332 &mut self,333 _from: address,334 _to: address,335 _token_id: uint256,336 ) -> Result<void> {337 338 Err("not implemented".into())339 }340341 342 343 344 345 346 347 348 349 350 351 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]352 fn transfer_from(353 &mut self,354 caller: caller,355 from: address,356 to: address,357 token_id: uint256,358 ) -> Result<void> {359 let caller = T::CrossAccountId::from_eth(caller);360 let from = T::CrossAccountId::from_eth(from);361 let to = T::CrossAccountId::from_eth(to);362 let token = token_id.try_into()?;363 let budget = self364 .recorder365 .weight_calls_budget(<StructureWeight<T>>::find_parent());366367 let balance = balance(&self, token, &from)?;368 ensure_single_owner(&self, token, balance)?;369370 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)371 .map_err(dispatch_to_evm::<T>)?;372373 Ok(())374 }375376 377 fn approve(&mut self, _caller: caller, _approved: address, _token_id: uint256) -> Result<void> {378 Err("not implemented".into())379 }380381 382 fn set_approval_for_all(383 &mut self,384 _caller: caller,385 _operator: address,386 _approved: bool,387 ) -> Result<void> {388 389 Err("not implemented".into())390 }391392 393 fn get_approved(&self, _token_id: uint256) -> Result<address> {394 395 Err("not implemented".into())396 }397398 399 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {400 401 Err("not implemented".into())402 }403}404405406pub fn balance<T: Config>(407 collection: &RefungibleHandle<T>,408 token: TokenId,409 owner: &T::CrossAccountId,410) -> Result<u128> {411 collection.consume_store_reads(1)?;412 let balance = <Balance<T>>::get((collection.id, token, &owner));413 Ok(balance)414}415416417pub fn ensure_single_owner<T: Config>(418 collection: &RefungibleHandle<T>,419 token: TokenId,420 owner_balance: u128,421) -> Result<()> {422 collection.consume_store_reads(1)?;423 let total_supply = <TotalSupply<T>>::get((collection.id, token));424 if total_supply != owner_balance {425 return Err("token has multiple owners".into());426 }427 Ok(())428}429430431#[solidity_interface(name = ERC721Burnable)]432impl<T: Config> RefungibleHandle<T> {433 434 435 436 437 #[weight(<SelfWeightOf<T>>::burn_item_fully())]438 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {439 let caller = T::CrossAccountId::from_eth(caller);440 let token = token_id.try_into()?;441442 let balance = balance(&self, token, &caller)?;443 ensure_single_owner(&self, token, balance)?;444445 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;446 Ok(())447 }448}449450451#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]452impl<T: Config> RefungibleHandle<T> {453 fn minting_finished(&self) -> Result<bool> {454 Ok(false)455 }456457 458 459 460 461 462 #[weight(<SelfWeightOf<T>>::create_item())]463 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {464 let caller = T::CrossAccountId::from_eth(caller);465 let to = T::CrossAccountId::from_eth(to);466 let token_id: u32 = token_id.try_into()?;467 let budget = self468 .recorder469 .weight_calls_budget(<StructureWeight<T>>::find_parent());470471 if <TokensMinted<T>>::get(self.id)472 .checked_add(1)473 .ok_or("item id overflow")?474 != token_id475 {476 return Err("item id should be next".into());477 }478479 let users = [(to.clone(), 1)]480 .into_iter()481 .collect::<BTreeMap<_, _>>()482 .try_into()483 .unwrap();484 <Pallet<T>>::create_item(485 self,486 &caller,487 CreateItemData::<T::CrossAccountId> {488 users,489 properties: CollectionPropertiesVec::default(),490 },491 &budget,492 )493 .map_err(dispatch_to_evm::<T>)?;494495 Ok(true)496 }497498 499 500 501 502 503 504 #[solidity(rename_selector = "mintWithTokenURI")]505 #[weight(<SelfWeightOf<T>>::create_item())]506 fn mint_with_token_uri(507 &mut self,508 caller: caller,509 to: address,510 token_id: uint256,511 token_uri: string,512 ) -> Result<bool> {513 let key = key::url();514 let permission = get_token_permission::<T>(self.id, &key)?;515 if !permission.collection_admin {516 return Err("Operation is not allowed".into());517 }518519 let caller = T::CrossAccountId::from_eth(caller);520 let to = T::CrossAccountId::from_eth(to);521 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;522 let budget = self523 .recorder524 .weight_calls_budget(<StructureWeight<T>>::find_parent());525526 if <TokensMinted<T>>::get(self.id)527 .checked_add(1)528 .ok_or("item id overflow")?529 != token_id530 {531 return Err("item id should be next".into());532 }533534 let mut properties = CollectionPropertiesVec::default();535 properties536 .try_push(Property {537 key,538 value: token_uri539 .into_bytes()540 .try_into()541 .map_err(|_| "token uri is too long")?,542 })543 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;544545 let users = [(to.clone(), 1)]546 .into_iter()547 .collect::<BTreeMap<_, _>>()548 .try_into()549 .unwrap();550 <Pallet<T>>::create_item(551 self,552 &caller,553 CreateItemData::<T::CrossAccountId> { users, properties },554 &budget,555 )556 .map_err(dispatch_to_evm::<T>)?;557 Ok(true)558 }559560 561 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {562 Err("not implementable".into())563 }564}565566fn get_token_property<T: Config>(567 collection: &CollectionHandle<T>,568 token_id: u32,569 key: &up_data_structs::PropertyKey,570) -> Result<string> {571 collection.consume_store_reads(1)?;572 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))573 .map_err(|_| Error::Revert("Token properties not found".into()))?;574 if let Some(property) = properties.get(key) {575 return Ok(string::from_utf8_lossy(property).into());576 }577578 Err("Property tokenURI not found".into())579}580581fn get_token_permission<T: Config>(582 collection_id: CollectionId,583 key: &PropertyKey,584) -> Result<PropertyPermission> {585 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)586 .map_err(|_| Error::Revert("No permissions for collection".into()))?;587 let a = token_property_permissions588 .get(key)589 .map(Clone::clone)590 .ok_or_else(|| {591 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();592 Error::Revert(alloc::format!("No permission for key {}", key))593 })?;594 Ok(a)595}596597598#[solidity_interface(name = ERC721UniqueExtensions)]599impl<T: Config> RefungibleHandle<T> {600 601 602 603 604 605 606 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]607 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {608 let caller = T::CrossAccountId::from_eth(caller);609 let to = T::CrossAccountId::from_eth(to);610 let token = token_id.try_into()?;611 let budget = self612 .recorder613 .weight_calls_budget(<StructureWeight<T>>::find_parent());614615 let balance = balance(&self, token, &caller)?;616 ensure_single_owner(&self, token, balance)?;617618 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)619 .map_err(dispatch_to_evm::<T>)?;620 Ok(())621 }622623 624 625 626 627 628 629 630 #[weight(<SelfWeightOf<T>>::burn_from())]631 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {632 let caller = T::CrossAccountId::from_eth(caller);633 let from = T::CrossAccountId::from_eth(from);634 let token = token_id.try_into()?;635 let budget = self636 .recorder637 .weight_calls_budget(<StructureWeight<T>>::find_parent());638639 let balance = balance(&self, token, &caller)?;640 ensure_single_owner(&self, token, balance)?;641642 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)643 .map_err(dispatch_to_evm::<T>)?;644 Ok(())645 }646647 648 fn next_token_id(&self) -> Result<uint256> {649 self.consume_store_reads(1)?;650 Ok(<TokensMinted<T>>::get(self.id)651 .checked_add(1)652 .ok_or("item id overflow")?653 .into())654 }655656 657 658 659 660 661 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]662 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {663 let caller = T::CrossAccountId::from_eth(caller);664 let to = T::CrossAccountId::from_eth(to);665 let mut expected_index = <TokensMinted<T>>::get(self.id)666 .checked_add(1)667 .ok_or("item id overflow")?;668 let budget = self669 .recorder670 .weight_calls_budget(<StructureWeight<T>>::find_parent());671672 let total_tokens = token_ids.len();673 for id in token_ids.into_iter() {674 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;675 if id != expected_index {676 return Err("item id should be next".into());677 }678 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;679 }680 let users = [(to.clone(), 1)]681 .into_iter()682 .collect::<BTreeMap<_, _>>()683 .try_into()684 .unwrap();685 let create_item_data = CreateItemData::<T::CrossAccountId> {686 users,687 properties: CollectionPropertiesVec::default(),688 };689 let data = (0..total_tokens)690 .map(|_| create_item_data.clone())691 .collect();692693 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)694 .map_err(dispatch_to_evm::<T>)?;695 Ok(true)696 }697698 699 700 701 702 703 #[solidity(rename_selector = "mintBulkWithTokenURI")]704 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]705 fn mint_bulk_with_token_uri(706 &mut self,707 caller: caller,708 to: address,709 tokens: Vec<(uint256, string)>,710 ) -> Result<bool> {711 let key = key::url();712 let caller = T::CrossAccountId::from_eth(caller);713 let to = T::CrossAccountId::from_eth(to);714 let mut expected_index = <TokensMinted<T>>::get(self.id)715 .checked_add(1)716 .ok_or("item id overflow")?;717 let budget = self718 .recorder719 .weight_calls_budget(<StructureWeight<T>>::find_parent());720721 let mut data = Vec::with_capacity(tokens.len());722 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]723 .into_iter()724 .collect::<BTreeMap<_, _>>()725 .try_into()726 .unwrap();727 for (id, token_uri) in tokens {728 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;729 if id != expected_index {730 return Err("item id should be next".into());731 }732 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;733734 let mut properties = CollectionPropertiesVec::default();735 properties736 .try_push(Property {737 key: key.clone(),738 value: token_uri739 .into_bytes()740 .try_into()741 .map_err(|_| "token uri is too long")?,742 })743 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;744745 let create_item_data = CreateItemData::<T::CrossAccountId> {746 users: users.clone(),747 properties,748 };749 data.push(create_item_data);750 }751752 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)753 .map_err(dispatch_to_evm::<T>)?;754 Ok(true)755 }756757 758 759 760 fn token_contract_address(&self, token: uint256) -> Result<address> {761 Ok(T::EvmTokenAddressMapping::token_to_address(762 self.id,763 token.try_into().map_err(|_| "token id overflow")?,764 ))765 }766}767768#[solidity_interface(769 name = UniqueRefungible,770 is(771 ERC721,772 ERC721Metadata(if(this.supports_metadata())),773 ERC721Enumerable,774 ERC721UniqueExtensions,775 ERC721Mintable,776 ERC721Burnable,777 Collection(via(common_mut returns CollectionHandle<T>)),778 TokenProperties,779 )780)]781impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}782783784generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);785generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);786787impl<T: Config> CommonEvmHandler for RefungibleHandle<T>788where789 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,790{791 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");792 fn call(793 self,794 handle: &mut impl PrecompileHandle,795 ) -> Option<pallet_common::erc::PrecompileResult> {796 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)797 }798}