difftreelog
Cargo fmt
in: master
3 files changed
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -49,7 +49,7 @@
#[solidity_interface(name = "Collection")]
impl<T: Config> CollectionHandle<T>
where
- T::AccountId: From<[u8; 32]>
+ T::AccountId: From<[u8; 32]>,
{
fn set_collection_property(&mut self, caller: caller, key: string, value: bytes) -> Result<()> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -176,12 +176,15 @@
new_admin.to_big_endian(&mut new_admin_arr);
let account_id = T::AccountId::from(new_admin_arr);
let new_admin = T::CrossAccountId::from_sub(account_id);
- <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true)
- .map_err(dispatch_to_evm::<T>)?;
+ <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
- fn remove_collection_admin_substrate(&self, caller: caller, new_admin: uint256) -> Result<void> {
+ fn remove_collection_admin_substrate(
+ &self,
+ caller: caller,
+ new_admin: uint256,
+ ) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
let mut new_admin_arr: [u8; 32] = Default::default();
new_admin.to_big_endian(&mut new_admin_arr);
@@ -195,16 +198,14 @@
fn add_collection_admin(&self, caller: caller, new_admin: address) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
let new_admin = T::CrossAccountId::from_eth(new_admin);
- <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true)
- .map_err(dispatch_to_evm::<T>)?;
+ <Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
fn remove_admin(&self, caller: caller, admin: address) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
let admin = T::CrossAccountId::from_eth(admin);
- <Pallet<T>>::toggle_admin(self, &caller, &admin, false)
- .map_err(dispatch_to_evm::<T>)?;
+ <Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
@@ -233,9 +234,9 @@
true => {
let mut bv = OwnerRestrictedSet::new();
for i in collections {
- bv.try_insert(crate::eth::map_eth_to_id(&i).ok_or_else(|| Error::Revert(
- "Can't convert address into collection id".into(),
- ))?)
+ bv.try_insert(crate::eth::map_eth_to_id(&i).ok_or_else(|| {
+ Error::Revert("Can't convert address into collection id".into())
+ })?)
.map_err(|e| Error::Revert(format!("{:?}", e)))?;
}
NestingRule::OwnerRestricted (bv)
@@ -259,16 +260,14 @@
fn add_to_collection_allow_list(&self, caller: caller, user: address) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
let user = T::CrossAccountId::from_eth(user);
- <Pallet<T>>::toggle_allowlist(self, &caller, &user, true)
- .map_err(dispatch_to_evm::<T>)?;
+ <Pallet<T>>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
fn remove_from_collection_allow_list(&self, caller: caller, user: address) -> Result<void> {
let caller = T::CrossAccountId::from_eth(caller);
let user = T::CrossAccountId::from_eth(user);
- <Pallet<T>>::toggle_allowlist(self, &caller, &user, false)
- .map_err(dispatch_to_evm::<T>)?;
+ <Pallet<T>>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -152,17 +152,14 @@
via("CollectionHandle<T>", common_mut, Collection)
)
)]
-impl<T: Config> FungibleHandle<T>
-where
- T::AccountId: From<[u8; 32]>
-{}
+impl<T: Config> FungibleHandle<T> where T::AccountId: From<[u8; 32]> {}
generate_stubgen!(gen_impl, UniqueFungibleCall<()>, true);
generate_stubgen!(gen_iface, UniqueFungibleCall<()>, false);
impl<T: Config> CommonEvmHandler for FungibleHandle<T>
where
- T::AccountId: From<[u8; 32]>
+ T::AccountId: From<[u8; 32]>,
{
const CODE: &'static [u8] = include_bytes!("./stubs/UniqueFungible.raw");
pallets/nonfungible/src/erc.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617extern 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::{25 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,26 CollectionPropertiesVec,27};28use pallet_evm_coder_substrate::dispatch_to_evm;29use sp_std::vec::Vec;30use pallet_common::{31 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, token_uri_key},32 CollectionHandle, CollectionPropertyPermissions,33};34use pallet_evm::{account::CrossAccountId, PrecompileHandle};35use pallet_evm_coder_substrate::call;36use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};3738use crate::{39 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,40 SelfWeightOf, weights::WeightInfo, TokenProperties,41};4243#[solidity_interface(name = "TokenProperties")]44impl<T: Config> NonfungibleHandle<T> {45 fn set_token_property_permission(46 &mut self,47 caller: caller,48 key: string,49 is_mutable: bool,50 collection_admin: bool,51 token_owner: bool,52 ) -> Result<()> {53 let caller = T::CrossAccountId::from_eth(caller);54 <Pallet<T>>::set_property_permission(55 self,56 &caller,57 PropertyKeyPermission {58 key: <Vec<u8>>::from(key)59 .try_into()60 .map_err(|_| "too long key")?,61 permission: PropertyPermission {62 mutable: is_mutable,63 collection_admin,64 token_owner,65 },66 },67 )68 .map_err(dispatch_to_evm::<T>)69 }7071 fn set_property(72 &mut self,73 caller: caller,74 token_id: uint256,75 key: string,76 value: bytes,77 ) -> Result<()> {78 let caller = T::CrossAccountId::from_eth(caller);79 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;80 let key = <Vec<u8>>::from(key)81 .try_into()82 .map_err(|_| "key too long")?;83 let value = value.try_into().map_err(|_| "value too long")?;8485 <Pallet<T>>::set_token_property(86 self,87 &caller,88 TokenId(token_id),89 Property { key, value },90 false,91 )92 .map_err(dispatch_to_evm::<T>)93 }9495 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {96 let caller = T::CrossAccountId::from_eth(caller);97 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;98 let key = <Vec<u8>>::from(key)99 .try_into()100 .map_err(|_| "key too long")?;101102 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key)103 .map_err(dispatch_to_evm::<T>)104 }105106 /// Throws error if key not found107 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {108 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;109 let key = <Vec<u8>>::from(key)110 .try_into()111 .map_err(|_| "key too long")?;112113 let props = <TokenProperties<T>>::get((self.id, token_id));114 let prop = props.get(&key).ok_or("key not found")?;115116 Ok(prop.to_vec())117 }118}119120#[derive(ToLog)]121pub enum ERC721Events {122 Transfer {123 #[indexed]124 from: address,125 #[indexed]126 to: address,127 #[indexed]128 token_id: uint256,129 },130 Approval {131 #[indexed]132 owner: address,133 #[indexed]134 approved: address,135 #[indexed]136 token_id: uint256,137 },138 #[allow(dead_code)]139 ApprovalForAll {140 #[indexed]141 owner: address,142 #[indexed]143 operator: address,144 approved: bool,145 },146}147148#[derive(ToLog)]149pub enum ERC721MintableEvents {150 #[allow(dead_code)]151 MintingFinished {},152}153154#[solidity_interface(name = "ERC721Metadata")]155impl<T: Config> NonfungibleHandle<T> {156 fn name(&self) -> Result<string> {157 Ok(decode_utf16(self.name.iter().copied())158 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))159 .collect::<string>())160 }161162 fn symbol(&self) -> Result<string> {163 Ok(string::from_utf8_lossy(&self.token_prefix).into())164 }165166 /// Returns token's const_metadata167 #[solidity(rename_selector = "tokenURI")]168 fn token_uri(&self, token_id: uint256) -> Result<string> {169 let key = token_uri_key();170 if !has_token_permission::<T>(self.id, &key) {171 return Err("No tokenURI permission".into());172 }173174 self.consume_store_reads(1)?;175 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;176177 let properties = <TokenProperties<T>>::try_get((self.id, token_id))178 .map_err(|_| Error::Revert("Token properties not found".into()))?;179 if let Some(property) = properties.get(&key) {180 return Ok(string::from_utf8_lossy(property).into());181 }182183 Err("Property tokenURI not found".into())184 }185}186187#[solidity_interface(name = "ERC721Enumerable")]188impl<T: Config> NonfungibleHandle<T> {189 fn token_by_index(&self, index: uint256) -> Result<uint256> {190 Ok(index)191 }192193 /// Not implemented194 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {195 // TODO: Not implemetable196 Err("not implemented".into())197 }198199 fn total_supply(&self) -> Result<uint256> {200 self.consume_store_reads(1)?;201 Ok(<Pallet<T>>::total_supply(self).into())202 }203}204205#[solidity_interface(name = "ERC721", events(ERC721Events))]206impl<T: Config> NonfungibleHandle<T> {207 fn balance_of(&self, owner: address) -> Result<uint256> {208 self.consume_store_reads(1)?;209 let owner = T::CrossAccountId::from_eth(owner);210 let balance = <AccountBalance<T>>::get((self.id, owner));211 Ok(balance.into())212 }213 fn owner_of(&self, token_id: uint256) -> Result<address> {214 self.consume_store_reads(1)?;215 let token: TokenId = token_id.try_into()?;216 Ok(*<TokenData<T>>::get((self.id, token))217 .ok_or("token not found")?218 .owner219 .as_eth())220 }221 /// Not implemented222 fn safe_transfer_from_with_data(223 &mut self,224 _from: address,225 _to: address,226 _token_id: uint256,227 _data: bytes,228 _value: value,229 ) -> Result<void> {230 // TODO: Not implemetable231 Err("not implemented".into())232 }233 /// Not implemented234 fn safe_transfer_from(235 &mut self,236 _from: address,237 _to: address,238 _token_id: uint256,239 _value: value,240 ) -> Result<void> {241 // TODO: Not implemetable242 Err("not implemented".into())243 }244245 #[weight(<SelfWeightOf<T>>::transfer_from())]246 fn transfer_from(247 &mut self,248 caller: caller,249 from: address,250 to: address,251 token_id: uint256,252 _value: value,253 ) -> Result<void> {254 let caller = T::CrossAccountId::from_eth(caller);255 let from = T::CrossAccountId::from_eth(from);256 let to = T::CrossAccountId::from_eth(to);257 let token = token_id.try_into()?;258 let budget = self259 .recorder260 .weight_calls_budget(<StructureWeight<T>>::find_parent());261262 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)263 .map_err(dispatch_to_evm::<T>)?;264 Ok(())265 }266267 #[weight(<SelfWeightOf<T>>::approve())]268 fn approve(269 &mut self,270 caller: caller,271 approved: address,272 token_id: uint256,273 _value: value,274 ) -> Result<void> {275 let caller = T::CrossAccountId::from_eth(caller);276 let approved = T::CrossAccountId::from_eth(approved);277 let token = token_id.try_into()?;278279 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))280 .map_err(dispatch_to_evm::<T>)?;281 Ok(())282 }283284 /// Not implemented285 fn set_approval_for_all(286 &mut self,287 _caller: caller,288 _operator: address,289 _approved: bool,290 ) -> Result<void> {291 // TODO: Not implemetable292 Err("not implemented".into())293 }294295 /// Not implemented296 fn get_approved(&self, _token_id: uint256) -> Result<address> {297 // TODO: Not implemetable298 Err("not implemented".into())299 }300301 /// Not implemented302 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {303 // TODO: Not implemetable304 Err("not implemented".into())305 }306}307308#[solidity_interface(name = "ERC721Burnable")]309impl<T: Config> NonfungibleHandle<T> {310 #[weight(<SelfWeightOf<T>>::burn_item())]311 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {312 let caller = T::CrossAccountId::from_eth(caller);313 let token = token_id.try_into()?;314315 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;316 Ok(())317 }318}319320#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]321impl<T: Config> NonfungibleHandle<T> {322 fn minting_finished(&self) -> Result<bool> {323 Ok(false)324 }325326 /// `token_id` should be obtained with `next_token_id` method,327 /// unlike standard, you can't specify it manually328 #[weight(<SelfWeightOf<T>>::create_item())]329 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {330 let caller = T::CrossAccountId::from_eth(caller);331 let to = T::CrossAccountId::from_eth(to);332 let token_id: u32 = token_id.try_into()?;333 let budget = self334 .recorder335 .weight_calls_budget(<StructureWeight<T>>::find_parent());336337 if <TokensMinted<T>>::get(self.id)338 .checked_add(1)339 .ok_or("item id overflow")?340 != token_id341 {342 return Err("item id should be next".into());343 }344345 <Pallet<T>>::create_item(346 self,347 &caller,348 CreateItemData::<T> {349 properties: BoundedVec::default(),350 owner: to,351 },352 &budget,353 )354 .map_err(dispatch_to_evm::<T>)?;355356 Ok(true)357 }358359 /// `token_id` should be obtained with `next_token_id` method,360 /// unlike standard, you can't specify it manually361 #[solidity(rename_selector = "mintWithTokenURI")]362 #[weight(<SelfWeightOf<T>>::create_item())]363 fn mint_with_token_uri(364 &mut self,365 caller: caller,366 to: address,367 token_id: uint256,368 token_uri: string,369 ) -> Result<bool> {370 let key = token_uri_key();371 let permission = get_token_permission::<T>(self.id, &key)?;372 if !permission.collection_admin {373 return Err("Operation is not allowed".into());374 }375376 let caller = T::CrossAccountId::from_eth(caller);377 let to = T::CrossAccountId::from_eth(to);378 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;379 let budget = self380 .recorder381 .weight_calls_budget(<StructureWeight<T>>::find_parent());382383 if <TokensMinted<T>>::get(self.id)384 .checked_add(1)385 .ok_or("item id overflow")?386 != token_id387 {388 return Err("item id should be next".into());389 }390391 let mut properties = CollectionPropertiesVec::default();392 properties393 .try_push(Property {394 key,395 value: token_uri396 .into_bytes()397 .try_into()398 .map_err(|_| "token uri is too long")?,399 })400 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;401402 <Pallet<T>>::create_item(403 self,404 &caller,405 CreateItemData::<T> {406 properties,407 owner: to,408 },409 &budget,410 )411 .map_err(dispatch_to_evm::<T>)?;412 Ok(true)413 }414415 /// Not implemented416 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {417 Err("not implementable".into())418 }419}420421fn get_token_permission<T: Config>(422 collection_id: CollectionId,423 key: &PropertyKey,424) -> Result<PropertyPermission> {425 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)426 .map_err(|_| Error::Revert("No permissions for collection".into()))?;427 let a = token_property_permissions428 .get(key)429 .map(|p| p.clone())430 .ok_or_else(|| Error::Revert("No permission".into()))?;431 Ok(a)432}433434fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {435 if let Ok(token_property_permissions) =436 CollectionPropertyPermissions::<T>::try_get(collection_id)437 {438 return token_property_permissions.contains_key(key);439 }440441 false442}443444#[solidity_interface(name = "ERC721UniqueExtensions")]445impl<T: Config> NonfungibleHandle<T> {446 #[weight(<SelfWeightOf<T>>::transfer())]447 fn transfer(448 &mut self,449 caller: caller,450 to: address,451 token_id: uint256,452 _value: value,453 ) -> Result<void> {454 let caller = T::CrossAccountId::from_eth(caller);455 let to = T::CrossAccountId::from_eth(to);456 let token = token_id.try_into()?;457 let budget = self458 .recorder459 .weight_calls_budget(<StructureWeight<T>>::find_parent());460461 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;462 Ok(())463 }464465 #[weight(<SelfWeightOf<T>>::burn_from())]466 fn burn_from(467 &mut self,468 caller: caller,469 from: address,470 token_id: uint256,471 _value: value,472 ) -> Result<void> {473 let caller = T::CrossAccountId::from_eth(caller);474 let from = T::CrossAccountId::from_eth(from);475 let token = token_id.try_into()?;476 let budget = self477 .recorder478 .weight_calls_budget(<StructureWeight<T>>::find_parent());479480 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)481 .map_err(dispatch_to_evm::<T>)?;482 Ok(())483 }484485 fn next_token_id(&self) -> Result<uint256> {486 self.consume_store_reads(1)?;487 Ok(<TokensMinted<T>>::get(self.id)488 .checked_add(1)489 .ok_or("item id overflow")?490 .into())491 }492493 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]494 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {495 let caller = T::CrossAccountId::from_eth(caller);496 let to = T::CrossAccountId::from_eth(to);497 let mut expected_index = <TokensMinted<T>>::get(self.id)498 .checked_add(1)499 .ok_or("item id overflow")?;500 let budget = self501 .recorder502 .weight_calls_budget(<StructureWeight<T>>::find_parent());503504 let total_tokens = token_ids.len();505 for id in token_ids.into_iter() {506 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;507 if id != expected_index {508 return Err("item id should be next".into());509 }510 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;511 }512 let data = (0..total_tokens)513 .map(|_| CreateItemData::<T> {514 properties: BoundedVec::default(),515 owner: to.clone(),516 })517 .collect();518519 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)520 .map_err(dispatch_to_evm::<T>)?;521 Ok(true)522 }523524 #[solidity(rename_selector = "mintBulkWithTokenURI")]525 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]526 fn mint_bulk_with_token_uri(527 &mut self,528 caller: caller,529 to: address,530 tokens: Vec<(uint256, string)>,531 ) -> Result<bool> {532 let key = token_uri_key();533 let caller = T::CrossAccountId::from_eth(caller);534 let to = T::CrossAccountId::from_eth(to);535 let mut expected_index = <TokensMinted<T>>::get(self.id)536 .checked_add(1)537 .ok_or("item id overflow")?;538 let budget = self539 .recorder540 .weight_calls_budget(<StructureWeight<T>>::find_parent());541542 let mut data = Vec::with_capacity(tokens.len());543 for (id, token_uri) in tokens {544 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;545 if id != expected_index {546 return Err("item id should be next".into());547 }548 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;549550 let mut properties = CollectionPropertiesVec::default();551 properties552 .try_push(Property {553 key: key.clone(),554 value: token_uri555 .into_bytes()556 .try_into()557 .map_err(|_| "token uri is too long")?,558 })559 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;560561 data.push(CreateItemData::<T> {562 properties,563 owner: to.clone(),564 });565 }566567 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)568 .map_err(dispatch_to_evm::<T>)?;569 Ok(true)570 }571}572573#[solidity_interface(574 name = "UniqueNFT",575 is(576 ERC721,577 ERC721Metadata,578 ERC721Enumerable,579 ERC721UniqueExtensions,580 ERC721Mintable,581 ERC721Burnable,582 via("CollectionHandle<T>", common_mut, Collection),583 TokenProperties,584 )585)]586impl<T: Config> NonfungibleHandle<T>587where588 T::AccountId: From<[u8; 32]>589{}590591// Not a tests, but code generators592generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);593generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);594595impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>596where597 T::AccountId: From<[u8; 32]>598{599 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");600601 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {602 call::<T, UniqueNFTCall<T>, _, _>(handle, self)603 }604}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617extern 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::{25 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,26 CollectionPropertiesVec,27};28use pallet_evm_coder_substrate::dispatch_to_evm;29use sp_std::vec::Vec;30use pallet_common::{31 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, token_uri_key},32 CollectionHandle, CollectionPropertyPermissions,33};34use pallet_evm::{account::CrossAccountId, PrecompileHandle};35use pallet_evm_coder_substrate::call;36use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};3738use crate::{39 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,40 SelfWeightOf, weights::WeightInfo, TokenProperties,41};4243#[solidity_interface(name = "TokenProperties")]44impl<T: Config> NonfungibleHandle<T> {45 fn set_token_property_permission(46 &mut self,47 caller: caller,48 key: string,49 is_mutable: bool,50 collection_admin: bool,51 token_owner: bool,52 ) -> Result<()> {53 let caller = T::CrossAccountId::from_eth(caller);54 <Pallet<T>>::set_property_permission(55 self,56 &caller,57 PropertyKeyPermission {58 key: <Vec<u8>>::from(key)59 .try_into()60 .map_err(|_| "too long key")?,61 permission: PropertyPermission {62 mutable: is_mutable,63 collection_admin,64 token_owner,65 },66 },67 )68 .map_err(dispatch_to_evm::<T>)69 }7071 fn set_property(72 &mut self,73 caller: caller,74 token_id: uint256,75 key: string,76 value: bytes,77 ) -> Result<()> {78 let caller = T::CrossAccountId::from_eth(caller);79 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;80 let key = <Vec<u8>>::from(key)81 .try_into()82 .map_err(|_| "key too long")?;83 let value = value.try_into().map_err(|_| "value too long")?;8485 <Pallet<T>>::set_token_property(86 self,87 &caller,88 TokenId(token_id),89 Property { key, value },90 false,91 )92 .map_err(dispatch_to_evm::<T>)93 }9495 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {96 let caller = T::CrossAccountId::from_eth(caller);97 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;98 let key = <Vec<u8>>::from(key)99 .try_into()100 .map_err(|_| "key too long")?;101102 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key)103 .map_err(dispatch_to_evm::<T>)104 }105106 /// Throws error if key not found107 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {108 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;109 let key = <Vec<u8>>::from(key)110 .try_into()111 .map_err(|_| "key too long")?;112113 let props = <TokenProperties<T>>::get((self.id, token_id));114 let prop = props.get(&key).ok_or("key not found")?;115116 Ok(prop.to_vec())117 }118}119120#[derive(ToLog)]121pub enum ERC721Events {122 Transfer {123 #[indexed]124 from: address,125 #[indexed]126 to: address,127 #[indexed]128 token_id: uint256,129 },130 Approval {131 #[indexed]132 owner: address,133 #[indexed]134 approved: address,135 #[indexed]136 token_id: uint256,137 },138 #[allow(dead_code)]139 ApprovalForAll {140 #[indexed]141 owner: address,142 #[indexed]143 operator: address,144 approved: bool,145 },146}147148#[derive(ToLog)]149pub enum ERC721MintableEvents {150 #[allow(dead_code)]151 MintingFinished {},152}153154#[solidity_interface(name = "ERC721Metadata")]155impl<T: Config> NonfungibleHandle<T> {156 fn name(&self) -> Result<string> {157 Ok(decode_utf16(self.name.iter().copied())158 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))159 .collect::<string>())160 }161162 fn symbol(&self) -> Result<string> {163 Ok(string::from_utf8_lossy(&self.token_prefix).into())164 }165166 /// Returns token's const_metadata167 #[solidity(rename_selector = "tokenURI")]168 fn token_uri(&self, token_id: uint256) -> Result<string> {169 let key = token_uri_key();170 if !has_token_permission::<T>(self.id, &key) {171 return Err("No tokenURI permission".into());172 }173174 self.consume_store_reads(1)?;175 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;176177 let properties = <TokenProperties<T>>::try_get((self.id, token_id))178 .map_err(|_| Error::Revert("Token properties not found".into()))?;179 if let Some(property) = properties.get(&key) {180 return Ok(string::from_utf8_lossy(property).into());181 }182183 Err("Property tokenURI not found".into())184 }185}186187#[solidity_interface(name = "ERC721Enumerable")]188impl<T: Config> NonfungibleHandle<T> {189 fn token_by_index(&self, index: uint256) -> Result<uint256> {190 Ok(index)191 }192193 /// Not implemented194 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {195 // TODO: Not implemetable196 Err("not implemented".into())197 }198199 fn total_supply(&self) -> Result<uint256> {200 self.consume_store_reads(1)?;201 Ok(<Pallet<T>>::total_supply(self).into())202 }203}204205#[solidity_interface(name = "ERC721", events(ERC721Events))]206impl<T: Config> NonfungibleHandle<T> {207 fn balance_of(&self, owner: address) -> Result<uint256> {208 self.consume_store_reads(1)?;209 let owner = T::CrossAccountId::from_eth(owner);210 let balance = <AccountBalance<T>>::get((self.id, owner));211 Ok(balance.into())212 }213 fn owner_of(&self, token_id: uint256) -> Result<address> {214 self.consume_store_reads(1)?;215 let token: TokenId = token_id.try_into()?;216 Ok(*<TokenData<T>>::get((self.id, token))217 .ok_or("token not found")?218 .owner219 .as_eth())220 }221 /// Not implemented222 fn safe_transfer_from_with_data(223 &mut self,224 _from: address,225 _to: address,226 _token_id: uint256,227 _data: bytes,228 _value: value,229 ) -> Result<void> {230 // TODO: Not implemetable231 Err("not implemented".into())232 }233 /// Not implemented234 fn safe_transfer_from(235 &mut self,236 _from: address,237 _to: address,238 _token_id: uint256,239 _value: value,240 ) -> Result<void> {241 // TODO: Not implemetable242 Err("not implemented".into())243 }244245 #[weight(<SelfWeightOf<T>>::transfer_from())]246 fn transfer_from(247 &mut self,248 caller: caller,249 from: address,250 to: address,251 token_id: uint256,252 _value: value,253 ) -> Result<void> {254 let caller = T::CrossAccountId::from_eth(caller);255 let from = T::CrossAccountId::from_eth(from);256 let to = T::CrossAccountId::from_eth(to);257 let token = token_id.try_into()?;258 let budget = self259 .recorder260 .weight_calls_budget(<StructureWeight<T>>::find_parent());261262 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)263 .map_err(dispatch_to_evm::<T>)?;264 Ok(())265 }266267 #[weight(<SelfWeightOf<T>>::approve())]268 fn approve(269 &mut self,270 caller: caller,271 approved: address,272 token_id: uint256,273 _value: value,274 ) -> Result<void> {275 let caller = T::CrossAccountId::from_eth(caller);276 let approved = T::CrossAccountId::from_eth(approved);277 let token = token_id.try_into()?;278279 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))280 .map_err(dispatch_to_evm::<T>)?;281 Ok(())282 }283284 /// Not implemented285 fn set_approval_for_all(286 &mut self,287 _caller: caller,288 _operator: address,289 _approved: bool,290 ) -> Result<void> {291 // TODO: Not implemetable292 Err("not implemented".into())293 }294295 /// Not implemented296 fn get_approved(&self, _token_id: uint256) -> Result<address> {297 // TODO: Not implemetable298 Err("not implemented".into())299 }300301 /// Not implemented302 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {303 // TODO: Not implemetable304 Err("not implemented".into())305 }306}307308#[solidity_interface(name = "ERC721Burnable")]309impl<T: Config> NonfungibleHandle<T> {310 #[weight(<SelfWeightOf<T>>::burn_item())]311 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {312 let caller = T::CrossAccountId::from_eth(caller);313 let token = token_id.try_into()?;314315 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;316 Ok(())317 }318}319320#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]321impl<T: Config> NonfungibleHandle<T> {322 fn minting_finished(&self) -> Result<bool> {323 Ok(false)324 }325326 /// `token_id` should be obtained with `next_token_id` method,327 /// unlike standard, you can't specify it manually328 #[weight(<SelfWeightOf<T>>::create_item())]329 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {330 let caller = T::CrossAccountId::from_eth(caller);331 let to = T::CrossAccountId::from_eth(to);332 let token_id: u32 = token_id.try_into()?;333 let budget = self334 .recorder335 .weight_calls_budget(<StructureWeight<T>>::find_parent());336337 if <TokensMinted<T>>::get(self.id)338 .checked_add(1)339 .ok_or("item id overflow")?340 != token_id341 {342 return Err("item id should be next".into());343 }344345 <Pallet<T>>::create_item(346 self,347 &caller,348 CreateItemData::<T> {349 properties: BoundedVec::default(),350 owner: to,351 },352 &budget,353 )354 .map_err(dispatch_to_evm::<T>)?;355356 Ok(true)357 }358359 /// `token_id` should be obtained with `next_token_id` method,360 /// unlike standard, you can't specify it manually361 #[solidity(rename_selector = "mintWithTokenURI")]362 #[weight(<SelfWeightOf<T>>::create_item())]363 fn mint_with_token_uri(364 &mut self,365 caller: caller,366 to: address,367 token_id: uint256,368 token_uri: string,369 ) -> Result<bool> {370 let key = token_uri_key();371 let permission = get_token_permission::<T>(self.id, &key)?;372 if !permission.collection_admin {373 return Err("Operation is not allowed".into());374 }375376 let caller = T::CrossAccountId::from_eth(caller);377 let to = T::CrossAccountId::from_eth(to);378 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;379 let budget = self380 .recorder381 .weight_calls_budget(<StructureWeight<T>>::find_parent());382383 if <TokensMinted<T>>::get(self.id)384 .checked_add(1)385 .ok_or("item id overflow")?386 != token_id387 {388 return Err("item id should be next".into());389 }390391 let mut properties = CollectionPropertiesVec::default();392 properties393 .try_push(Property {394 key,395 value: token_uri396 .into_bytes()397 .try_into()398 .map_err(|_| "token uri is too long")?,399 })400 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;401402 <Pallet<T>>::create_item(403 self,404 &caller,405 CreateItemData::<T> {406 properties,407 owner: to,408 },409 &budget,410 )411 .map_err(dispatch_to_evm::<T>)?;412 Ok(true)413 }414415 /// Not implemented416 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {417 Err("not implementable".into())418 }419}420421fn get_token_permission<T: Config>(422 collection_id: CollectionId,423 key: &PropertyKey,424) -> Result<PropertyPermission> {425 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)426 .map_err(|_| Error::Revert("No permissions for collection".into()))?;427 let a = token_property_permissions428 .get(key)429 .map(|p| p.clone())430 .ok_or_else(|| Error::Revert("No permission".into()))?;431 Ok(a)432}433434fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {435 if let Ok(token_property_permissions) =436 CollectionPropertyPermissions::<T>::try_get(collection_id)437 {438 return token_property_permissions.contains_key(key);439 }440441 false442}443444#[solidity_interface(name = "ERC721UniqueExtensions")]445impl<T: Config> NonfungibleHandle<T> {446 #[weight(<SelfWeightOf<T>>::transfer())]447 fn transfer(448 &mut self,449 caller: caller,450 to: address,451 token_id: uint256,452 _value: value,453 ) -> Result<void> {454 let caller = T::CrossAccountId::from_eth(caller);455 let to = T::CrossAccountId::from_eth(to);456 let token = token_id.try_into()?;457 let budget = self458 .recorder459 .weight_calls_budget(<StructureWeight<T>>::find_parent());460461 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;462 Ok(())463 }464465 #[weight(<SelfWeightOf<T>>::burn_from())]466 fn burn_from(467 &mut self,468 caller: caller,469 from: address,470 token_id: uint256,471 _value: value,472 ) -> Result<void> {473 let caller = T::CrossAccountId::from_eth(caller);474 let from = T::CrossAccountId::from_eth(from);475 let token = token_id.try_into()?;476 let budget = self477 .recorder478 .weight_calls_budget(<StructureWeight<T>>::find_parent());479480 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)481 .map_err(dispatch_to_evm::<T>)?;482 Ok(())483 }484485 fn next_token_id(&self) -> Result<uint256> {486 self.consume_store_reads(1)?;487 Ok(<TokensMinted<T>>::get(self.id)488 .checked_add(1)489 .ok_or("item id overflow")?490 .into())491 }492493 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]494 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {495 let caller = T::CrossAccountId::from_eth(caller);496 let to = T::CrossAccountId::from_eth(to);497 let mut expected_index = <TokensMinted<T>>::get(self.id)498 .checked_add(1)499 .ok_or("item id overflow")?;500 let budget = self501 .recorder502 .weight_calls_budget(<StructureWeight<T>>::find_parent());503504 let total_tokens = token_ids.len();505 for id in token_ids.into_iter() {506 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;507 if id != expected_index {508 return Err("item id should be next".into());509 }510 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;511 }512 let data = (0..total_tokens)513 .map(|_| CreateItemData::<T> {514 properties: BoundedVec::default(),515 owner: to.clone(),516 })517 .collect();518519 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)520 .map_err(dispatch_to_evm::<T>)?;521 Ok(true)522 }523524 #[solidity(rename_selector = "mintBulkWithTokenURI")]525 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]526 fn mint_bulk_with_token_uri(527 &mut self,528 caller: caller,529 to: address,530 tokens: Vec<(uint256, string)>,531 ) -> Result<bool> {532 let key = token_uri_key();533 let caller = T::CrossAccountId::from_eth(caller);534 let to = T::CrossAccountId::from_eth(to);535 let mut expected_index = <TokensMinted<T>>::get(self.id)536 .checked_add(1)537 .ok_or("item id overflow")?;538 let budget = self539 .recorder540 .weight_calls_budget(<StructureWeight<T>>::find_parent());541542 let mut data = Vec::with_capacity(tokens.len());543 for (id, token_uri) in tokens {544 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;545 if id != expected_index {546 return Err("item id should be next".into());547 }548 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;549550 let mut properties = CollectionPropertiesVec::default();551 properties552 .try_push(Property {553 key: key.clone(),554 value: token_uri555 .into_bytes()556 .try_into()557 .map_err(|_| "token uri is too long")?,558 })559 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;560561 data.push(CreateItemData::<T> {562 properties,563 owner: to.clone(),564 });565 }566567 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)568 .map_err(dispatch_to_evm::<T>)?;569 Ok(true)570 }571}572573#[solidity_interface(574 name = "UniqueNFT",575 is(576 ERC721,577 ERC721Metadata,578 ERC721Enumerable,579 ERC721UniqueExtensions,580 ERC721Mintable,581 ERC721Burnable,582 via("CollectionHandle<T>", common_mut, Collection),583 TokenProperties,584 )585)]586impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> {}587588// Not a tests, but code generators589generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);590generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);591592impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>593where594 T::AccountId: From<[u8; 32]>,595{596 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");597598 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {599 call::<T, UniqueNFTCall<T>, _, _>(handle, self)600 }601}