difftreelog
Merge pull request #569 from UniqueNetwork/feature/evm-conditional-inheritance
in: master
11 files changed
crates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth--- a/crates/evm-coder/procedural/src/solidity_interface.rs
+++ b/crates/evm-coder/procedural/src/solidity_interface.rs
@@ -42,6 +42,7 @@
pascal_call_name: Ident,
snake_call_name: Ident,
via: Option<(Type, Ident)>,
+ condition: Option<Expr>,
}
impl Is {
fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
@@ -64,8 +65,13 @@
generics: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
let pascal_call_name = &self.pascal_call_name;
+ let condition = self.condition.as_ref().map(|condition| {
+ quote! {
+ (#condition) &&
+ }
+ });
quote! {
- <#pascal_call_name #generics>::supports_interface(interface_id)
+ #condition <#pascal_call_name #generics>::supports_interface(this, interface_id)
}
}
@@ -93,8 +99,13 @@
.as_ref()
.map(|(_, i)| quote! {.#i()})
.unwrap_or_default();
+ let condition = self.condition.as_ref().map(|condition| {
+ quote! {
+ if ({let this = &self; (#condition)})
+ }
+ });
quote! {
- #call_name::#name(call) => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {
+ #call_name::#name(call) #condition => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {
call,
caller: c.caller,
value: c.value,
@@ -138,17 +149,50 @@
}
let name = input.parse::<Ident>()?;
let lookahead = input.lookahead1();
- let via = if lookahead.peek(syn::token::Paren) {
+
+ let mut condition: Option<Expr> = None;
+ let mut via: Option<(Type, Ident)> = None;
+
+ if lookahead.peek(syn::token::Paren) {
let contents;
parenthesized!(contents in input);
- let method = contents.parse::<Ident>()?;
- contents.parse::<Token![,]>()?;
- let ty = contents.parse::<Type>()?;
- Some((ty, method))
- } else if lookahead.peek(Token![,]) {
- None
- } else if input.is_empty() {
- None
+ let input = contents;
+
+ while !input.is_empty() {
+ let lookahead = input.lookahead1();
+ if lookahead.peek(Token![if]) {
+ input.parse::<Token![if]>()?;
+ let contents;
+ parenthesized!(contents in input);
+ let contents = contents.parse::<Expr>()?;
+
+ if condition.replace(contents).is_some() {
+ return Err(syn::Error::new(input.span(), "condition is already set"));
+ }
+ } else if lookahead.peek(kw::via) {
+ input.parse::<kw::via>()?;
+ let contents;
+ parenthesized!(contents in input);
+
+ let method = contents.parse::<Ident>()?;
+ contents.parse::<kw::returns>()?;
+ let ty = contents.parse::<Type>()?;
+
+ if via.replace((ty, method)).is_some() {
+ return Err(syn::Error::new(input.span(), "via is already set"));
+ }
+ } else {
+ return Err(lookahead.error());
+ }
+
+ if input.peek(Token![,]) {
+ input.parse::<Token![,]>()?;
+ } else if !input.is_empty() {
+ return Err(syn::Error::new(input.span(), "expected end"));
+ }
+ }
+ } else if lookahead.peek(Token![,]) || input.is_empty() {
+ // Pass
} else {
return Err(lookahead.error());
};
@@ -157,6 +201,7 @@
snake_call_name: pascal_ident_to_snake_call(&name),
name,
via,
+ condition,
});
if input.peek(Token![,]) {
input.parse::<Token![,]>()?;
@@ -495,6 +540,7 @@
syn::custom_keyword!(weight);
syn::custom_keyword!(via);
+ syn::custom_keyword!(returns);
syn::custom_keyword!(name);
syn::custom_keyword!(is);
syn::custom_keyword!(inline_is);
@@ -996,16 +1042,6 @@
#(#inline_interface_id)*
u32::to_be_bytes(interface_id)
}
- /// Is this contract implements specified ERC165 selector
- pub fn supports_interface(interface_id: ::evm_coder::types::bytes4) -> bool {
- interface_id != u32::to_be_bytes(0xffffff) && (
- interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||
- interface_id == Self::interface_id()
- #(
- || #supports_interface
- )*
- )
- }
/// Generate solidity definitions for methods described in this interface
pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {
use evm_coder::solidity::*;
@@ -1024,7 +1060,7 @@
)*),
};
- let mut out = string::new();
+ let mut out = ::evm_coder::types::string::new();
if #solidity_name.starts_with("Inline") {
out.push_str("/// @dev inlined interface\n");
}
@@ -1062,6 +1098,20 @@
return Ok(None);
}
}
+ impl #generics #call_name #gen_ref
+ #gen_where
+ {
+ /// Is this contract implements specified ERC165 selector
+ pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {
+ interface_id != u32::to_be_bytes(0xffffff) && (
+ interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||
+ interface_id == Self::interface_id()
+ #(
+ || #supports_interface
+ )*
+ )
+ }
+ }
impl #generics ::evm_coder::Weighted for #call_name #gen_ref
#gen_where
{
@@ -1091,7 +1141,7 @@
)*
#call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {
let mut writer = ::evm_coder::abi::AbiWriter::default();
- writer.bool(&<#call_name #gen_ref>::supports_interface(interface_id));
+ writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));
return Ok(writer.into());
}
_ => {},
@@ -1101,7 +1151,7 @@
#(
#call_variants_this,
)*
- _ => unreachable!()
+ _ => Err(::evm_coder::execution::Error::from("method is not available").into()),
}
}
}
crates/evm-coder/src/abi.rsdiffbeforeafterboth--- a/crates/evm-coder/src/abi.rs
+++ b/crates/evm-coder/src/abi.rs
@@ -313,7 +313,7 @@
/// Finish writer, concatenating all internal buffers
pub fn finish(mut self) -> Vec<u8> {
for (static_offset, part) in self.dynamic_part {
- let part_offset = self.static_part.len() - self.had_call.then(|| 4).unwrap_or(0);
+ let part_offset = self.static_part.len() - if self.had_call { 4 } else { 0 };
let encoded_dynamic_offset = usize::to_be_bytes(part_offset);
self.static_part[static_offset + ABI_ALIGNMENT - encoded_dynamic_offset.len()
crates/evm-coder/src/lib.rsdiffbeforeafterboth--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -74,10 +74,10 @@
/// #[solidity_interface(name = MyContract, is(SuperContract), inline_is(InlineContract))]
/// impl Contract {
/// /// Multiply two numbers
-/// /// @param a First number
-/// /// @param b Second number
-/// /// @return uint32 Product of two passed numbers
-/// /// @dev This function returns error in case of overflow
+/// /// @param a First number
+/// /// @param b Second number
+/// /// @return uint32 Product of two passed numbers
+/// /// @dev This function returns error in case of overflow
/// #[weight(200 + a + b)]
/// #[solidity_interface(rename_selector = "mul")]
/// fn mul(&mut self, a: uint32, b: uint32) -> Result<uint32> {
crates/evm-coder/tests/conditional_is.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/evm-coder/tests/conditional_is.rs
@@ -0,0 +1,44 @@
+use evm_coder::{types::*, solidity_interface, execution::Result, Call};
+
+pub struct Contract(bool);
+
+#[solidity_interface(name = A)]
+impl Contract {
+ fn method_a() -> Result<void> {
+ Ok(())
+ }
+}
+
+#[solidity_interface(name = B)]
+impl Contract {
+ fn method_b() -> Result<void> {
+ Ok(())
+ }
+}
+
+#[solidity_interface(name = Contract, is(
+ A(if(this.0)),
+ B(if(!this.0)),
+))]
+impl Contract {}
+
+#[test]
+fn conditional_erc165() {
+ assert!(ContractCall::supports_interface(
+ &Contract(true),
+ ACall::METHOD_A
+ ));
+ assert!(!ContractCall::supports_interface(
+ &Contract(false),
+ ACall::METHOD_A
+ ));
+
+ assert!(ContractCall::supports_interface(
+ &Contract(false),
+ BCall::METHOD_B
+ ));
+ assert!(!ContractCall::supports_interface(
+ &Contract(true),
+ BCall::METHOD_B
+ ));
+}
crates/evm-coder/tests/generics.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/generics.rs
+++ b/crates/evm-coder/tests/generics.rs
@@ -17,7 +17,7 @@
use std::marker::PhantomData;
use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};
-struct Generic<T>(PhantomData<T>);
+pub struct Generic<T>(PhantomData<T>);
#[solidity_interface(name = GenericIs)]
impl<T> Generic<T> {
crates/evm-coder/tests/random.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/random.rs
+++ b/crates/evm-coder/tests/random.rs
@@ -18,7 +18,7 @@
use evm_coder::{ToLog, execution::Result, solidity_interface, types::*, solidity, weight};
-struct Impls;
+pub struct Impls;
#[solidity_interface(name = OurInterface)]
impl Impls {
crates/evm-coder/tests/solidity_generation.rsdiffbeforeafterboth--- a/crates/evm-coder/tests/solidity_generation.rs
+++ b/crates/evm-coder/tests/solidity_generation.rs
@@ -16,7 +16,7 @@
use evm_coder::{execution::Result, generate_stubgen, solidity_interface, types::*};
-struct ERC20;
+pub struct ERC20;
#[solidity_interface(name = ERC20)]
impl ERC20 {
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -406,9 +406,9 @@
true => {
let mut bv = OwnerRestrictedSet::new();
for i in collections {
- bv.try_insert(crate::eth::map_eth_to_id(&i).ok_or(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(|_| "too many collections")?;
}
let mut nesting = permissions.nesting().clone();
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -199,7 +199,7 @@
ERC20,
ERC20Mintable,
ERC20UniqueExtensions,
- Collection(common_mut, CollectionHandle<T>),
+ Collection(via(common_mut returns CollectionHandle<T>)),
)
)]
impl<T: Config> FungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}
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/>.1617//! # Nonfungible Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;23use core::{24 char::{REPLACEMENT_CHARACTER, decode_utf16},25 convert::TryInto,26};27use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};28use frame_support::BoundedVec;29use up_data_structs::{30 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,31 CollectionPropertiesVec,32};33use pallet_evm_coder_substrate::dispatch_to_evm;34use sp_std::vec::Vec;35use pallet_common::{36 erc::{37 CommonEvmHandler, PrecompileResult, CollectionCall,38 static_property::{key, value as property_value},39 },40 CollectionHandle, CollectionPropertyPermissions,41};42use pallet_evm::{account::CrossAccountId, PrecompileHandle};43use pallet_evm_coder_substrate::call;44use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};45use alloc::string::ToString;4647use crate::{48 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,49 SelfWeightOf, weights::WeightInfo, TokenProperties,50};5152/// @title A contract that allows to set and delete token properties and change token property permissions.53#[solidity_interface(name = TokenProperties)]54impl<T: Config> NonfungibleHandle<T> {55 /// @notice Set permissions for token property.56 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.57 /// @param key Property key.58 /// @param isMutable Permission to mutate property.59 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.60 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.61 fn set_token_property_permission(62 &mut self,63 caller: caller,64 key: string,65 is_mutable: bool,66 collection_admin: bool,67 token_owner: bool,68 ) -> Result<()> {69 let caller = T::CrossAccountId::from_eth(caller);70 <Pallet<T>>::set_property_permission(71 self,72 &caller,73 PropertyKeyPermission {74 key: <Vec<u8>>::from(key)75 .try_into()76 .map_err(|_| "too long key")?,77 permission: PropertyPermission {78 mutable: is_mutable,79 collection_admin,80 token_owner,81 },82 },83 )84 .map_err(dispatch_to_evm::<T>)85 }8687 /// @notice Set token property value.88 /// @dev Throws error if `msg.sender` has no permission to edit the property.89 /// @param tokenId ID of the token.90 /// @param key Property key.91 /// @param value Property value.92 fn set_property(93 &mut self,94 caller: caller,95 token_id: uint256,96 key: string,97 value: bytes,98 ) -> Result<()> {99 let caller = T::CrossAccountId::from_eth(caller);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")?;104 let value = value.try_into().map_err(|_| "value too long")?;105106 let nesting_budget = self107 .recorder108 .weight_calls_budget(<StructureWeight<T>>::find_parent());109110 <Pallet<T>>::set_token_property(111 self,112 &caller,113 TokenId(token_id),114 Property { key, value },115 &nesting_budget,116 )117 .map_err(dispatch_to_evm::<T>)118 }119120 /// @notice Delete token property value.121 /// @dev Throws error if `msg.sender` has no permission to edit the property.122 /// @param tokenId ID of the token.123 /// @param key Property key.124 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {125 let caller = T::CrossAccountId::from_eth(caller);126 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;127 let key = <Vec<u8>>::from(key)128 .try_into()129 .map_err(|_| "key too long")?;130131 let nesting_budget = self132 .recorder133 .weight_calls_budget(<StructureWeight<T>>::find_parent());134135 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)136 .map_err(dispatch_to_evm::<T>)137 }138139 /// @notice Get token property value.140 /// @dev Throws error if key not found141 /// @param tokenId ID of the token.142 /// @param key Property key.143 /// @return Property value bytes144 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {145 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;146 let key = <Vec<u8>>::from(key)147 .try_into()148 .map_err(|_| "key too long")?;149150 let props = <TokenProperties<T>>::get((self.id, token_id));151 let prop = props.get(&key).ok_or("key not found")?;152153 Ok(prop.to_vec())154 }155}156157#[derive(ToLog)]158pub enum ERC721Events {159 /// @dev This emits when ownership of any NFT changes by any mechanism.160 /// This event emits when NFTs are created (`from` == 0) and destroyed161 /// (`to` == 0). Exception: during contract creation, any number of NFTs162 /// may be created and assigned without emitting Transfer. At the time of163 /// any transfer, the approved address for that NFT (if any) is reset to none.164 Transfer {165 #[indexed]166 from: address,167 #[indexed]168 to: address,169 #[indexed]170 token_id: uint256,171 },172 /// @dev This emits when the approved address for an NFT is changed or173 /// reaffirmed. The zero address indicates there is no approved address.174 /// When a Transfer event emits, this also indicates that the approved175 /// address for that NFT (if any) is reset to none.176 Approval {177 #[indexed]178 owner: address,179 #[indexed]180 approved: address,181 #[indexed]182 token_id: uint256,183 },184 /// @dev This emits when an operator is enabled or disabled for an owner.185 /// The operator can manage all NFTs of the owner.186 #[allow(dead_code)]187 ApprovalForAll {188 #[indexed]189 owner: address,190 #[indexed]191 operator: address,192 approved: bool,193 },194}195196#[derive(ToLog)]197pub enum ERC721MintableEvents {198 #[allow(dead_code)]199 MintingFinished {},200}201202/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension203/// @dev See https://eips.ethereum.org/EIPS/eip-721204#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]205impl<T: Config> NonfungibleHandle<T> {206 /// @notice A descriptive name for a collection of NFTs in this contract207 fn name(&self) -> Result<string> {208 Ok(decode_utf16(self.name.iter().copied())209 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))210 .collect::<string>())211 }212213 /// @notice An abbreviated name for NFTs in this contract214 fn symbol(&self) -> Result<string> {215 Ok(string::from_utf8_lossy(&self.token_prefix).into())216 }217218 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.219 ///220 /// @dev If the token has a `url` property and it is not empty, it is returned.221 /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.222 /// If the collection property `baseURI` is empty or absent, return "" (empty string)223 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix224 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).225 ///226 /// @return token's const_metadata227 #[solidity(rename_selector = "tokenURI")]228 fn token_uri(&self, token_id: uint256) -> Result<string> {229 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;230231 if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {232 if !url.is_empty() {233 return Ok(url);234 }235 } else if !is_erc721_metadata_compatible::<T>(self.id) {236 return Err("tokenURI not set".into());237 }238239 if let Some(base_uri) =240 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())241 {242 if !base_uri.is_empty() {243 let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {244 Error::Revert(alloc::format!(245 "Can not convert value \"baseURI\" to string with error \"{}\"",246 e247 ))248 })?;249 if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {250 if !suffix.is_empty() {251 return Ok(base_uri + suffix.as_str());252 }253 }254255 return Ok(base_uri + token_id.to_string().as_str());256 }257 }258259 Ok("".into())260 }261}262263/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension264/// @dev See https://eips.ethereum.org/EIPS/eip-721265#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63)]266impl<T: Config> NonfungibleHandle<T> {267 /// @notice Enumerate valid NFTs268 /// @param index A counter less than `totalSupply()`269 /// @return The token identifier for the `index`th NFT,270 /// (sort order not specified)271 fn token_by_index(&self, index: uint256) -> Result<uint256> {272 Ok(index)273 }274275 /// @dev Not implemented276 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {277 // TODO: Not implemetable278 Err("not implemented".into())279 }280281 /// @notice Count NFTs tracked by this contract282 /// @return A count of valid NFTs tracked by this contract, where each one of283 /// them has an assigned and queryable owner not equal to the zero address284 fn total_supply(&self) -> Result<uint256> {285 self.consume_store_reads(1)?;286 Ok(<Pallet<T>>::total_supply(self).into())287 }288}289290/// @title ERC-721 Non-Fungible Token Standard291/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md292#[solidity_interface(name = ERC721, events(ERC721Events), expect_selector = 0x80ac58cd)]293impl<T: Config> NonfungibleHandle<T> {294 /// @notice Count all NFTs assigned to an owner295 /// @dev NFTs assigned to the zero address are considered invalid, and this296 /// function throws for queries about the zero address.297 /// @param owner An address for whom to query the balance298 /// @return The number of NFTs owned by `owner`, possibly zero299 fn balance_of(&self, owner: address) -> Result<uint256> {300 self.consume_store_reads(1)?;301 let owner = T::CrossAccountId::from_eth(owner);302 let balance = <AccountBalance<T>>::get((self.id, owner));303 Ok(balance.into())304 }305 /// @notice Find the owner of an NFT306 /// @dev NFTs assigned to zero address are considered invalid, and queries307 /// about them do throw.308 /// @param tokenId The identifier for an NFT309 /// @return The address of the owner of the NFT310 fn owner_of(&self, token_id: uint256) -> Result<address> {311 self.consume_store_reads(1)?;312 let token: TokenId = token_id.try_into()?;313 Ok(*<TokenData<T>>::get((self.id, token))314 .ok_or("token not found")?315 .owner316 .as_eth())317 }318 /// @dev Not implemented319 #[solidity(rename_selector = "safeTransferFrom")]320 fn safe_transfer_from_with_data(321 &mut self,322 _from: address,323 _to: address,324 _token_id: uint256,325 _data: bytes,326 ) -> Result<void> {327 // TODO: Not implemetable328 Err("not implemented".into())329 }330 /// @dev Not implemented331 fn safe_transfer_from(332 &mut self,333 _from: address,334 _to: address,335 _token_id: uint256,336 ) -> Result<void> {337 // TODO: Not implemetable338 Err("not implemented".into())339 }340341 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE342 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE343 /// THEY MAY BE PERMANENTLY LOST344 /// @dev Throws unless `msg.sender` is the current owner or an authorized345 /// operator for this NFT. Throws if `from` is not the current owner. Throws346 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.347 /// @param from The current owner of the NFT348 /// @param to The new owner349 /// @param tokenId The NFT to transfer350 #[weight(<SelfWeightOf<T>>::transfer_from())]351 fn transfer_from(352 &mut self,353 caller: caller,354 from: address,355 to: address,356 token_id: uint256,357 ) -> Result<void> {358 let caller = T::CrossAccountId::from_eth(caller);359 let from = T::CrossAccountId::from_eth(from);360 let to = T::CrossAccountId::from_eth(to);361 let token = token_id.try_into()?;362 let budget = self363 .recorder364 .weight_calls_budget(<StructureWeight<T>>::find_parent());365366 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)367 .map_err(dispatch_to_evm::<T>)?;368 Ok(())369 }370371 /// @notice Set or reaffirm the approved address for an NFT372 /// @dev The zero address indicates there is no approved address.373 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized374 /// operator of the current owner.375 /// @param approved The new approved NFT controller376 /// @param tokenId The NFT to approve377 #[weight(<SelfWeightOf<T>>::approve())]378 fn approve(&mut self, caller: caller, approved: address, token_id: uint256) -> Result<void> {379 let caller = T::CrossAccountId::from_eth(caller);380 let approved = T::CrossAccountId::from_eth(approved);381 let token = token_id.try_into()?;382383 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))384 .map_err(dispatch_to_evm::<T>)?;385 Ok(())386 }387388 /// @dev Not implemented389 fn set_approval_for_all(390 &mut self,391 _caller: caller,392 _operator: address,393 _approved: bool,394 ) -> Result<void> {395 // TODO: Not implemetable396 Err("not implemented".into())397 }398399 /// @dev Not implemented400 fn get_approved(&self, _token_id: uint256) -> Result<address> {401 // TODO: Not implemetable402 Err("not implemented".into())403 }404405 /// @dev Not implemented406 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {407 // TODO: Not implemetable408 Err("not implemented".into())409 }410}411412/// @title ERC721 Token that can be irreversibly burned (destroyed).413#[solidity_interface(name = ERC721Burnable)]414impl<T: Config> NonfungibleHandle<T> {415 /// @notice Burns a specific ERC721 token.416 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized417 /// operator of the current owner.418 /// @param tokenId The NFT to approve419 #[weight(<SelfWeightOf<T>>::burn_item())]420 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {421 let caller = T::CrossAccountId::from_eth(caller);422 let token = token_id.try_into()?;423424 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;425 Ok(())426 }427}428429/// @title ERC721 minting logic.430#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]431impl<T: Config> NonfungibleHandle<T> {432 fn minting_finished(&self) -> Result<bool> {433 Ok(false)434 }435436 /// @notice Function to mint token.437 /// @dev `tokenId` should be obtained with `nextTokenId` method,438 /// unlike standard, you can't specify it manually439 /// @param to The new owner440 /// @param tokenId ID of the minted NFT441 #[weight(<SelfWeightOf<T>>::create_item())]442 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {443 let caller = T::CrossAccountId::from_eth(caller);444 let to = T::CrossAccountId::from_eth(to);445 let token_id: u32 = token_id.try_into()?;446 let budget = self447 .recorder448 .weight_calls_budget(<StructureWeight<T>>::find_parent());449450 if <TokensMinted<T>>::get(self.id)451 .checked_add(1)452 .ok_or("item id overflow")?453 != token_id454 {455 return Err("item id should be next".into());456 }457458 <Pallet<T>>::create_item(459 self,460 &caller,461 CreateItemData::<T> {462 properties: BoundedVec::default(),463 owner: to,464 },465 &budget,466 )467 .map_err(dispatch_to_evm::<T>)?;468469 Ok(true)470 }471472 /// @notice Function to mint token with the given tokenUri.473 /// @dev `tokenId` should be obtained with `nextTokenId` method,474 /// unlike standard, you can't specify it manually475 /// @param to The new owner476 /// @param tokenId ID of the minted NFT477 /// @param tokenUri Token URI that would be stored in the NFT properties478 #[solidity(rename_selector = "mintWithTokenURI")]479 #[weight(<SelfWeightOf<T>>::create_item())]480 fn mint_with_token_uri(481 &mut self,482 caller: caller,483 to: address,484 token_id: uint256,485 token_uri: string,486 ) -> Result<bool> {487 let key = key::url();488 let permission = get_token_permission::<T>(self.id, &key)?;489 if !permission.collection_admin {490 return Err("Operation is not allowed".into());491 }492493 let caller = T::CrossAccountId::from_eth(caller);494 let to = T::CrossAccountId::from_eth(to);495 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;496 let budget = self497 .recorder498 .weight_calls_budget(<StructureWeight<T>>::find_parent());499500 if <TokensMinted<T>>::get(self.id)501 .checked_add(1)502 .ok_or("item id overflow")?503 != token_id504 {505 return Err("item id should be next".into());506 }507508 let mut properties = CollectionPropertiesVec::default();509 properties510 .try_push(Property {511 key,512 value: token_uri513 .into_bytes()514 .try_into()515 .map_err(|_| "token uri is too long")?,516 })517 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;518519 <Pallet<T>>::create_item(520 self,521 &caller,522 CreateItemData::<T> {523 properties,524 owner: to,525 },526 &budget,527 )528 .map_err(dispatch_to_evm::<T>)?;529 Ok(true)530 }531532 /// @dev Not implemented533 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {534 Err("not implementable".into())535 }536}537538fn get_token_property<T: Config>(539 collection: &CollectionHandle<T>,540 token_id: u32,541 key: &up_data_structs::PropertyKey,542) -> Result<string> {543 collection.consume_store_reads(1)?;544 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))545 .map_err(|_| Error::Revert("Token properties not found".into()))?;546 if let Some(property) = properties.get(key) {547 return Ok(string::from_utf8_lossy(property).into());548 }549550 Err("Property tokenURI not found".into())551}552553fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {554 if let Some(shema_name) =555 pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())556 {557 let shema_name = shema_name.into_inner();558 shema_name == property_value::ERC721_METADATA559 } else {560 false561 }562}563564fn get_token_permission<T: Config>(565 collection_id: CollectionId,566 key: &PropertyKey,567) -> Result<PropertyPermission> {568 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)569 .map_err(|_| Error::Revert("No permissions for collection".into()))?;570 let a = token_property_permissions571 .get(key)572 .map(Clone::clone)573 .ok_or_else(|| {574 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();575 Error::Revert(alloc::format!("No permission for key {}", key))576 })?;577 Ok(a)578}579580fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {581 if let Ok(token_property_permissions) =582 CollectionPropertyPermissions::<T>::try_get(collection_id)583 {584 return token_property_permissions.contains_key(key);585 }586587 false588}589590/// @title Unique extensions for ERC721.591#[solidity_interface(name = ERC721UniqueExtensions)]592impl<T: Config> NonfungibleHandle<T> {593 /// @notice Transfer ownership of an NFT594 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`595 /// is the zero address. Throws if `tokenId` is not a valid NFT.596 /// @param to The new owner597 /// @param tokenId The NFT to transfer598 #[weight(<SelfWeightOf<T>>::transfer())]599 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {600 let caller = T::CrossAccountId::from_eth(caller);601 let to = T::CrossAccountId::from_eth(to);602 let token = token_id.try_into()?;603 let budget = self604 .recorder605 .weight_calls_budget(<StructureWeight<T>>::find_parent());606607 <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;608 Ok(())609 }610611 /// @notice Burns a specific ERC721 token.612 /// @dev Throws unless `msg.sender` is the current owner or an authorized613 /// operator for this NFT. Throws if `from` is not the current owner. Throws614 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.615 /// @param from The current owner of the NFT616 /// @param tokenId The NFT to transfer617 #[weight(<SelfWeightOf<T>>::burn_from())]618 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {619 let caller = T::CrossAccountId::from_eth(caller);620 let from = T::CrossAccountId::from_eth(from);621 let token = token_id.try_into()?;622 let budget = self623 .recorder624 .weight_calls_budget(<StructureWeight<T>>::find_parent());625626 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)627 .map_err(dispatch_to_evm::<T>)?;628 Ok(())629 }630631 /// @notice Returns next free NFT ID.632 fn next_token_id(&self) -> Result<uint256> {633 self.consume_store_reads(1)?;634 Ok(<TokensMinted<T>>::get(self.id)635 .checked_add(1)636 .ok_or("item id overflow")?637 .into())638 }639640 /// @notice Function to mint multiple tokens.641 /// @dev `tokenIds` should be an array of consecutive numbers and first number642 /// should be obtained with `nextTokenId` method643 /// @param to The new owner644 /// @param tokenIds IDs of the minted NFTs645 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]646 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {647 let caller = T::CrossAccountId::from_eth(caller);648 let to = T::CrossAccountId::from_eth(to);649 let mut expected_index = <TokensMinted<T>>::get(self.id)650 .checked_add(1)651 .ok_or("item id overflow")?;652 let budget = self653 .recorder654 .weight_calls_budget(<StructureWeight<T>>::find_parent());655656 let total_tokens = token_ids.len();657 for id in token_ids.into_iter() {658 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;659 if id != expected_index {660 return Err("item id should be next".into());661 }662 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;663 }664 let data = (0..total_tokens)665 .map(|_| CreateItemData::<T> {666 properties: BoundedVec::default(),667 owner: to.clone(),668 })669 .collect();670671 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)672 .map_err(dispatch_to_evm::<T>)?;673 Ok(true)674 }675676 /// @notice Function to mint multiple tokens with the given tokenUris.677 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive678 /// numbers and first number should be obtained with `nextTokenId` method679 /// @param to The new owner680 /// @param tokens array of pairs of token ID and token URI for minted tokens681 #[solidity(rename_selector = "mintBulkWithTokenURI")]682 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]683 fn mint_bulk_with_token_uri(684 &mut self,685 caller: caller,686 to: address,687 tokens: Vec<(uint256, string)>,688 ) -> Result<bool> {689 let key = key::url();690 let caller = T::CrossAccountId::from_eth(caller);691 let to = T::CrossAccountId::from_eth(to);692 let mut expected_index = <TokensMinted<T>>::get(self.id)693 .checked_add(1)694 .ok_or("item id overflow")?;695 let budget = self696 .recorder697 .weight_calls_budget(<StructureWeight<T>>::find_parent());698699 let mut data = Vec::with_capacity(tokens.len());700 for (id, token_uri) in tokens {701 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;702 if id != expected_index {703 return Err("item id should be next".into());704 }705 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;706707 let mut properties = CollectionPropertiesVec::default();708 properties709 .try_push(Property {710 key: key.clone(),711 value: token_uri712 .into_bytes()713 .try_into()714 .map_err(|_| "token uri is too long")?,715 })716 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;717718 data.push(CreateItemData::<T> {719 properties,720 owner: to.clone(),721 });722 }723724 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)725 .map_err(dispatch_to_evm::<T>)?;726 Ok(true)727 }728}729730#[solidity_interface(731 name = UniqueNFT,732 is(733 ERC721,734 ERC721Metadata,735 ERC721Enumerable,736 ERC721UniqueExtensions,737 ERC721Mintable,738 ERC721Burnable,739 Collection(common_mut, CollectionHandle<T>),740 TokenProperties,741 )742)]743impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}744745// Not a tests, but code generators746generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);747generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);748749impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>750where751 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,752{753 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");754755 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {756 call::<T, UniqueNFTCall<T>, _, _>(handle, self)757 }758}pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -785,7 +785,7 @@
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
- Collection(common_mut, CollectionHandle<T>),
+ Collection(via(common_mut returns CollectionHandle<T>)),
TokenProperties,
)
)]