1use core::char::{decode_utf16, REPLACEMENT_CHARACTER};2use evm_coder::{ToLog, execution::Result, generate_stubgen, solidity, solidity_interface, types::*};3use nft_data_structs::{CreateItemData, CreateNftData};4use core::convert::TryInto;5use crate::{6 Allowances, Module, Balance, CollectionHandle, CollectionMode, Config, NftItemList,7 ItemListIndex,8};9use frame_support::storage::{StorageMap, StorageDoubleMap};10use pallet_evm::AddressMapping;11use pallet_evm_coder_substrate::dispatch_to_evm;12use super::account::CrossAccountId;13use sp_std::{vec, vec::Vec};1415#[solidity_interface(name = "ERC165")]16impl<T: Config> CollectionHandle<T> {17 fn supports_interface(&self, interface_id: bytes4) -> Result<bool> {18 Ok(match self.mode {19 CollectionMode::Fungible(_) => UniqueFungibleCall::supports_interface(interface_id),20 CollectionMode::NFT => UniqueNFTCall::supports_interface(interface_id),21 _ => false,22 })23 }24}2526#[solidity_interface(name = "InlineNameSymbol")]27impl<T: Config> CollectionHandle<T> {28 fn name(&self) -> Result<string> {29 Ok(decode_utf16(self.name.iter().copied())30 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))31 .collect::<string>())32 }3334 fn symbol(&self) -> Result<string> {35 Ok(string::from_utf8_lossy(&self.token_prefix).into())36 }37}3839#[solidity_interface(name = "InlineTotalSupply")]40impl<T: Config> CollectionHandle<T> {41 fn total_supply(&self) -> Result<uint256> {42 43 Ok(0.into())44 }45}4647#[solidity_interface(name = "ERC721Metadata", inline_is(InlineNameSymbol))]48impl<T: Config> CollectionHandle<T> {49 #[solidity(rename_selector = "tokenURI")]50 fn token_uri(&self, token_id: uint256) -> Result<string> {51 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;52 Ok(string::from_utf8_lossy(53 &<NftItemList<T>>::get(self.id, token_id)54 .ok_or("token not found")?55 .const_data,56 )57 .into())58 }59}6061#[solidity_interface(name = "ERC721Enumerable", inline_is(InlineTotalSupply))]62impl<T: Config> CollectionHandle<T> {63 fn token_by_index(&self, index: uint256) -> Result<uint256> {64 Ok(index)65 }6667 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {68 69 Err("not implemented".into())70 }71}7273#[derive(ToLog)]74pub enum ERC721Events {75 Transfer {76 #[indexed]77 from: address,78 #[indexed]79 to: address,80 #[indexed]81 token_id: uint256,82 },83 Approval {84 #[indexed]85 owner: address,86 #[indexed]87 approved: address,88 #[indexed]89 token_id: uint256,90 },91 #[allow(dead_code)]92 ApprovalForAll {93 #[indexed]94 owner: address,95 #[indexed]96 operator: address,97 approved: bool,98 },99}100101#[solidity_interface(name = "ERC721", is(ERC165), events(ERC721Events))]102impl<T: Config> CollectionHandle<T> {103 #[solidity(rename_selector = "balanceOf")]104 fn balance_of_nft(&self, owner: address) -> Result<uint256> {105 let owner = T::EvmAddressMapping::into_account_id(owner);106 let balance = <Balance<T>>::get(self.id, owner);107 Ok(balance.into())108 }109 fn owner_of(&self, token_id: uint256) -> Result<address> {110 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;111 let token = <NftItemList<T>>::get(self.id, token_id).ok_or("unknown token")?;112 Ok(*token.owner.as_eth())113 }114 fn safe_transfer_from_with_data(115 &mut self,116 _from: address,117 _to: address,118 _token_id: uint256,119 _data: bytes,120 _value: value,121 ) -> Result<void> {122 123 Err("not implemented".into())124 }125 fn safe_transfer_from(126 &mut self,127 _from: address,128 _to: address,129 _token_id: uint256,130 _value: value,131 ) -> Result<void> {132 133 Err("not implemented".into())134 }135136 fn transfer_from(137 &mut self,138 caller: caller,139 from: address,140 to: address,141 token_id: uint256,142 _value: value,143 ) -> Result<void> {144 let caller = T::CrossAccountId::from_eth(caller);145 let from = T::CrossAccountId::from_eth(from);146 let to = T::CrossAccountId::from_eth(to);147 let token_id = token_id.try_into().map_err(|_| "token_id overflow")?;148149 <Module<T>>::transfer_from_internal(&caller, &from, &to, self, token_id, 1)150 .map_err(|_| "transferFrom error")?;151 Ok(())152 }153154 fn approve(155 &mut self,156 caller: caller,157 approved: address,158 token_id: uint256,159 _value: value,160 ) -> Result<void> {161 let caller = T::CrossAccountId::from_eth(caller);162 let approved = T::CrossAccountId::from_eth(approved);163 let token_id = token_id.try_into().map_err(|_| "token_id overflow")?;164165 <Module<T>>::approve_internal(&caller, &approved, self, token_id, 1)166 .map_err(|_| "approve internal")?;167 Ok(())168 }169170 fn set_approval_for_all(171 &mut self,172 _caller: caller,173 _operator: address,174 _approved: bool,175 ) -> Result<void> {176 177 Err("not implemented".into())178 }179180 fn get_approved(&self, _token_id: uint256) -> Result<address> {181 182 Err("not implemented".into())183 }184185 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {186 187 Err("not implemented".into())188 }189}190191#[solidity_interface(name = "ERC721Burnable")]192impl<T: Config> CollectionHandle<T> {193 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {194 let caller = T::CrossAccountId::from_eth(caller);195 let token_id = token_id.try_into().map_err(|_| "amount overflow")?;196197 <Module<T>>::burn_item_internal(&caller, &self, token_id, 1).map_err(|_| "burn error")?;198 Ok(())199 }200}201202#[derive(ToLog)]203pub enum ERC721MintableEvents {204 #[allow(dead_code)]205 MintingFinished {},206}207208#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]209impl<T: Config> CollectionHandle<T> {210 fn minting_finished(&self) -> Result<bool> {211 Ok(false)212 }213214 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {215 let caller = T::CrossAccountId::from_eth(caller);216 let to = T::CrossAccountId::from_eth(to);217 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;218 if <ItemListIndex>::get(self.id)219 .checked_add(1)220 .ok_or("item id overflow")?221 != token_id222 {223 return Err("item id should be next".into());224 }225226 <Module<T>>::create_item_internal(227 &caller,228 &self,229 &to,230 CreateItemData::NFT(CreateNftData {231 const_data: vec![].try_into().unwrap(),232 variable_data: vec![].try_into().unwrap(),233 }),234 )235 .map_err(|_| "mint error")?;236 Ok(true)237 }238239 #[solidity(rename_selector = "mintWithTokenURI")]240 fn mint_with_token_uri(241 &mut self,242 caller: caller,243 to: address,244 token_id: uint256,245 token_uri: string,246 ) -> Result<bool> {247 let caller = T::CrossAccountId::from_eth(caller);248 let to = T::CrossAccountId::from_eth(to);249 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;250 if <ItemListIndex>::get(self.id)251 .checked_add(1)252 .ok_or("item id overflow")?253 != token_id254 {255 return Err("item id should be next".into());256 }257258 <Module<T>>::create_item_internal(259 &caller,260 &self,261 &to,262 CreateItemData::NFT(CreateNftData {263 const_data: Vec::<u8>::from(token_uri)264 .try_into()265 .map_err(|_| "token uri is too long")?,266 variable_data: vec![].try_into().unwrap(),267 }),268 )269 .map_err(|_| "mint error")?;270 Ok(true)271 }272273 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {274 Err("not implementable".into())275 }276}277278#[solidity_interface(name = "ERC721UniqueExtensions")]279impl<T: Config> CollectionHandle<T> {280 #[solidity(rename_selector = "transfer")]281 fn transfer_nft(282 &mut self,283 caller: caller,284 to: address,285 token_id: uint256,286 _value: value,287 ) -> Result<void> {288 let caller = T::CrossAccountId::from_eth(caller);289 let to = T::CrossAccountId::from_eth(to);290 let token_id = token_id.try_into().map_err(|_| "amount overflow")?;291292 <Module<T>>::transfer_internal(&caller, &to, self, token_id, 1)293 .map_err(|_| "transfer error")?;294 Ok(())295 }296297 fn next_token_id(&self) -> Result<uint256> {298 Ok(ItemListIndex::get(self.id)299 .checked_add(1)300 .ok_or("item id overflow")?301 .into())302 }303304 fn set_variable_metadata(305 &mut self,306 caller: caller,307 token_id: uint256,308 data: bytes,309 ) -> Result<void> {310 let caller = T::CrossAccountId::from_eth(caller);311 let token_id = token_id.try_into().map_err(|_| "token id overflow")?;312313 <Module<T>>::set_variable_meta_data_internal(&caller, self, token_id, data)314 .map_err(dispatch_to_evm::<T>)?;315 Ok(())316 }317318 fn get_variable_metadata(&self, token_id: uint256) -> Result<bytes> {319 let token_id = token_id.try_into().map_err(|_| "token id overflow")?;320321 <Module<T>>::get_variable_metadata(self, token_id).map_err(dispatch_to_evm::<T>)322 }323324 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {325 let caller = T::CrossAccountId::from_eth(caller);326 let to = T::CrossAccountId::from_eth(to);327 let mut expected_index = <ItemListIndex>::get(self.id)328 .checked_add(1)329 .ok_or("item id overflow")?;330331 let total_tokens = token_ids.len();332 for id in token_ids.into_iter() {333 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;334 if id != expected_index {335 return Err("item id should be next".into());336 }337 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;338 }339340 let data = (0..total_tokens)341 .map(|_| {342 CreateItemData::NFT(CreateNftData {343 const_data: vec![].try_into().unwrap(),344 variable_data: vec![].try_into().unwrap(),345 })346 })347 .collect();348349 <Module<T>>::create_multiple_items_internal(&caller, self, &to, data)350 .map_err(dispatch_to_evm::<T>)?;351 Ok(true)352 }353354 #[solidity(rename_selector = "mintBulkWithTokenURI")]355 fn mint_bulk_with_token_uri(356 &mut self,357 caller: caller,358 to: address,359 tokens: Vec<(uint256, string)>,360 ) -> Result<bool> {361 let caller = T::CrossAccountId::from_eth(caller);362 let to = T::CrossAccountId::from_eth(to);363 let mut expected_index = <ItemListIndex>::get(self.id)364 .checked_add(1)365 .ok_or("item id overflow")?;366367 let mut data = Vec::with_capacity(tokens.len());368 for (id, token_uri) in tokens {369 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;370 if id != expected_index {371 panic!("item id should be next ({}) but got {}", expected_index, id);372 }373 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;374375 data.push(CreateItemData::NFT(CreateNftData {376 const_data: Vec::<u8>::from(token_uri)377 .try_into()378 .map_err(|_| "token uri is too long")?,379 variable_data: vec![].try_into().unwrap(),380 }));381 }382383 <Module<T>>::create_multiple_items_internal(&caller, self, &to, data)384 .map_err(dispatch_to_evm::<T>)?;385 Ok(true)386 }387}388389#[solidity_interface(390 name = "UniqueNFT",391 is(392 ERC165,393 ERC721,394 ERC721Metadata,395 ERC721Enumerable,396 ERC721UniqueExtensions,397 ERC721Mintable,398 ERC721Burnable,399 )400)]401impl<T: Config> CollectionHandle<T> {}402403#[derive(ToLog)]404pub enum ERC20Events {405 Transfer {406 #[indexed]407 from: address,408 #[indexed]409 to: address,410 value: uint256,411 },412 Approval {413 #[indexed]414 owner: address,415 #[indexed]416 spender: address,417 value: uint256,418 },419}420421#[solidity_interface(422 name = "ERC20",423 inline_is(InlineNameSymbol, InlineTotalSupply),424 events(ERC20Events)425)]426impl<T: Config> CollectionHandle<T> {427 fn decimals(&self) -> Result<uint8> {428 Ok(if let CollectionMode::Fungible(decimals) = &self.mode {429 *decimals430 } else {431 unreachable!()432 })433 }434 fn balance_of(&self, owner: address) -> Result<uint256> {435 let owner = T::EvmAddressMapping::into_account_id(owner);436 let balance = <Balance<T>>::get(self.id, owner);437 Ok(balance.into())438 }439 fn transfer(&mut self, caller: caller, to: address, amount: uint256) -> Result<bool> {440 let caller = T::CrossAccountId::from_eth(caller);441 let to = T::CrossAccountId::from_eth(to);442 let amount = amount.try_into().map_err(|_| "amount overflow")?;443444 <Module<T>>::transfer_internal(&caller, &to, self, 1, amount)445 .map_err(|_| "transfer error")?;446 Ok(true)447 }448 #[solidity(rename_selector = "transferFrom")]449 fn transfer_from_fungible(450 &mut self,451 caller: caller,452 from: address,453 to: address,454 amount: uint256,455 ) -> Result<bool> {456 let caller = T::CrossAccountId::from_eth(caller);457 let from = T::CrossAccountId::from_eth(from);458 let to = T::CrossAccountId::from_eth(to);459 let amount = amount.try_into().map_err(|_| "amount overflow")?;460461 <Module<T>>::transfer_from_internal(&caller, &from, &to, self, 1, amount)462 .map_err(|_| "transferFrom error")?;463 Ok(true)464 }465 #[solidity(rename_selector = "approve")]466 fn approve_fungible(467 &mut self,468 caller: caller,469 spender: address,470 amount: uint256,471 ) -> Result<bool> {472 let caller = T::CrossAccountId::from_eth(caller);473 let spender = T::CrossAccountId::from_eth(spender);474 let amount = amount.try_into().map_err(|_| "amount overflow")?;475476 <Module<T>>::approve_internal(&caller, &spender, self, 1, amount)477 .map_err(|_| "approve internal")?;478 Ok(true)479 }480 fn allowance(&self, owner: address, spender: address) -> Result<uint256> {481 let owner = T::CrossAccountId::from_eth(owner);482 let spender = T::CrossAccountId::from_eth(spender);483484 Ok(<Allowances<T>>::get(self.id, (1, owner.as_sub(), spender.as_sub())).into())485 }486}487488#[solidity_interface(name = "UniqueFungible", is(ERC165, ERC20))]489impl<T: Config> CollectionHandle<T> {}490491492generate_stubgen!(nft_impl, UniqueNFTCall, true);493generate_stubgen!(nft_iface, UniqueNFTCall, false);494495generate_stubgen!(fungible_impl, UniqueFungibleCall, true);496generate_stubgen!(fungible_iface, UniqueFungibleCall, false);