1234567891011121314151617extern crate alloc;18use core::{19 char::{REPLACEMENT_CHARACTER, decode_utf16},20 convert::TryInto,21};22use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};23use frame_support::BoundedVec;24use up_data_structs::{TokenId, SchemaVersion, PropertyPermission, PropertyKeyPermission, Property};25use pallet_evm_coder_substrate::dispatch_to_evm;26use sp_core::{H160, U256};27use sp_std::vec::Vec;28use pallet_common::{29 erc::{CommonEvmHandler, PrecompileResult, CollectionPropertiesCall},30 CollectionHandle,31};32use pallet_evm::account::CrossAccountId;33use pallet_evm_coder_substrate::call;34use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};3536use crate::{37 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,38 SelfWeightOf, weights::WeightInfo, TokenProperties,39};4041#[solidity_interface(name = "TokenProperties")]42impl<T: Config> NonfungibleHandle<T> {43 fn set_token_property_permission(44 &mut self,45 caller: caller,46 key: string,47 is_mutable: bool,48 collection_admin: bool,49 token_owner: bool,50 ) -> Result<()> {51 let caller = T::CrossAccountId::from_eth(caller);52 <Pallet<T>>::set_property_permission(53 self,54 &caller,55 PropertyKeyPermission {56 key: <Vec<u8>>::from(key)57 .try_into()58 .map_err(|_| "too long key")?,59 permission: PropertyPermission {60 mutable: is_mutable,61 collection_admin,62 token_owner,63 },64 },65 )66 .map_err(dispatch_to_evm::<T>)67 }6869 fn set_property(70 &mut self,71 caller: caller,72 token_id: uint256,73 key: string,74 value: bytes,75 ) -> Result<()> {76 let caller = T::CrossAccountId::from_eth(caller);77 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;78 let key = <Vec<u8>>::from(key)79 .try_into()80 .map_err(|_| "key too long")?;81 let value = value.try_into().map_err(|_| "value too long")?;8283 <Pallet<T>>::set_token_property(self, &caller, TokenId(token_id), Property { key, value })84 .map_err(dispatch_to_evm::<T>)85 }8687 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {88 let caller = T::CrossAccountId::from_eth(caller);89 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;90 let key = <Vec<u8>>::from(key)91 .try_into()92 .map_err(|_| "key too long")?;9394 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key)95 .map_err(dispatch_to_evm::<T>)96 }9798 99 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {100 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;101 let key = <Vec<u8>>::from(key)102 .try_into()103 .map_err(|_| "key too long")?;104105 let props = <TokenProperties<T>>::get((self.id, token_id));106 let prop = props.get(&key).ok_or("key not found")?;107108 Ok(prop.to_vec())109 }110}111112#[derive(ToLog)]113pub enum ERC721Events {114 Transfer {115 #[indexed]116 from: address,117 #[indexed]118 to: address,119 #[indexed]120 token_id: uint256,121 },122 Approval {123 #[indexed]124 owner: address,125 #[indexed]126 approved: address,127 #[indexed]128 token_id: uint256,129 },130 #[allow(dead_code)]131 ApprovalForAll {132 #[indexed]133 owner: address,134 #[indexed]135 operator: address,136 approved: bool,137 },138}139140#[derive(ToLog)]141pub enum ERC721MintableEvents {142 #[allow(dead_code)]143 MintingFinished {},144}145146#[solidity_interface(name = "ERC721Metadata")]147impl<T: Config> NonfungibleHandle<T> {148 fn name(&self) -> Result<string> {149 Ok(decode_utf16(self.name.iter().copied())150 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))151 .collect::<string>())152 }153154 fn symbol(&self) -> Result<string> {155 Ok(string::from_utf8_lossy(&self.token_prefix).into())156 }157158 159 #[solidity(rename_selector = "tokenURI")]160 fn token_uri(&self, token_id: uint256) -> Result<string> {161 self.consume_store_reads(1)?;162 let _token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;163 Ok(string::from_utf8_lossy(164 todo!()165 )166 .into())167 }168}169170#[solidity_interface(name = "ERC721Enumerable")]171impl<T: Config> NonfungibleHandle<T> {172 fn token_by_index(&self, index: uint256) -> Result<uint256> {173 Ok(index)174 }175176 177 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {178 179 Err("not implemented".into())180 }181182 fn total_supply(&self) -> Result<uint256> {183 self.consume_store_reads(1)?;184 Ok(<Pallet<T>>::total_supply(self).into())185 }186}187188#[solidity_interface(name = "ERC721", events(ERC721Events))]189impl<T: Config> NonfungibleHandle<T> {190 fn balance_of(&self, owner: address) -> Result<uint256> {191 self.consume_store_reads(1)?;192 let owner = T::CrossAccountId::from_eth(owner);193 let balance = <AccountBalance<T>>::get((self.id, owner));194 Ok(balance.into())195 }196 fn owner_of(&self, token_id: uint256) -> Result<address> {197 self.consume_store_reads(1)?;198 let token: TokenId = token_id.try_into()?;199 Ok(*<TokenData<T>>::get((self.id, token))200 .ok_or("token not found")?201 .owner202 .as_eth())203 }204 205 fn safe_transfer_from_with_data(206 &mut self,207 _from: address,208 _to: address,209 _token_id: uint256,210 _data: bytes,211 _value: value,212 ) -> Result<void> {213 214 Err("not implemented".into())215 }216 217 fn safe_transfer_from(218 &mut self,219 _from: address,220 _to: address,221 _token_id: uint256,222 _value: value,223 ) -> Result<void> {224 225 Err("not implemented".into())226 }227228 #[weight(<SelfWeightOf<T>>::transfer_from())]229 fn transfer_from(230 &mut self,231 caller: caller,232 from: address,233 to: address,234 token_id: uint256,235 _value: value,236 ) -> Result<void> {237 let caller = T::CrossAccountId::from_eth(caller);238 let from = T::CrossAccountId::from_eth(from);239 let to = T::CrossAccountId::from_eth(to);240 let token = token_id.try_into()?;241 let budget = self242 .recorder243 .weight_calls_budget(<StructureWeight<T>>::find_parent());244245 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)246 .map_err(dispatch_to_evm::<T>)?;247 Ok(())248 }249250 #[weight(<SelfWeightOf<T>>::approve())]251 fn approve(252 &mut self,253 caller: caller,254 approved: address,255 token_id: uint256,256 _value: value,257 ) -> Result<void> {258 let caller = T::CrossAccountId::from_eth(caller);259 let approved = T::CrossAccountId::from_eth(approved);260 let token = token_id.try_into()?;261262 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))263 .map_err(dispatch_to_evm::<T>)?;264 Ok(())265 }266267 268 fn set_approval_for_all(269 &mut self,270 _caller: caller,271 _operator: address,272 _approved: bool,273 ) -> Result<void> {274 275 Err("not implemented".into())276 }277278 279 fn get_approved(&self, _token_id: uint256) -> Result<address> {280 281 Err("not implemented".into())282 }283284 285 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {286 287 Err("not implemented".into())288 }289}290291#[solidity_interface(name = "ERC721Burnable")]292impl<T: Config> NonfungibleHandle<T> {293 #[weight(<SelfWeightOf<T>>::burn_item())]294 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {295 let caller = T::CrossAccountId::from_eth(caller);296 let token = token_id.try_into()?;297298 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;299 Ok(())300 }301}302303#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]304impl<T: Config> NonfungibleHandle<T> {305 fn minting_finished(&self) -> Result<bool> {306 Ok(false)307 }308309 310 311 #[weight(<SelfWeightOf<T>>::create_item())]312 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {313 let caller = T::CrossAccountId::from_eth(caller);314 let to = T::CrossAccountId::from_eth(to);315 let token_id: u32 = token_id.try_into()?;316 let budget = self317 .recorder318 .weight_calls_budget(<StructureWeight<T>>::find_parent());319320 if <TokensMinted<T>>::get(self.id)321 .checked_add(1)322 .ok_or("item id overflow")?323 != token_id324 {325 return Err("item id should be next".into());326 }327328 <Pallet<T>>::create_item(329 self,330 &caller,331 CreateItemData::<T> {332 properties: BoundedVec::default(),333 owner: to,334 },335 &budget,336 )337 .map_err(dispatch_to_evm::<T>)?;338339 Ok(true)340 }341342 343 344 #[solidity(rename_selector = "mintWithTokenURI")]345 #[weight(<SelfWeightOf<T>>::create_item())]346 fn mint_with_token_uri(347 &mut self,348 caller: caller,349 to: address,350 token_id: uint256,351 token_uri: string,352 ) -> Result<bool> {353 let caller = T::CrossAccountId::from_eth(caller);354 let to = T::CrossAccountId::from_eth(to);355 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;356 let budget = self357 .recorder358 .weight_calls_budget(<StructureWeight<T>>::find_parent());359360 if <TokensMinted<T>>::get(self.id)361 .checked_add(1)362 .ok_or("item id overflow")?363 != token_id364 {365 return Err("item id should be next".into());366 }367368 todo!("token uri");369370 <Pallet<T>>::create_item(371 self,372 &caller,373 CreateItemData::<T> {374 properties: BoundedVec::default(),375 owner: to,376 },377 &budget,378 )379 .map_err(dispatch_to_evm::<T>)?;380 Ok(true)381 }382383 384 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {385 Err("not implementable".into())386 }387}388389#[solidity_interface(name = "ERC721UniqueExtensions")]390impl<T: Config> NonfungibleHandle<T> {391 #[weight(<SelfWeightOf<T>>::transfer())]392 fn transfer(393 &mut self,394 caller: caller,395 to: address,396 token_id: uint256,397 _value: value,398 ) -> Result<void> {399 let caller = T::CrossAccountId::from_eth(caller);400 let to = T::CrossAccountId::from_eth(to);401 let token = token_id.try_into()?;402 let budget = self403 .recorder404 .weight_calls_budget(<StructureWeight<T>>::find_parent());405406 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;407 Ok(())408 }409410 #[weight(<SelfWeightOf<T>>::burn_from())]411 fn burn_from(412 &mut self,413 caller: caller,414 from: address,415 token_id: uint256,416 _value: value,417 ) -> Result<void> {418 let caller = T::CrossAccountId::from_eth(caller);419 let from = T::CrossAccountId::from_eth(from);420 let token = token_id.try_into()?;421 let budget = self422 .recorder423 .weight_calls_budget(<StructureWeight<T>>::find_parent());424425 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)426 .map_err(dispatch_to_evm::<T>)?;427 Ok(())428 }429430 fn next_token_id(&self) -> Result<uint256> {431 self.consume_store_reads(1)?;432 Ok(<TokensMinted<T>>::get(self.id)433 .checked_add(1)434 .ok_or("item id overflow")?435 .into())436 }437438 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]439 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {440 let caller = T::CrossAccountId::from_eth(caller);441 let to = T::CrossAccountId::from_eth(to);442 let mut expected_index = <TokensMinted<T>>::get(self.id)443 .checked_add(1)444 .ok_or("item id overflow")?;445 let budget = self446 .recorder447 .weight_calls_budget(<StructureWeight<T>>::find_parent());448449 let total_tokens = token_ids.len();450 for id in token_ids.into_iter() {451 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;452 if id != expected_index {453 return Err("item id should be next".into());454 }455 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;456 }457 let data = (0..total_tokens)458 .map(|_| CreateItemData::<T> {459 properties: BoundedVec::default(),460 owner: to.clone(),461 })462 .collect();463464 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)465 .map_err(dispatch_to_evm::<T>)?;466 Ok(true)467 }468469 #[solidity(rename_selector = "mintBulkWithTokenURI")]470 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]471 fn mint_bulk_with_token_uri(472 &mut self,473 caller: caller,474 to: address,475 tokens: Vec<(uint256, string)>,476 ) -> Result<bool> {477 let caller = T::CrossAccountId::from_eth(caller);478 let to = T::CrossAccountId::from_eth(to);479 let mut expected_index = <TokensMinted<T>>::get(self.id)480 .checked_add(1)481 .ok_or("item id overflow")?;482 let budget = self483 .recorder484 .weight_calls_budget(<StructureWeight<T>>::find_parent());485486 let mut data = Vec::with_capacity(tokens.len());487 for (id, token_uri) in tokens {488 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;489 if id != expected_index {490 return Err("item id should be next".into());491 }492 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;493494 todo!("token uri");495 data.push(CreateItemData::<T> {496 properties: BoundedVec::default(),497 owner: to.clone(),498 });499 }500501 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)502 .map_err(dispatch_to_evm::<T>)?;503 Ok(true)504 }505}506507#[solidity_interface(508 name = "UniqueNFT",509 is(510 ERC721,511 ERC721Metadata,512 ERC721Enumerable,513 ERC721UniqueExtensions,514 ERC721Mintable,515 ERC721Burnable,516 via("CollectionHandle<T>", common_mut, CollectionProperties),517 TokenProperties,518 )519)]520impl<T: Config> NonfungibleHandle<T> {}521522523generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);524generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);525526impl<T: Config> CommonEvmHandler for NonfungibleHandle<T> {527 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");528529 fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult> {530 call::<T, UniqueNFTCall<T>, _>(*source, self, value, input)531 }532}