difftreelog
feat delegate erc call to other struct
in: master
9 files changed
crates/evm-coder-macros/src/solidity_interface.rsdiffbeforeafterboth--- a/crates/evm-coder-macros/src/solidity_interface.rs
+++ b/crates/evm-coder-macros/src/solidity_interface.rs
@@ -23,6 +23,7 @@
use syn::{
Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,
MetaNameValue, NestedMeta, PatType, Path, PathArguments, ReturnType, Type, spanned::Spanned,
+ parse_str,
};
use crate::{
@@ -35,16 +36,21 @@
name: Ident,
pascal_call_name: Ident,
snake_call_name: Ident,
+ via: Option<(Type, Ident)>,
}
impl Is {
- fn try_from(path: &Path) -> syn::Result<Self> {
+ fn new_via(path: &Path, via: Option<(Type, Ident)>) -> syn::Result<Self> {
let name = parse_ident_from_path(path, false)?.clone();
Ok(Self {
pascal_call_name: pascal_ident_to_call(&name),
snake_call_name: pascal_ident_to_snake_call(&name),
name,
+ via,
})
}
+ fn new(path: &Path) -> syn::Result<Self> {
+ Self::new_via(path, None)
+ }
fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
let name = &self.name;
@@ -85,8 +91,18 @@
) -> proc_macro2::TokenStream {
let name = &self.name;
let pascal_call_name = &self.pascal_call_name;
+ let via_typ = self
+ .via
+ .as_ref()
+ .map(|(t, _)| quote! {#t})
+ .unwrap_or_else(|| quote! {Self});
+ let via_map = self
+ .via
+ .as_ref()
+ .map(|(_, i)| quote! {.#i()})
+ .unwrap_or_default();
quote! {
- #call_name::#name(call) => return <Self as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self, Msg {
+ #call_name::#name(call) => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {
call,
caller: c.caller,
value: c.value,
@@ -126,8 +142,46 @@
let mut out = Vec::new();
for item in items {
match item {
- NestedMeta::Meta(Meta::Path(path)) => out.push(Is::try_from(path)?),
- _ => return Err(syn::Error::new(item.span(), "expected path").into()),
+ NestedMeta::Meta(Meta::Path(path)) => out.push(Is::new(path)?),
+ // TODO: replace meta parsing with manual
+ NestedMeta::Meta(Meta::List(list))
+ if list.path.is_ident("via") && list.nested.len() == 3 =>
+ {
+ let mut data = list.nested.iter();
+ let typ = match data.next().expect("len == 3") {
+ NestedMeta::Lit(Lit::Str(s)) => {
+ let v = s.value();
+ let typ: Type = parse_str(&v)?;
+ typ
+ }
+ _ => {
+ return Err(syn::Error::new(
+ item.span(),
+ "via typ should be type in string",
+ )
+ .into())
+ }
+ };
+ let via = match data.next().expect("len == 3") {
+ NestedMeta::Meta(Meta::Path(path)) => path
+ .get_ident()
+ .ok_or_else(|| syn::Error::new(item.span(), "via should be ident"))?,
+ _ => return Err(syn::Error::new(item.span(), "via should be ident").into()),
+ };
+ let path = match data.next().expect("len == 3") {
+ NestedMeta::Meta(Meta::Path(path)) => path,
+ _ => return Err(syn::Error::new(item.span(), "path should be path").into()),
+ };
+
+ out.push(Is::new_via(path, Some((typ, via.clone())))?)
+ }
+ _ => {
+ return Err(syn::Error::new(
+ item.span(),
+ "expected either Name or via(\"Type\", getter, Name)",
+ )
+ .into())
+ }
}
}
Ok(Self(out))
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -14,9 +14,14 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-pub use pallet_evm::PrecompileOutput;
-pub use pallet_evm::PrecompileResult;
+use evm_coder::{solidity_interface, types::*, execution::Result};
+pub use pallet_evm::{PrecompileOutput, PrecompileResult, account::CrossAccountId};
+use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_core::{H160, U256};
+use sp_std::vec::Vec;
+use up_data_structs::Property;
+
+use crate::{Pallet, CollectionHandle, Config};
/// Does not always represent a full collection, for RFT it is either
/// collection (Implementing ERC721), or specific collection token (Implementing ERC20)
@@ -25,3 +30,27 @@
fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult>;
}
+
+#[solidity_interface(name = "CollectionProperties")]
+impl<T: Config> CollectionHandle<T> {
+ fn set_property(&mut self, caller: caller, key: string, value: string) -> Result<()> {
+ <Pallet<T>>::set_collection_property(
+ self,
+ &T::CrossAccountId::from_eth(caller),
+ Property {
+ key: <Vec<u8>>::from(key)
+ .try_into()
+ .map_err(|_| "key too large")?,
+ value: <Vec<u8>>::from(value)
+ .try_into()
+ .map_err(|_| "value too large")?,
+ },
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
+ fn delete_property(&mut self, caller: caller, key: string) -> Result<()> {
+ self.set_property(caller, key, string::new())
+ }
+}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -595,7 +595,7 @@
.iter()
.map(|(key, value)| Property {
key: key.clone(),
- value: value.clone()
+ value: value.clone(),
})
.collect();
@@ -680,19 +680,20 @@
};
let mut collection_properties = up_data_structs::CollectionProperties::get();
- collection_properties.try_set_from_iter(
- data.properties.into_iter()
- .map(|p| (p.key, p.value))
- ).map_err(|e| -> Error<T> { e.into() })?;
+ collection_properties
+ .try_set_from_iter(data.properties.into_iter().map(|p| (p.key, p.value)))
+ .map_err(|e| -> Error<T> { e.into() })?;
CollectionProperties::<T>::insert(id, collection_properties);
let mut token_props_permissions = PropertiesPermissionMap::new();
- token_props_permissions.try_set_from_iter(
- data.token_property_permissions
- .into_iter()
- .map(|property| (property.key, property.permission))
- ).map_err(|e| -> Error<T> { e.into() })?;
+ token_props_permissions
+ .try_set_from_iter(
+ data.token_property_permissions
+ .into_iter()
+ .map(|property| (property.key, property.permission)),
+ )
+ .map_err(|e| -> Error<T> { e.into() })?;
CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);
@@ -806,7 +807,8 @@
CollectionProperties::<T>::try_mutate(collection.id, |properties| {
properties.remove(&property_key)
- }).map_err(|e| -> Error<T> { e.into() })?;
+ })
+ .map_err(|e| -> Error<T> { e.into() })?;
Self::deposit_event(Event::CollectionPropertyDeleted(
collection.id,
@@ -903,11 +905,10 @@
let properties = keys
.into_iter()
.filter_map(|key| {
- properties.get(&key)
- .map(|value| Property {
- key,
- value: value.clone(),
- })
+ properties.get(&key).map(|value| Property {
+ key,
+ value: value.clone(),
+ })
})
.collect();
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -24,6 +24,7 @@
use pallet_evm::account::CrossAccountId;
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
+use pallet_common::{CollectionHandle, erc::CollectionPropertiesCall};
use crate::{
Allowance, Balance, Config, FungibleHandle, Pallet, SelfWeightOf, TotalSupply,
@@ -144,7 +145,14 @@
}
}
-#[solidity_interface(name = "UniqueFungible", is(ERC20))]
+#[solidity_interface(
+ name = "UniqueFungible",
+ is(
+ ERC20,
+ ERC20UniqueExtensions,
+ via("CollectionHandle<T>", common_mut, CollectionProperties)
+ )
+)]
impl<T: Config> FungibleHandle<T> {}
generate_stubgen!(gen_impl, UniqueFungibleCall<()>, true);
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -110,6 +110,9 @@
pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {
self.0
}
+ pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {
+ &mut self.0
+ }
}
impl<T: Config> WithRecorder<T> for FungibleHandle<T> {
fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -391,11 +391,10 @@
keys.into_iter()
.filter_map(|key| {
- properties.get(&key)
- .map(|value| Property {
- key,
- value: value.clone(),
- })
+ properties.get(&key).map(|value| Property {
+ key,
+ value: value.clone(),
+ })
})
.collect()
}
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::{TokenId, SchemaVersion};25use pallet_evm_coder_substrate::dispatch_to_evm;26use sp_core::{H160, U256};27use sp_std::{vec::Vec, vec};28use pallet_common::{29 erc::{CommonEvmHandler, PrecompileResult},30};31use pallet_evm::account::CrossAccountId;32use pallet_evm_coder_substrate::call;33use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};3435use crate::{36 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,37 SelfWeightOf, weights::WeightInfo,38};3940fn error_unsupported_schema_version() -> Error {41 alloc::format!(42 "Unsupported schema version! Support only {:?}",43 SchemaVersion::ImageURL44 )45 .as_str()46 .into()47}4849#[derive(ToLog)]50pub enum ERC721Events {51 Transfer {52 #[indexed]53 from: address,54 #[indexed]55 to: address,56 #[indexed]57 token_id: uint256,58 },59 Approval {60 #[indexed]61 owner: address,62 #[indexed]63 approved: address,64 #[indexed]65 token_id: uint256,66 },67 #[allow(dead_code)]68 ApprovalForAll {69 #[indexed]70 owner: address,71 #[indexed]72 operator: address,73 approved: bool,74 },75}7677#[derive(ToLog)]78pub enum ERC721MintableEvents {79 #[allow(dead_code)]80 MintingFinished {},81}8283#[solidity_interface(name = "ERC721Metadata")]84impl<T: Config> NonfungibleHandle<T> {85 fn name(&self) -> Result<string> {86 Ok(decode_utf16(self.name.iter().copied())87 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))88 .collect::<string>())89 }9091 fn symbol(&self) -> Result<string> {92 Ok(string::from_utf8_lossy(&self.token_prefix).into())93 }9495 /// Returns token's const_metadata96 #[solidity(rename_selector = "tokenURI")]97 fn token_uri(&self, token_id: uint256) -> Result<string> {98 if !matches!(self.schema_version, SchemaVersion::ImageURL) {99 return Err(error_unsupported_schema_version());100 }101102 self.consume_store_reads(1)?;103 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;104 Ok(string::from_utf8_lossy(105 &<TokenData<T>>::get((self.id, token_id))106 .ok_or("token not found")?107 .const_data,108 )109 .into())110 }111}112113#[solidity_interface(name = "ERC721Enumerable")]114impl<T: Config> NonfungibleHandle<T> {115 fn token_by_index(&self, index: uint256) -> Result<uint256> {116 Ok(index)117 }118119 /// Not implemented120 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {121 // TODO: Not implemetable122 Err("not implemented".into())123 }124125 fn total_supply(&self) -> Result<uint256> {126 self.consume_store_reads(1)?;127 Ok(<Pallet<T>>::total_supply(self).into())128 }129}130131#[solidity_interface(name = "ERC721", events(ERC721Events))]132impl<T: Config> NonfungibleHandle<T> {133 fn balance_of(&self, owner: address) -> Result<uint256> {134 self.consume_store_reads(1)?;135 let owner = T::CrossAccountId::from_eth(owner);136 let balance = <AccountBalance<T>>::get((self.id, owner));137 Ok(balance.into())138 }139 fn owner_of(&self, token_id: uint256) -> Result<address> {140 self.consume_store_reads(1)?;141 let token: TokenId = token_id.try_into()?;142 Ok(*<TokenData<T>>::get((self.id, token))143 .ok_or("token not found")?144 .owner145 .as_eth())146 }147 /// Not implemented148 fn safe_transfer_from_with_data(149 &mut self,150 _from: address,151 _to: address,152 _token_id: uint256,153 _data: bytes,154 _value: value,155 ) -> Result<void> {156 // TODO: Not implemetable157 Err("not implemented".into())158 }159 /// Not implemented160 fn safe_transfer_from(161 &mut self,162 _from: address,163 _to: address,164 _token_id: uint256,165 _value: value,166 ) -> Result<void> {167 // TODO: Not implemetable168 Err("not implemented".into())169 }170171 #[weight(<SelfWeightOf<T>>::transfer_from())]172 fn transfer_from(173 &mut self,174 caller: caller,175 from: address,176 to: address,177 token_id: uint256,178 _value: value,179 ) -> Result<void> {180 let caller = T::CrossAccountId::from_eth(caller);181 let from = T::CrossAccountId::from_eth(from);182 let to = T::CrossAccountId::from_eth(to);183 let token = token_id.try_into()?;184 let budget = self185 .recorder186 .weight_calls_budget(<StructureWeight<T>>::find_parent());187188 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)189 .map_err(dispatch_to_evm::<T>)?;190 Ok(())191 }192193 #[weight(<SelfWeightOf<T>>::approve())]194 fn approve(195 &mut self,196 caller: caller,197 approved: address,198 token_id: uint256,199 _value: value,200 ) -> Result<void> {201 let caller = T::CrossAccountId::from_eth(caller);202 let approved = T::CrossAccountId::from_eth(approved);203 let token = token_id.try_into()?;204205 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))206 .map_err(dispatch_to_evm::<T>)?;207 Ok(())208 }209210 /// Not implemented211 fn set_approval_for_all(212 &mut self,213 _caller: caller,214 _operator: address,215 _approved: bool,216 ) -> Result<void> {217 // TODO: Not implemetable218 Err("not implemented".into())219 }220221 /// Not implemented222 fn get_approved(&self, _token_id: uint256) -> Result<address> {223 // TODO: Not implemetable224 Err("not implemented".into())225 }226227 /// Not implemented228 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {229 // TODO: Not implemetable230 Err("not implemented".into())231 }232}233234#[solidity_interface(name = "ERC721Burnable")]235impl<T: Config> NonfungibleHandle<T> {236 #[weight(<SelfWeightOf<T>>::burn_item())]237 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {238 let caller = T::CrossAccountId::from_eth(caller);239 let token = token_id.try_into()?;240241 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;242 Ok(())243 }244}245246#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]247impl<T: Config> NonfungibleHandle<T> {248 fn minting_finished(&self) -> Result<bool> {249 Ok(false)250 }251252 /// `token_id` should be obtained with `next_token_id` method,253 /// unlike standard, you can't specify it manually254 #[weight(<SelfWeightOf<T>>::create_item())]255 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {256 let caller = T::CrossAccountId::from_eth(caller);257 let to = T::CrossAccountId::from_eth(to);258 let token_id: u32 = token_id.try_into()?;259 let budget = self260 .recorder261 .weight_calls_budget(<StructureWeight<T>>::find_parent());262263 if <TokensMinted<T>>::get(self.id)264 .checked_add(1)265 .ok_or("item id overflow")?266 != token_id267 {268 return Err("item id should be next".into());269 }270271 <Pallet<T>>::create_item(272 self,273 &caller,274 CreateItemData::<T> {275 const_data: BoundedVec::default(),276 variable_data: BoundedVec::default(),277 properties: BoundedVec::default(),278 owner: to,279 },280 &budget,281 )282 .map_err(dispatch_to_evm::<T>)?;283284 Ok(true)285 }286287 /// `token_id` should be obtained with `next_token_id` method,288 /// unlike standard, you can't specify it manually289 #[solidity(rename_selector = "mintWithTokenURI")]290 #[weight(<SelfWeightOf<T>>::create_item())]291 fn mint_with_token_uri(292 &mut self,293 caller: caller,294 to: address,295 token_id: uint256,296 token_uri: string,297 ) -> Result<bool> {298 if !matches!(self.schema_version, SchemaVersion::ImageURL) {299 return Err(error_unsupported_schema_version());300 }301302 let caller = T::CrossAccountId::from_eth(caller);303 let to = T::CrossAccountId::from_eth(to);304 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;305 let budget = self306 .recorder307 .weight_calls_budget(<StructureWeight<T>>::find_parent());308309 if <TokensMinted<T>>::get(self.id)310 .checked_add(1)311 .ok_or("item id overflow")?312 != token_id313 {314 return Err("item id should be next".into());315 }316317 <Pallet<T>>::create_item(318 self,319 &caller,320 CreateItemData::<T> {321 const_data: Vec::<u8>::from(token_uri)322 .try_into()323 .map_err(|_| "token uri is too long")?,324 variable_data: BoundedVec::default(),325 properties: BoundedVec::default(),326 owner: to,327 },328 &budget,329 )330 .map_err(dispatch_to_evm::<T>)?;331 Ok(true)332 }333334 /// Not implemented335 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {336 Err("not implementable".into())337 }338}339340#[solidity_interface(name = "ERC721UniqueExtensions")]341impl<T: Config> NonfungibleHandle<T> {342 #[weight(<SelfWeightOf<T>>::transfer())]343 fn transfer(344 &mut self,345 caller: caller,346 to: address,347 token_id: uint256,348 _value: value,349 ) -> Result<void> {350 let caller = T::CrossAccountId::from_eth(caller);351 let to = T::CrossAccountId::from_eth(to);352 let token = token_id.try_into()?;353 let budget = self354 .recorder355 .weight_calls_budget(<StructureWeight<T>>::find_parent());356357 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;358 Ok(())359 }360361 #[weight(<SelfWeightOf<T>>::burn_from())]362 fn burn_from(363 &mut self,364 caller: caller,365 from: address,366 token_id: uint256,367 _value: value,368 ) -> Result<void> {369 let caller = T::CrossAccountId::from_eth(caller);370 let from = T::CrossAccountId::from_eth(from);371 let token = token_id.try_into()?;372 let budget = self373 .recorder374 .weight_calls_budget(<StructureWeight<T>>::find_parent());375376 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)377 .map_err(dispatch_to_evm::<T>)?;378 Ok(())379 }380381 fn next_token_id(&self) -> Result<uint256> {382 self.consume_store_reads(1)?;383 Ok(<TokensMinted<T>>::get(self.id)384 .checked_add(1)385 .ok_or("item id overflow")?386 .into())387 }388389 #[weight(<SelfWeightOf<T>>::set_variable_metadata(data.len() as u32))]390 fn set_variable_metadata(391 &mut self,392 caller: caller,393 token_id: uint256,394 data: bytes,395 ) -> Result<void> {396 let caller = T::CrossAccountId::from_eth(caller);397 let token = token_id.try_into()?;398399 <Pallet<T>>::set_variable_metadata(400 self,401 &caller,402 token,403 data.try_into()404 .map_err(|_| "metadata size exceeded limit")?,405 )406 .map_err(dispatch_to_evm::<T>)?;407 Ok(())408 }409410 fn get_variable_metadata(&self, token_id: uint256) -> Result<bytes> {411 self.consume_store_reads(1)?;412 let token: TokenId = token_id.try_into()?;413414 Ok(<TokenData<T>>::get((self.id, token))415 .ok_or("token not found")?416 .variable_data417 .into_inner())418 }419420 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]421 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {422 let caller = T::CrossAccountId::from_eth(caller);423 let to = T::CrossAccountId::from_eth(to);424 let mut expected_index = <TokensMinted<T>>::get(self.id)425 .checked_add(1)426 .ok_or("item id overflow")?;427 let budget = self428 .recorder429 .weight_calls_budget(<StructureWeight<T>>::find_parent());430431 let total_tokens = token_ids.len();432 for id in token_ids.into_iter() {433 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;434 if id != expected_index {435 return Err("item id should be next".into());436 }437 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;438 }439 let data = (0..total_tokens)440 .map(|_| CreateItemData::<T> {441 const_data: BoundedVec::default(),442 variable_data: BoundedVec::default(),443 properties: BoundedVec::default(),444 owner: to.clone(),445 })446 .collect();447448 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)449 .map_err(dispatch_to_evm::<T>)?;450 Ok(true)451 }452453 #[solidity(rename_selector = "mintBulkWithTokenURI")]454 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]455 fn mint_bulk_with_token_uri(456 &mut self,457 caller: caller,458 to: address,459 tokens: Vec<(uint256, string)>,460 ) -> Result<bool> {461 if !matches!(self.schema_version, SchemaVersion::ImageURL) {462 return Err(error_unsupported_schema_version());463 }464465 let caller = T::CrossAccountId::from_eth(caller);466 let to = T::CrossAccountId::from_eth(to);467 let mut expected_index = <TokensMinted<T>>::get(self.id)468 .checked_add(1)469 .ok_or("item id overflow")?;470 let budget = self471 .recorder472 .weight_calls_budget(<StructureWeight<T>>::find_parent());473474 let mut data = Vec::with_capacity(tokens.len());475 for (id, token_uri) in tokens {476 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;477 if id != expected_index {478 return Err("item id should be next".into());479 }480 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;481482 data.push(CreateItemData::<T> {483 const_data: Vec::<u8>::from(token_uri)484 .try_into()485 .map_err(|_| "token uri is too long")?,486 variable_data: vec![].try_into().unwrap(),487 properties: BoundedVec::default(),488 owner: to.clone(),489 });490 }491492 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)493 .map_err(dispatch_to_evm::<T>)?;494 Ok(true)495 }496}497498#[solidity_interface(499 name = "UniqueNFT",500 is(501 ERC721,502 ERC721Metadata,503 ERC721Enumerable,504 ERC721UniqueExtensions,505 ERC721Mintable,506 ERC721Burnable,507 )508)]509impl<T: Config> NonfungibleHandle<T> {}510511// Not a tests, but code generators512generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);513generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);514515impl<T: Config> CommonEvmHandler for NonfungibleHandle<T> {516 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");517518 fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult> {519 call::<T, UniqueNFTCall<T>, _>(*source, self, value, input)520 }521}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::{TokenId, SchemaVersion};25use pallet_evm_coder_substrate::dispatch_to_evm;26use sp_core::{H160, U256};27use sp_std::{vec::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,39};4041fn error_unsupported_schema_version() -> Error {42 alloc::format!(43 "Unsupported schema version! Support only {:?}",44 SchemaVersion::ImageURL45 )46 .as_str()47 .into()48}4950#[derive(ToLog)]51pub enum ERC721Events {52 Transfer {53 #[indexed]54 from: address,55 #[indexed]56 to: address,57 #[indexed]58 token_id: uint256,59 },60 Approval {61 #[indexed]62 owner: address,63 #[indexed]64 approved: address,65 #[indexed]66 token_id: uint256,67 },68 #[allow(dead_code)]69 ApprovalForAll {70 #[indexed]71 owner: address,72 #[indexed]73 operator: address,74 approved: bool,75 },76}7778#[derive(ToLog)]79pub enum ERC721MintableEvents {80 #[allow(dead_code)]81 MintingFinished {},82}8384#[solidity_interface(name = "ERC721Metadata")]85impl<T: Config> NonfungibleHandle<T> {86 fn name(&self) -> Result<string> {87 Ok(decode_utf16(self.name.iter().copied())88 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))89 .collect::<string>())90 }9192 fn symbol(&self) -> Result<string> {93 Ok(string::from_utf8_lossy(&self.token_prefix).into())94 }9596 /// Returns token's const_metadata97 #[solidity(rename_selector = "tokenURI")]98 fn token_uri(&self, token_id: uint256) -> Result<string> {99 if !matches!(self.schema_version, SchemaVersion::ImageURL) {100 return Err(error_unsupported_schema_version());101 }102103 self.consume_store_reads(1)?;104 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;105 Ok(string::from_utf8_lossy(106 &<TokenData<T>>::get((self.id, token_id))107 .ok_or("token not found")?108 .const_data,109 )110 .into())111 }112}113114#[solidity_interface(name = "ERC721Enumerable")]115impl<T: Config> NonfungibleHandle<T> {116 fn token_by_index(&self, index: uint256) -> Result<uint256> {117 Ok(index)118 }119120 /// Not implemented121 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {122 // TODO: Not implemetable123 Err("not implemented".into())124 }125126 fn total_supply(&self) -> Result<uint256> {127 self.consume_store_reads(1)?;128 Ok(<Pallet<T>>::total_supply(self).into())129 }130}131132#[solidity_interface(name = "ERC721", events(ERC721Events))]133impl<T: Config> NonfungibleHandle<T> {134 fn balance_of(&self, owner: address) -> Result<uint256> {135 self.consume_store_reads(1)?;136 let owner = T::CrossAccountId::from_eth(owner);137 let balance = <AccountBalance<T>>::get((self.id, owner));138 Ok(balance.into())139 }140 fn owner_of(&self, token_id: uint256) -> Result<address> {141 self.consume_store_reads(1)?;142 let token: TokenId = token_id.try_into()?;143 Ok(*<TokenData<T>>::get((self.id, token))144 .ok_or("token not found")?145 .owner146 .as_eth())147 }148 /// Not implemented149 fn safe_transfer_from_with_data(150 &mut self,151 _from: address,152 _to: address,153 _token_id: uint256,154 _data: bytes,155 _value: value,156 ) -> Result<void> {157 // TODO: Not implemetable158 Err("not implemented".into())159 }160 /// Not implemented161 fn safe_transfer_from(162 &mut self,163 _from: address,164 _to: address,165 _token_id: uint256,166 _value: value,167 ) -> Result<void> {168 // TODO: Not implemetable169 Err("not implemented".into())170 }171172 #[weight(<SelfWeightOf<T>>::transfer_from())]173 fn transfer_from(174 &mut self,175 caller: caller,176 from: address,177 to: address,178 token_id: uint256,179 _value: value,180 ) -> Result<void> {181 let caller = T::CrossAccountId::from_eth(caller);182 let from = T::CrossAccountId::from_eth(from);183 let to = T::CrossAccountId::from_eth(to);184 let token = token_id.try_into()?;185 let budget = self186 .recorder187 .weight_calls_budget(<StructureWeight<T>>::find_parent());188189 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)190 .map_err(dispatch_to_evm::<T>)?;191 Ok(())192 }193194 #[weight(<SelfWeightOf<T>>::approve())]195 fn approve(196 &mut self,197 caller: caller,198 approved: address,199 token_id: uint256,200 _value: value,201 ) -> Result<void> {202 let caller = T::CrossAccountId::from_eth(caller);203 let approved = T::CrossAccountId::from_eth(approved);204 let token = token_id.try_into()?;205206 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))207 .map_err(dispatch_to_evm::<T>)?;208 Ok(())209 }210211 /// Not implemented212 fn set_approval_for_all(213 &mut self,214 _caller: caller,215 _operator: address,216 _approved: bool,217 ) -> Result<void> {218 // TODO: Not implemetable219 Err("not implemented".into())220 }221222 /// Not implemented223 fn get_approved(&self, _token_id: uint256) -> Result<address> {224 // TODO: Not implemetable225 Err("not implemented".into())226 }227228 /// Not implemented229 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {230 // TODO: Not implemetable231 Err("not implemented".into())232 }233}234235#[solidity_interface(name = "ERC721Burnable")]236impl<T: Config> NonfungibleHandle<T> {237 #[weight(<SelfWeightOf<T>>::burn_item())]238 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {239 let caller = T::CrossAccountId::from_eth(caller);240 let token = token_id.try_into()?;241242 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;243 Ok(())244 }245}246247#[solidity_interface(name = "ERC721Mintable", events(ERC721MintableEvents))]248impl<T: Config> NonfungibleHandle<T> {249 fn minting_finished(&self) -> Result<bool> {250 Ok(false)251 }252253 /// `token_id` should be obtained with `next_token_id` method,254 /// unlike standard, you can't specify it manually255 #[weight(<SelfWeightOf<T>>::create_item())]256 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {257 let caller = T::CrossAccountId::from_eth(caller);258 let to = T::CrossAccountId::from_eth(to);259 let token_id: u32 = token_id.try_into()?;260 let budget = self261 .recorder262 .weight_calls_budget(<StructureWeight<T>>::find_parent());263264 if <TokensMinted<T>>::get(self.id)265 .checked_add(1)266 .ok_or("item id overflow")?267 != token_id268 {269 return Err("item id should be next".into());270 }271272 <Pallet<T>>::create_item(273 self,274 &caller,275 CreateItemData::<T> {276 const_data: BoundedVec::default(),277 variable_data: BoundedVec::default(),278 properties: BoundedVec::default(),279 owner: to,280 },281 &budget,282 )283 .map_err(dispatch_to_evm::<T>)?;284285 Ok(true)286 }287288 /// `token_id` should be obtained with `next_token_id` method,289 /// unlike standard, you can't specify it manually290 #[solidity(rename_selector = "mintWithTokenURI")]291 #[weight(<SelfWeightOf<T>>::create_item())]292 fn mint_with_token_uri(293 &mut self,294 caller: caller,295 to: address,296 token_id: uint256,297 token_uri: string,298 ) -> Result<bool> {299 if !matches!(self.schema_version, SchemaVersion::ImageURL) {300 return Err(error_unsupported_schema_version());301 }302303 let caller = T::CrossAccountId::from_eth(caller);304 let to = T::CrossAccountId::from_eth(to);305 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;306 let budget = self307 .recorder308 .weight_calls_budget(<StructureWeight<T>>::find_parent());309310 if <TokensMinted<T>>::get(self.id)311 .checked_add(1)312 .ok_or("item id overflow")?313 != token_id314 {315 return Err("item id should be next".into());316 }317318 <Pallet<T>>::create_item(319 self,320 &caller,321 CreateItemData::<T> {322 const_data: Vec::<u8>::from(token_uri)323 .try_into()324 .map_err(|_| "token uri is too long")?,325 variable_data: BoundedVec::default(),326 properties: BoundedVec::default(),327 owner: to,328 },329 &budget,330 )331 .map_err(dispatch_to_evm::<T>)?;332 Ok(true)333 }334335 /// Not implemented336 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {337 Err("not implementable".into())338 }339}340341#[solidity_interface(name = "ERC721UniqueExtensions")]342impl<T: Config> NonfungibleHandle<T> {343 #[weight(<SelfWeightOf<T>>::transfer())]344 fn transfer(345 &mut self,346 caller: caller,347 to: address,348 token_id: uint256,349 _value: value,350 ) -> Result<void> {351 let caller = T::CrossAccountId::from_eth(caller);352 let to = T::CrossAccountId::from_eth(to);353 let token = token_id.try_into()?;354 let budget = self355 .recorder356 .weight_calls_budget(<StructureWeight<T>>::find_parent());357358 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;359 Ok(())360 }361362 #[weight(<SelfWeightOf<T>>::burn_from())]363 fn burn_from(364 &mut self,365 caller: caller,366 from: address,367 token_id: uint256,368 _value: value,369 ) -> Result<void> {370 let caller = T::CrossAccountId::from_eth(caller);371 let from = T::CrossAccountId::from_eth(from);372 let token = token_id.try_into()?;373 let budget = self374 .recorder375 .weight_calls_budget(<StructureWeight<T>>::find_parent());376377 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)378 .map_err(dispatch_to_evm::<T>)?;379 Ok(())380 }381382 fn next_token_id(&self) -> Result<uint256> {383 self.consume_store_reads(1)?;384 Ok(<TokensMinted<T>>::get(self.id)385 .checked_add(1)386 .ok_or("item id overflow")?387 .into())388 }389390 #[weight(<SelfWeightOf<T>>::set_variable_metadata(data.len() as u32))]391 fn set_variable_metadata(392 &mut self,393 caller: caller,394 token_id: uint256,395 data: bytes,396 ) -> Result<void> {397 let caller = T::CrossAccountId::from_eth(caller);398 let token = token_id.try_into()?;399400 <Pallet<T>>::set_variable_metadata(401 self,402 &caller,403 token,404 data.try_into()405 .map_err(|_| "metadata size exceeded limit")?,406 )407 .map_err(dispatch_to_evm::<T>)?;408 Ok(())409 }410411 fn get_variable_metadata(&self, token_id: uint256) -> Result<bytes> {412 self.consume_store_reads(1)?;413 let token: TokenId = token_id.try_into()?;414415 Ok(<TokenData<T>>::get((self.id, token))416 .ok_or("token not found")?417 .variable_data418 .into_inner())419 }420421 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]422 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {423 let caller = T::CrossAccountId::from_eth(caller);424 let to = T::CrossAccountId::from_eth(to);425 let mut expected_index = <TokensMinted<T>>::get(self.id)426 .checked_add(1)427 .ok_or("item id overflow")?;428 let budget = self429 .recorder430 .weight_calls_budget(<StructureWeight<T>>::find_parent());431432 let total_tokens = token_ids.len();433 for id in token_ids.into_iter() {434 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;435 if id != expected_index {436 return Err("item id should be next".into());437 }438 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;439 }440 let data = (0..total_tokens)441 .map(|_| CreateItemData::<T> {442 const_data: BoundedVec::default(),443 variable_data: BoundedVec::default(),444 properties: BoundedVec::default(),445 owner: to.clone(),446 })447 .collect();448449 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)450 .map_err(dispatch_to_evm::<T>)?;451 Ok(true)452 }453454 #[solidity(rename_selector = "mintBulkWithTokenURI")]455 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]456 fn mint_bulk_with_token_uri(457 &mut self,458 caller: caller,459 to: address,460 tokens: Vec<(uint256, string)>,461 ) -> Result<bool> {462 if !matches!(self.schema_version, SchemaVersion::ImageURL) {463 return Err(error_unsupported_schema_version());464 }465466 let caller = T::CrossAccountId::from_eth(caller);467 let to = T::CrossAccountId::from_eth(to);468 let mut expected_index = <TokensMinted<T>>::get(self.id)469 .checked_add(1)470 .ok_or("item id overflow")?;471 let budget = self472 .recorder473 .weight_calls_budget(<StructureWeight<T>>::find_parent());474475 let mut data = Vec::with_capacity(tokens.len());476 for (id, token_uri) in tokens {477 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;478 if id != expected_index {479 return Err("item id should be next".into());480 }481 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;482483 data.push(CreateItemData::<T> {484 const_data: Vec::<u8>::from(token_uri)485 .try_into()486 .map_err(|_| "token uri is too long")?,487 variable_data: vec![].try_into().unwrap(),488 properties: BoundedVec::default(),489 owner: to.clone(),490 });491 }492493 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)494 .map_err(dispatch_to_evm::<T>)?;495 Ok(true)496 }497}498499#[solidity_interface(500 name = "UniqueNFT",501 is(502 ERC721,503 ERC721Metadata,504 ERC721Enumerable,505 ERC721UniqueExtensions,506 ERC721Mintable,507 ERC721Burnable,508 via("CollectionHandle<T>", common_mut, CollectionProperties)509 )510)]511impl<T: Config> NonfungibleHandle<T> {}512513// Not a tests, but code generators514generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);515generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);516517impl<T: Config> CommonEvmHandler for NonfungibleHandle<T> {518 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");519520 fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult> {521 call::<T, UniqueNFTCall<T>, _>(*source, self, value, input)522 }523}pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -142,6 +142,9 @@
pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {
self.0
}
+ pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {
+ &mut self.0
+ }
}
impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {
fn recorder(&self) -> &SubstrateRecorder<T> {
@@ -302,7 +305,8 @@
<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
properties.remove(&property_key)
- }).map_err(|e| -> CommonError<T> { e.into() })?;
+ })
+ .map_err(|e| -> CommonError<T> { e.into() })?;
<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(
collection.id,
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -699,7 +699,7 @@
fn try_set_from_iter<I>(&mut self, iter: I) -> Result<(), PropertiesError>
where
- I: Iterator<Item=(PropertyKey, Self::Value)>
+ I: Iterator<Item = (PropertyKey, Self::Value)>,
{
for (key, value) in iter {
self.try_set(key, value)?;
@@ -711,7 +711,9 @@
#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]
#[derivative(Default(bound = ""))]
-pub struct PropertiesMap<Value>(BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>);
+pub struct PropertiesMap<Value>(
+ BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,
+);
impl<Value> PropertiesMap<Value> {
pub fn new() -> Self {