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.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -736,7 +736,7 @@
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
- Collection(common_mut, CollectionHandle<T>),
+ Collection(via(common_mut returns CollectionHandle<T>)),
TokenProperties,
)
)]
pallets/refungible/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//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use alloc::string::ToString;25use core::{26 char::{REPLACEMENT_CHARACTER, decode_utf16},27 convert::TryInto,28};29use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};30use frame_support::BoundedBTreeMap;31use pallet_common::{32 CollectionHandle, CollectionPropertyPermissions,33 erc::{34 CommonEvmHandler, CollectionCall,35 static_property::{key, value as property_value},36 },37};38use pallet_evm::{account::CrossAccountId, PrecompileHandle};39use pallet_evm_coder_substrate::{call, dispatch_to_evm};40use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};41use sp_core::H160;42use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};43use up_data_structs::{44 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,45 PropertyKeyPermission, PropertyPermission, TokenId,46};4748use crate::{49 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,50 TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,51};5253pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);5455/// @title A contract that allows to set and delete token properties and change token property permissions.56#[solidity_interface(name = TokenProperties)]57impl<T: Config> RefungibleHandle<T> {58 /// @notice Set permissions for token property.59 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.60 /// @param key Property key.61 /// @param isMutable Permission to mutate property.62 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.63 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.64 fn set_token_property_permission(65 &mut self,66 caller: caller,67 key: string,68 is_mutable: bool,69 collection_admin: bool,70 token_owner: bool,71 ) -> Result<()> {72 let caller = T::CrossAccountId::from_eth(caller);73 <Pallet<T>>::set_token_property_permissions(74 self,75 &caller,76 vec![PropertyKeyPermission {77 key: <Vec<u8>>::from(key)78 .try_into()79 .map_err(|_| "too long key")?,80 permission: PropertyPermission {81 mutable: is_mutable,82 collection_admin,83 token_owner,84 },85 }],86 )87 .map_err(dispatch_to_evm::<T>)88 }8990 /// @notice Set token property value.91 /// @dev Throws error if `msg.sender` has no permission to edit the property.92 /// @param tokenId ID of the token.93 /// @param key Property key.94 /// @param value Property value.95 fn set_property(96 &mut self,97 caller: caller,98 token_id: uint256,99 key: string,100 value: bytes,101 ) -> Result<()> {102 let caller = T::CrossAccountId::from_eth(caller);103 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;104 let key = <Vec<u8>>::from(key)105 .try_into()106 .map_err(|_| "key too long")?;107 let value = value.try_into().map_err(|_| "value too long")?;108109 let nesting_budget = self110 .recorder111 .weight_calls_budget(<StructureWeight<T>>::find_parent());112113 <Pallet<T>>::set_token_property(114 self,115 &caller,116 TokenId(token_id),117 Property { key, value },118 &nesting_budget,119 )120 .map_err(dispatch_to_evm::<T>)121 }122123 /// @notice Delete token property value.124 /// @dev Throws error if `msg.sender` has no permission to edit the property.125 /// @param tokenId ID of the token.126 /// @param key Property key.127 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {128 let caller = T::CrossAccountId::from_eth(caller);129 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;130 let key = <Vec<u8>>::from(key)131 .try_into()132 .map_err(|_| "key too long")?;133134 let nesting_budget = self135 .recorder136 .weight_calls_budget(<StructureWeight<T>>::find_parent());137138 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)139 .map_err(dispatch_to_evm::<T>)140 }141142 /// @notice Get token property value.143 /// @dev Throws error if key not found144 /// @param tokenId ID of the token.145 /// @param key Property key.146 /// @return Property value bytes147 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {148 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;149 let key = <Vec<u8>>::from(key)150 .try_into()151 .map_err(|_| "key too long")?;152153 let props = <TokenProperties<T>>::get((self.id, token_id));154 let prop = props.get(&key).ok_or("key not found")?;155156 Ok(prop.to_vec())157 }158}159160#[derive(ToLog)]161pub enum ERC721Events {162 /// @dev This event emits when NFTs are created (`from` == 0) and destroyed163 /// (`to` == 0). Exception: during contract creation, any number of RFTs164 /// may be created and assigned without emitting Transfer.165 Transfer {166 #[indexed]167 from: address,168 #[indexed]169 to: address,170 #[indexed]171 token_id: uint256,172 },173 /// @dev Not supported174 Approval {175 #[indexed]176 owner: address,177 #[indexed]178 approved: address,179 #[indexed]180 token_id: uint256,181 },182 /// @dev Not supported183 #[allow(dead_code)]184 ApprovalForAll {185 #[indexed]186 owner: address,187 #[indexed]188 operator: address,189 approved: bool,190 },191}192193#[derive(ToLog)]194pub enum ERC721MintableEvents {195 /// @dev Not supported196 #[allow(dead_code)]197 MintingFinished {},198}199200#[solidity_interface(name = ERC721Metadata)]201impl<T: Config> RefungibleHandle<T> {202 /// @notice A descriptive name for a collection of RFTs in this contract203 fn name(&self) -> Result<string> {204 Ok(decode_utf16(self.name.iter().copied())205 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))206 .collect::<string>())207 }208209 /// @notice An abbreviated name for RFTs in this contract210 fn symbol(&self) -> Result<string> {211 Ok(string::from_utf8_lossy(&self.token_prefix).into())212 }213214 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.215 ///216 /// @dev If the token has a `url` property and it is not empty, it is returned.217 /// 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`.218 /// If the collection property `baseURI` is empty or absent, return "" (empty string)219 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix220 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).221 ///222 /// @return token's const_metadata223 #[solidity(rename_selector = "tokenURI")]224 fn token_uri(&self, token_id: uint256) -> Result<string> {225 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;226227 if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {228 if !url.is_empty() {229 return Ok(url);230 }231 } else if !is_erc721_metadata_compatible::<T>(self.id) {232 return Err("tokenURI not set".into());233 }234235 if let Some(base_uri) =236 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())237 {238 if !base_uri.is_empty() {239 let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {240 Error::Revert(alloc::format!(241 "Can not convert value \"baseURI\" to string with error \"{}\"",242 e243 ))244 })?;245 if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {246 if !suffix.is_empty() {247 return Ok(base_uri + suffix.as_str());248 }249 }250251 return Ok(base_uri + token_id.to_string().as_str());252 }253 }254255 Ok("".into())256 }257}258259/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension260/// @dev See https://eips.ethereum.org/EIPS/eip-721261#[solidity_interface(name = ERC721Enumerable)]262impl<T: Config> RefungibleHandle<T> {263 /// @notice Enumerate valid RFTs264 /// @param index A counter less than `totalSupply()`265 /// @return The token identifier for the `index`th NFT,266 /// (sort order not specified)267 fn token_by_index(&self, index: uint256) -> Result<uint256> {268 Ok(index)269 }270271 /// Not implemented272 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {273 // TODO: Not implemetable274 Err("not implemented".into())275 }276277 /// @notice Count RFTs tracked by this contract278 /// @return A count of valid RFTs tracked by this contract, where each one of279 /// them has an assigned and queryable owner not equal to the zero address280 fn total_supply(&self) -> Result<uint256> {281 self.consume_store_reads(1)?;282 Ok(<Pallet<T>>::total_supply(self).into())283 }284}285286/// @title ERC-721 Non-Fungible Token Standard287/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md288#[solidity_interface(name = ERC721, events(ERC721Events))]289impl<T: Config> RefungibleHandle<T> {290 /// @notice Count all RFTs assigned to an owner291 /// @dev RFTs assigned to the zero address are considered invalid, and this292 /// function throws for queries about the zero address.293 /// @param owner An address for whom to query the balance294 /// @return The number of RFTs owned by `owner`, possibly zero295 fn balance_of(&self, owner: address) -> Result<uint256> {296 self.consume_store_reads(1)?;297 let owner = T::CrossAccountId::from_eth(owner);298 let balance = <AccountBalance<T>>::get((self.id, owner));299 Ok(balance.into())300 }301302 /// @notice Find the owner of an RFT303 /// @dev RFTs assigned to zero address are considered invalid, and queries304 /// about them do throw.305 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for306 /// the tokens that are partially owned.307 /// @param tokenId The identifier for an RFT308 /// @return The address of the owner of the RFT309 fn owner_of(&self, token_id: uint256) -> Result<address> {310 self.consume_store_reads(2)?;311 let token = token_id.try_into()?;312 let owner = <Pallet<T>>::token_owner(self.id, token);313 Ok(owner314 .map(|address| *address.as_eth())315 .unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))316 }317318 /// @dev Not implemented319 fn safe_transfer_from_with_data(320 &mut self,321 _from: address,322 _to: address,323 _token_id: uint256,324 _data: bytes,325 ) -> Result<void> {326 // TODO: Not implemetable327 Err("not implemented".into())328 }329330 /// @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 RFT -- 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 RFT. Throws if `from` is not the current owner. Throws346 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.347 /// Throws if RFT pieces have multiple owners.348 /// @param from The current owner of the NFT349 /// @param to The new owner350 /// @param tokenId The NFT to transfer351 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]352 fn transfer_from(353 &mut self,354 caller: caller,355 from: address,356 to: address,357 token_id: uint256,358 ) -> Result<void> {359 let caller = T::CrossAccountId::from_eth(caller);360 let from = T::CrossAccountId::from_eth(from);361 let to = T::CrossAccountId::from_eth(to);362 let token = token_id.try_into()?;363 let budget = self364 .recorder365 .weight_calls_budget(<StructureWeight<T>>::find_parent());366367 let balance = balance(&self, token, &from)?;368 ensure_single_owner(&self, token, balance)?;369370 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)371 .map_err(dispatch_to_evm::<T>)?;372373 Ok(())374 }375376 /// @dev Not implemented377 fn approve(&mut self, _caller: caller, _approved: address, _token_id: uint256) -> Result<void> {378 Err("not implemented".into())379 }380381 /// @dev Not implemented382 fn set_approval_for_all(383 &mut self,384 _caller: caller,385 _operator: address,386 _approved: bool,387 ) -> Result<void> {388 // TODO: Not implemetable389 Err("not implemented".into())390 }391392 /// @dev Not implemented393 fn get_approved(&self, _token_id: uint256) -> Result<address> {394 // TODO: Not implemetable395 Err("not implemented".into())396 }397398 /// @dev Not implemented399 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {400 // TODO: Not implemetable401 Err("not implemented".into())402 }403}404405/// Returns amount of pieces of `token` that `owner` have406pub fn balance<T: Config>(407 collection: &RefungibleHandle<T>,408 token: TokenId,409 owner: &T::CrossAccountId,410) -> Result<u128> {411 collection.consume_store_reads(1)?;412 let balance = <Balance<T>>::get((collection.id, token, &owner));413 Ok(balance)414}415416/// Throws if `owner_balance` is lower than total amount of `token` pieces417pub fn ensure_single_owner<T: Config>(418 collection: &RefungibleHandle<T>,419 token: TokenId,420 owner_balance: u128,421) -> Result<()> {422 collection.consume_store_reads(1)?;423 let total_supply = <TotalSupply<T>>::get((collection.id, token));424 if total_supply != owner_balance {425 return Err("token has multiple owners".into());426 }427 Ok(())428}429430/// @title ERC721 Token that can be irreversibly burned (destroyed).431#[solidity_interface(name = ERC721Burnable)]432impl<T: Config> RefungibleHandle<T> {433 /// @notice Burns a specific ERC721 token.434 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized435 /// operator of the current owner.436 /// @param tokenId The RFT to approve437 #[weight(<SelfWeightOf<T>>::burn_item_fully())]438 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {439 let caller = T::CrossAccountId::from_eth(caller);440 let token = token_id.try_into()?;441442 let balance = balance(&self, token, &caller)?;443 ensure_single_owner(&self, token, balance)?;444445 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;446 Ok(())447 }448}449450/// @title ERC721 minting logic.451#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]452impl<T: Config> RefungibleHandle<T> {453 fn minting_finished(&self) -> Result<bool> {454 Ok(false)455 }456457 /// @notice Function to mint token.458 /// @dev `tokenId` should be obtained with `nextTokenId` method,459 /// unlike standard, you can't specify it manually460 /// @param to The new owner461 /// @param tokenId ID of the minted RFT462 #[weight(<SelfWeightOf<T>>::create_item())]463 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {464 let caller = T::CrossAccountId::from_eth(caller);465 let to = T::CrossAccountId::from_eth(to);466 let token_id: u32 = token_id.try_into()?;467 let budget = self468 .recorder469 .weight_calls_budget(<StructureWeight<T>>::find_parent());470471 if <TokensMinted<T>>::get(self.id)472 .checked_add(1)473 .ok_or("item id overflow")?474 != token_id475 {476 return Err("item id should be next".into());477 }478479 let users = [(to.clone(), 1)]480 .into_iter()481 .collect::<BTreeMap<_, _>>()482 .try_into()483 .unwrap();484 <Pallet<T>>::create_item(485 self,486 &caller,487 CreateItemData::<T::CrossAccountId> {488 users,489 properties: CollectionPropertiesVec::default(),490 },491 &budget,492 )493 .map_err(dispatch_to_evm::<T>)?;494495 Ok(true)496 }497498 /// @notice Function to mint token with the given tokenUri.499 /// @dev `tokenId` should be obtained with `nextTokenId` method,500 /// unlike standard, you can't specify it manually501 /// @param to The new owner502 /// @param tokenId ID of the minted RFT503 /// @param tokenUri Token URI that would be stored in the RFT properties504 #[solidity(rename_selector = "mintWithTokenURI")]505 #[weight(<SelfWeightOf<T>>::create_item())]506 fn mint_with_token_uri(507 &mut self,508 caller: caller,509 to: address,510 token_id: uint256,511 token_uri: string,512 ) -> Result<bool> {513 let key = key::url();514 let permission = get_token_permission::<T>(self.id, &key)?;515 if !permission.collection_admin {516 return Err("Operation is not allowed".into());517 }518519 let caller = T::CrossAccountId::from_eth(caller);520 let to = T::CrossAccountId::from_eth(to);521 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;522 let budget = self523 .recorder524 .weight_calls_budget(<StructureWeight<T>>::find_parent());525526 if <TokensMinted<T>>::get(self.id)527 .checked_add(1)528 .ok_or("item id overflow")?529 != token_id530 {531 return Err("item id should be next".into());532 }533534 let mut properties = CollectionPropertiesVec::default();535 properties536 .try_push(Property {537 key,538 value: token_uri539 .into_bytes()540 .try_into()541 .map_err(|_| "token uri is too long")?,542 })543 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;544545 let users = [(to.clone(), 1)]546 .into_iter()547 .collect::<BTreeMap<_, _>>()548 .try_into()549 .unwrap();550 <Pallet<T>>::create_item(551 self,552 &caller,553 CreateItemData::<T::CrossAccountId> { users, properties },554 &budget,555 )556 .map_err(dispatch_to_evm::<T>)?;557 Ok(true)558 }559560 /// @dev Not implemented561 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {562 Err("not implementable".into())563 }564}565566fn get_token_property<T: Config>(567 collection: &CollectionHandle<T>,568 token_id: u32,569 key: &up_data_structs::PropertyKey,570) -> Result<string> {571 collection.consume_store_reads(1)?;572 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))573 .map_err(|_| Error::Revert("Token properties not found".into()))?;574 if let Some(property) = properties.get(key) {575 return Ok(string::from_utf8_lossy(property).into());576 }577578 Err("Property tokenURI not found".into())579}580581fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {582 if let Some(shema_name) =583 pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())584 {585 let shema_name = shema_name.into_inner();586 shema_name == property_value::ERC721_METADATA587 } else {588 false589 }590}591592fn get_token_permission<T: Config>(593 collection_id: CollectionId,594 key: &PropertyKey,595) -> Result<PropertyPermission> {596 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)597 .map_err(|_| Error::Revert("No permissions for collection".into()))?;598 let a = token_property_permissions599 .get(key)600 .map(Clone::clone)601 .ok_or_else(|| {602 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();603 Error::Revert(alloc::format!("No permission for key {}", key))604 })?;605 Ok(a)606}607608/// @title Unique extensions for ERC721.609#[solidity_interface(name = ERC721UniqueExtensions)]610impl<T: Config> RefungibleHandle<T> {611 /// @notice Transfer ownership of an RFT612 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`613 /// is the zero address. Throws if `tokenId` is not a valid RFT.614 /// Throws if RFT pieces have multiple owners.615 /// @param to The new owner616 /// @param tokenId The RFT to transfer617 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]618 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {619 let caller = T::CrossAccountId::from_eth(caller);620 let to = T::CrossAccountId::from_eth(to);621 let token = token_id.try_into()?;622 let budget = self623 .recorder624 .weight_calls_budget(<StructureWeight<T>>::find_parent());625626 let balance = balance(&self, token, &caller)?;627 ensure_single_owner(&self, token, balance)?;628629 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)630 .map_err(dispatch_to_evm::<T>)?;631 Ok(())632 }633634 /// @notice Burns a specific ERC721 token.635 /// @dev Throws unless `msg.sender` is the current owner or an authorized636 /// operator for this RFT. Throws if `from` is not the current owner. Throws637 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.638 /// Throws if RFT pieces have multiple owners.639 /// @param from The current owner of the RFT640 /// @param tokenId The RFT to transfer641 #[weight(<SelfWeightOf<T>>::burn_from())]642 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {643 let caller = T::CrossAccountId::from_eth(caller);644 let from = T::CrossAccountId::from_eth(from);645 let token = token_id.try_into()?;646 let budget = self647 .recorder648 .weight_calls_budget(<StructureWeight<T>>::find_parent());649650 let balance = balance(&self, token, &caller)?;651 ensure_single_owner(&self, token, balance)?;652653 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)654 .map_err(dispatch_to_evm::<T>)?;655 Ok(())656 }657658 /// @notice Returns next free RFT ID.659 fn next_token_id(&self) -> Result<uint256> {660 self.consume_store_reads(1)?;661 Ok(<TokensMinted<T>>::get(self.id)662 .checked_add(1)663 .ok_or("item id overflow")?664 .into())665 }666667 /// @notice Function to mint multiple tokens.668 /// @dev `tokenIds` should be an array of consecutive numbers and first number669 /// should be obtained with `nextTokenId` method670 /// @param to The new owner671 /// @param tokenIds IDs of the minted RFTs672 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]673 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {674 let caller = T::CrossAccountId::from_eth(caller);675 let to = T::CrossAccountId::from_eth(to);676 let mut expected_index = <TokensMinted<T>>::get(self.id)677 .checked_add(1)678 .ok_or("item id overflow")?;679 let budget = self680 .recorder681 .weight_calls_budget(<StructureWeight<T>>::find_parent());682683 let total_tokens = token_ids.len();684 for id in token_ids.into_iter() {685 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;686 if id != expected_index {687 return Err("item id should be next".into());688 }689 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;690 }691 let users = [(to.clone(), 1)]692 .into_iter()693 .collect::<BTreeMap<_, _>>()694 .try_into()695 .unwrap();696 let create_item_data = CreateItemData::<T::CrossAccountId> {697 users,698 properties: CollectionPropertiesVec::default(),699 };700 let data = (0..total_tokens)701 .map(|_| create_item_data.clone())702 .collect();703704 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)705 .map_err(dispatch_to_evm::<T>)?;706 Ok(true)707 }708709 /// @notice Function to mint multiple tokens with the given tokenUris.710 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive711 /// numbers and first number should be obtained with `nextTokenId` method712 /// @param to The new owner713 /// @param tokens array of pairs of token ID and token URI for minted tokens714 #[solidity(rename_selector = "mintBulkWithTokenURI")]715 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]716 fn mint_bulk_with_token_uri(717 &mut self,718 caller: caller,719 to: address,720 tokens: Vec<(uint256, string)>,721 ) -> Result<bool> {722 let key = key::url();723 let caller = T::CrossAccountId::from_eth(caller);724 let to = T::CrossAccountId::from_eth(to);725 let mut expected_index = <TokensMinted<T>>::get(self.id)726 .checked_add(1)727 .ok_or("item id overflow")?;728 let budget = self729 .recorder730 .weight_calls_budget(<StructureWeight<T>>::find_parent());731732 let mut data = Vec::with_capacity(tokens.len());733 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]734 .into_iter()735 .collect::<BTreeMap<_, _>>()736 .try_into()737 .unwrap();738 for (id, token_uri) in tokens {739 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;740 if id != expected_index {741 return Err("item id should be next".into());742 }743 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;744745 let mut properties = CollectionPropertiesVec::default();746 properties747 .try_push(Property {748 key: key.clone(),749 value: token_uri750 .into_bytes()751 .try_into()752 .map_err(|_| "token uri is too long")?,753 })754 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;755756 let create_item_data = CreateItemData::<T::CrossAccountId> {757 users: users.clone(),758 properties,759 };760 data.push(create_item_data);761 }762763 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)764 .map_err(dispatch_to_evm::<T>)?;765 Ok(true)766 }767768 /// Returns EVM address for refungible token769 ///770 /// @param token ID of the token771 fn token_contract_address(&self, token: uint256) -> Result<address> {772 Ok(T::EvmTokenAddressMapping::token_to_address(773 self.id,774 token.try_into().map_err(|_| "token id overflow")?,775 ))776 }777}778779#[solidity_interface(780 name = UniqueRefungible,781 is(782 ERC721,783 ERC721Metadata,784 ERC721Enumerable,785 ERC721UniqueExtensions,786 ERC721Mintable,787 ERC721Burnable,788 Collection(common_mut, CollectionHandle<T>),789 TokenProperties,790 )791)]792impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}793794// Not a tests, but code generators795generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);796generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);797798impl<T: Config> CommonEvmHandler for RefungibleHandle<T>799where800 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,801{802 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");803 fn call(804 self,805 handle: &mut impl PrecompileHandle,806 ) -> Option<pallet_common::erc::PrecompileResult> {807 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)808 }809}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/>.1617//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use alloc::string::ToString;25use core::{26 char::{REPLACEMENT_CHARACTER, decode_utf16},27 convert::TryInto,28};29use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};30use frame_support::BoundedBTreeMap;31use pallet_common::{32 CollectionHandle, CollectionPropertyPermissions,33 erc::{34 CommonEvmHandler, CollectionCall,35 static_property::{key, value as property_value},36 },37};38use pallet_evm::{account::CrossAccountId, PrecompileHandle};39use pallet_evm_coder_substrate::{call, dispatch_to_evm};40use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};41use sp_core::H160;42use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};43use up_data_structs::{44 CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,45 PropertyKeyPermission, PropertyPermission, TokenId,46};4748use crate::{49 AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,50 TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,51};5253pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);5455/// @title A contract that allows to set and delete token properties and change token property permissions.56#[solidity_interface(name = TokenProperties)]57impl<T: Config> RefungibleHandle<T> {58 /// @notice Set permissions for token property.59 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.60 /// @param key Property key.61 /// @param isMutable Permission to mutate property.62 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.63 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.64 fn set_token_property_permission(65 &mut self,66 caller: caller,67 key: string,68 is_mutable: bool,69 collection_admin: bool,70 token_owner: bool,71 ) -> Result<()> {72 let caller = T::CrossAccountId::from_eth(caller);73 <Pallet<T>>::set_token_property_permissions(74 self,75 &caller,76 vec![PropertyKeyPermission {77 key: <Vec<u8>>::from(key)78 .try_into()79 .map_err(|_| "too long key")?,80 permission: PropertyPermission {81 mutable: is_mutable,82 collection_admin,83 token_owner,84 },85 }],86 )87 .map_err(dispatch_to_evm::<T>)88 }8990 /// @notice Set token property value.91 /// @dev Throws error if `msg.sender` has no permission to edit the property.92 /// @param tokenId ID of the token.93 /// @param key Property key.94 /// @param value Property value.95 fn set_property(96 &mut self,97 caller: caller,98 token_id: uint256,99 key: string,100 value: bytes,101 ) -> Result<()> {102 let caller = T::CrossAccountId::from_eth(caller);103 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;104 let key = <Vec<u8>>::from(key)105 .try_into()106 .map_err(|_| "key too long")?;107 let value = value.try_into().map_err(|_| "value too long")?;108109 let nesting_budget = self110 .recorder111 .weight_calls_budget(<StructureWeight<T>>::find_parent());112113 <Pallet<T>>::set_token_property(114 self,115 &caller,116 TokenId(token_id),117 Property { key, value },118 &nesting_budget,119 )120 .map_err(dispatch_to_evm::<T>)121 }122123 /// @notice Delete token property value.124 /// @dev Throws error if `msg.sender` has no permission to edit the property.125 /// @param tokenId ID of the token.126 /// @param key Property key.127 fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {128 let caller = T::CrossAccountId::from_eth(caller);129 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;130 let key = <Vec<u8>>::from(key)131 .try_into()132 .map_err(|_| "key too long")?;133134 let nesting_budget = self135 .recorder136 .weight_calls_budget(<StructureWeight<T>>::find_parent());137138 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)139 .map_err(dispatch_to_evm::<T>)140 }141142 /// @notice Get token property value.143 /// @dev Throws error if key not found144 /// @param tokenId ID of the token.145 /// @param key Property key.146 /// @return Property value bytes147 fn property(&self, token_id: uint256, key: string) -> Result<bytes> {148 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;149 let key = <Vec<u8>>::from(key)150 .try_into()151 .map_err(|_| "key too long")?;152153 let props = <TokenProperties<T>>::get((self.id, token_id));154 let prop = props.get(&key).ok_or("key not found")?;155156 Ok(prop.to_vec())157 }158}159160#[derive(ToLog)]161pub enum ERC721Events {162 /// @dev This event emits when NFTs are created (`from` == 0) and destroyed163 /// (`to` == 0). Exception: during contract creation, any number of RFTs164 /// may be created and assigned without emitting Transfer.165 Transfer {166 #[indexed]167 from: address,168 #[indexed]169 to: address,170 #[indexed]171 token_id: uint256,172 },173 /// @dev Not supported174 Approval {175 #[indexed]176 owner: address,177 #[indexed]178 approved: address,179 #[indexed]180 token_id: uint256,181 },182 /// @dev Not supported183 #[allow(dead_code)]184 ApprovalForAll {185 #[indexed]186 owner: address,187 #[indexed]188 operator: address,189 approved: bool,190 },191}192193#[derive(ToLog)]194pub enum ERC721MintableEvents {195 /// @dev Not supported196 #[allow(dead_code)]197 MintingFinished {},198}199200#[solidity_interface(name = ERC721Metadata)]201impl<T: Config> RefungibleHandle<T> {202 /// @notice A descriptive name for a collection of RFTs in this contract203 fn name(&self) -> Result<string> {204 Ok(decode_utf16(self.name.iter().copied())205 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))206 .collect::<string>())207 }208209 /// @notice An abbreviated name for RFTs in this contract210 fn symbol(&self) -> Result<string> {211 Ok(string::from_utf8_lossy(&self.token_prefix).into())212 }213214 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.215 ///216 /// @dev If the token has a `url` property and it is not empty, it is returned.217 /// 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`.218 /// If the collection property `baseURI` is empty or absent, return "" (empty string)219 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix220 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).221 ///222 /// @return token's const_metadata223 #[solidity(rename_selector = "tokenURI")]224 fn token_uri(&self, token_id: uint256) -> Result<string> {225 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;226227 if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {228 if !url.is_empty() {229 return Ok(url);230 }231 } else if !is_erc721_metadata_compatible::<T>(self.id) {232 return Err("tokenURI not set".into());233 }234235 if let Some(base_uri) =236 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())237 {238 if !base_uri.is_empty() {239 let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {240 Error::Revert(alloc::format!(241 "Can not convert value \"baseURI\" to string with error \"{}\"",242 e243 ))244 })?;245 if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {246 if !suffix.is_empty() {247 return Ok(base_uri + suffix.as_str());248 }249 }250251 return Ok(base_uri + token_id.to_string().as_str());252 }253 }254255 Ok("".into())256 }257}258259/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension260/// @dev See https://eips.ethereum.org/EIPS/eip-721261#[solidity_interface(name = ERC721Enumerable)]262impl<T: Config> RefungibleHandle<T> {263 /// @notice Enumerate valid RFTs264 /// @param index A counter less than `totalSupply()`265 /// @return The token identifier for the `index`th NFT,266 /// (sort order not specified)267 fn token_by_index(&self, index: uint256) -> Result<uint256> {268 Ok(index)269 }270271 /// Not implemented272 fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {273 // TODO: Not implemetable274 Err("not implemented".into())275 }276277 /// @notice Count RFTs tracked by this contract278 /// @return A count of valid RFTs tracked by this contract, where each one of279 /// them has an assigned and queryable owner not equal to the zero address280 fn total_supply(&self) -> Result<uint256> {281 self.consume_store_reads(1)?;282 Ok(<Pallet<T>>::total_supply(self).into())283 }284}285286/// @title ERC-721 Non-Fungible Token Standard287/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md288#[solidity_interface(name = ERC721, events(ERC721Events))]289impl<T: Config> RefungibleHandle<T> {290 /// @notice Count all RFTs assigned to an owner291 /// @dev RFTs assigned to the zero address are considered invalid, and this292 /// function throws for queries about the zero address.293 /// @param owner An address for whom to query the balance294 /// @return The number of RFTs owned by `owner`, possibly zero295 fn balance_of(&self, owner: address) -> Result<uint256> {296 self.consume_store_reads(1)?;297 let owner = T::CrossAccountId::from_eth(owner);298 let balance = <AccountBalance<T>>::get((self.id, owner));299 Ok(balance.into())300 }301302 /// @notice Find the owner of an RFT303 /// @dev RFTs assigned to zero address are considered invalid, and queries304 /// about them do throw.305 /// Returns special 0xffffffffffffffffffffffffffffffffffffffff address for306 /// the tokens that are partially owned.307 /// @param tokenId The identifier for an RFT308 /// @return The address of the owner of the RFT309 fn owner_of(&self, token_id: uint256) -> Result<address> {310 self.consume_store_reads(2)?;311 let token = token_id.try_into()?;312 let owner = <Pallet<T>>::token_owner(self.id, token);313 Ok(owner314 .map(|address| *address.as_eth())315 .unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))316 }317318 /// @dev Not implemented319 fn safe_transfer_from_with_data(320 &mut self,321 _from: address,322 _to: address,323 _token_id: uint256,324 _data: bytes,325 ) -> Result<void> {326 // TODO: Not implemetable327 Err("not implemented".into())328 }329330 /// @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 RFT -- 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 RFT. Throws if `from` is not the current owner. Throws346 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.347 /// Throws if RFT pieces have multiple owners.348 /// @param from The current owner of the NFT349 /// @param to The new owner350 /// @param tokenId The NFT to transfer351 #[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]352 fn transfer_from(353 &mut self,354 caller: caller,355 from: address,356 to: address,357 token_id: uint256,358 ) -> Result<void> {359 let caller = T::CrossAccountId::from_eth(caller);360 let from = T::CrossAccountId::from_eth(from);361 let to = T::CrossAccountId::from_eth(to);362 let token = token_id.try_into()?;363 let budget = self364 .recorder365 .weight_calls_budget(<StructureWeight<T>>::find_parent());366367 let balance = balance(&self, token, &from)?;368 ensure_single_owner(&self, token, balance)?;369370 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)371 .map_err(dispatch_to_evm::<T>)?;372373 Ok(())374 }375376 /// @dev Not implemented377 fn approve(&mut self, _caller: caller, _approved: address, _token_id: uint256) -> Result<void> {378 Err("not implemented".into())379 }380381 /// @dev Not implemented382 fn set_approval_for_all(383 &mut self,384 _caller: caller,385 _operator: address,386 _approved: bool,387 ) -> Result<void> {388 // TODO: Not implemetable389 Err("not implemented".into())390 }391392 /// @dev Not implemented393 fn get_approved(&self, _token_id: uint256) -> Result<address> {394 // TODO: Not implemetable395 Err("not implemented".into())396 }397398 /// @dev Not implemented399 fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {400 // TODO: Not implemetable401 Err("not implemented".into())402 }403}404405/// Returns amount of pieces of `token` that `owner` have406pub fn balance<T: Config>(407 collection: &RefungibleHandle<T>,408 token: TokenId,409 owner: &T::CrossAccountId,410) -> Result<u128> {411 collection.consume_store_reads(1)?;412 let balance = <Balance<T>>::get((collection.id, token, &owner));413 Ok(balance)414}415416/// Throws if `owner_balance` is lower than total amount of `token` pieces417pub fn ensure_single_owner<T: Config>(418 collection: &RefungibleHandle<T>,419 token: TokenId,420 owner_balance: u128,421) -> Result<()> {422 collection.consume_store_reads(1)?;423 let total_supply = <TotalSupply<T>>::get((collection.id, token));424 if total_supply != owner_balance {425 return Err("token has multiple owners".into());426 }427 Ok(())428}429430/// @title ERC721 Token that can be irreversibly burned (destroyed).431#[solidity_interface(name = ERC721Burnable)]432impl<T: Config> RefungibleHandle<T> {433 /// @notice Burns a specific ERC721 token.434 /// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized435 /// operator of the current owner.436 /// @param tokenId The RFT to approve437 #[weight(<SelfWeightOf<T>>::burn_item_fully())]438 fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {439 let caller = T::CrossAccountId::from_eth(caller);440 let token = token_id.try_into()?;441442 let balance = balance(&self, token, &caller)?;443 ensure_single_owner(&self, token, balance)?;444445 <Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;446 Ok(())447 }448}449450/// @title ERC721 minting logic.451#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]452impl<T: Config> RefungibleHandle<T> {453 fn minting_finished(&self) -> Result<bool> {454 Ok(false)455 }456457 /// @notice Function to mint token.458 /// @dev `tokenId` should be obtained with `nextTokenId` method,459 /// unlike standard, you can't specify it manually460 /// @param to The new owner461 /// @param tokenId ID of the minted RFT462 #[weight(<SelfWeightOf<T>>::create_item())]463 fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {464 let caller = T::CrossAccountId::from_eth(caller);465 let to = T::CrossAccountId::from_eth(to);466 let token_id: u32 = token_id.try_into()?;467 let budget = self468 .recorder469 .weight_calls_budget(<StructureWeight<T>>::find_parent());470471 if <TokensMinted<T>>::get(self.id)472 .checked_add(1)473 .ok_or("item id overflow")?474 != token_id475 {476 return Err("item id should be next".into());477 }478479 let users = [(to.clone(), 1)]480 .into_iter()481 .collect::<BTreeMap<_, _>>()482 .try_into()483 .unwrap();484 <Pallet<T>>::create_item(485 self,486 &caller,487 CreateItemData::<T::CrossAccountId> {488 users,489 properties: CollectionPropertiesVec::default(),490 },491 &budget,492 )493 .map_err(dispatch_to_evm::<T>)?;494495 Ok(true)496 }497498 /// @notice Function to mint token with the given tokenUri.499 /// @dev `tokenId` should be obtained with `nextTokenId` method,500 /// unlike standard, you can't specify it manually501 /// @param to The new owner502 /// @param tokenId ID of the minted RFT503 /// @param tokenUri Token URI that would be stored in the RFT properties504 #[solidity(rename_selector = "mintWithTokenURI")]505 #[weight(<SelfWeightOf<T>>::create_item())]506 fn mint_with_token_uri(507 &mut self,508 caller: caller,509 to: address,510 token_id: uint256,511 token_uri: string,512 ) -> Result<bool> {513 let key = key::url();514 let permission = get_token_permission::<T>(self.id, &key)?;515 if !permission.collection_admin {516 return Err("Operation is not allowed".into());517 }518519 let caller = T::CrossAccountId::from_eth(caller);520 let to = T::CrossAccountId::from_eth(to);521 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;522 let budget = self523 .recorder524 .weight_calls_budget(<StructureWeight<T>>::find_parent());525526 if <TokensMinted<T>>::get(self.id)527 .checked_add(1)528 .ok_or("item id overflow")?529 != token_id530 {531 return Err("item id should be next".into());532 }533534 let mut properties = CollectionPropertiesVec::default();535 properties536 .try_push(Property {537 key,538 value: token_uri539 .into_bytes()540 .try_into()541 .map_err(|_| "token uri is too long")?,542 })543 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;544545 let users = [(to.clone(), 1)]546 .into_iter()547 .collect::<BTreeMap<_, _>>()548 .try_into()549 .unwrap();550 <Pallet<T>>::create_item(551 self,552 &caller,553 CreateItemData::<T::CrossAccountId> { users, properties },554 &budget,555 )556 .map_err(dispatch_to_evm::<T>)?;557 Ok(true)558 }559560 /// @dev Not implemented561 fn finish_minting(&mut self, _caller: caller) -> Result<bool> {562 Err("not implementable".into())563 }564}565566fn get_token_property<T: Config>(567 collection: &CollectionHandle<T>,568 token_id: u32,569 key: &up_data_structs::PropertyKey,570) -> Result<string> {571 collection.consume_store_reads(1)?;572 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))573 .map_err(|_| Error::Revert("Token properties not found".into()))?;574 if let Some(property) = properties.get(key) {575 return Ok(string::from_utf8_lossy(property).into());576 }577578 Err("Property tokenURI not found".into())579}580581fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {582 if let Some(shema_name) =583 pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())584 {585 let shema_name = shema_name.into_inner();586 shema_name == property_value::ERC721_METADATA587 } else {588 false589 }590}591592fn get_token_permission<T: Config>(593 collection_id: CollectionId,594 key: &PropertyKey,595) -> Result<PropertyPermission> {596 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)597 .map_err(|_| Error::Revert("No permissions for collection".into()))?;598 let a = token_property_permissions599 .get(key)600 .map(Clone::clone)601 .ok_or_else(|| {602 let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();603 Error::Revert(alloc::format!("No permission for key {}", key))604 })?;605 Ok(a)606}607608/// @title Unique extensions for ERC721.609#[solidity_interface(name = ERC721UniqueExtensions)]610impl<T: Config> RefungibleHandle<T> {611 /// @notice Transfer ownership of an RFT612 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`613 /// is the zero address. Throws if `tokenId` is not a valid RFT.614 /// Throws if RFT pieces have multiple owners.615 /// @param to The new owner616 /// @param tokenId The RFT to transfer617 #[weight(<SelfWeightOf<T>>::transfer_creating_removing())]618 fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {619 let caller = T::CrossAccountId::from_eth(caller);620 let to = T::CrossAccountId::from_eth(to);621 let token = token_id.try_into()?;622 let budget = self623 .recorder624 .weight_calls_budget(<StructureWeight<T>>::find_parent());625626 let balance = balance(&self, token, &caller)?;627 ensure_single_owner(&self, token, balance)?;628629 <Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)630 .map_err(dispatch_to_evm::<T>)?;631 Ok(())632 }633634 /// @notice Burns a specific ERC721 token.635 /// @dev Throws unless `msg.sender` is the current owner or an authorized636 /// operator for this RFT. Throws if `from` is not the current owner. Throws637 /// if `to` is the zero address. Throws if `tokenId` is not a valid RFT.638 /// Throws if RFT pieces have multiple owners.639 /// @param from The current owner of the RFT640 /// @param tokenId The RFT to transfer641 #[weight(<SelfWeightOf<T>>::burn_from())]642 fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {643 let caller = T::CrossAccountId::from_eth(caller);644 let from = T::CrossAccountId::from_eth(from);645 let token = token_id.try_into()?;646 let budget = self647 .recorder648 .weight_calls_budget(<StructureWeight<T>>::find_parent());649650 let balance = balance(&self, token, &caller)?;651 ensure_single_owner(&self, token, balance)?;652653 <Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)654 .map_err(dispatch_to_evm::<T>)?;655 Ok(())656 }657658 /// @notice Returns next free RFT ID.659 fn next_token_id(&self) -> Result<uint256> {660 self.consume_store_reads(1)?;661 Ok(<TokensMinted<T>>::get(self.id)662 .checked_add(1)663 .ok_or("item id overflow")?664 .into())665 }666667 /// @notice Function to mint multiple tokens.668 /// @dev `tokenIds` should be an array of consecutive numbers and first number669 /// should be obtained with `nextTokenId` method670 /// @param to The new owner671 /// @param tokenIds IDs of the minted RFTs672 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]673 fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {674 let caller = T::CrossAccountId::from_eth(caller);675 let to = T::CrossAccountId::from_eth(to);676 let mut expected_index = <TokensMinted<T>>::get(self.id)677 .checked_add(1)678 .ok_or("item id overflow")?;679 let budget = self680 .recorder681 .weight_calls_budget(<StructureWeight<T>>::find_parent());682683 let total_tokens = token_ids.len();684 for id in token_ids.into_iter() {685 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;686 if id != expected_index {687 return Err("item id should be next".into());688 }689 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;690 }691 let users = [(to.clone(), 1)]692 .into_iter()693 .collect::<BTreeMap<_, _>>()694 .try_into()695 .unwrap();696 let create_item_data = CreateItemData::<T::CrossAccountId> {697 users,698 properties: CollectionPropertiesVec::default(),699 };700 let data = (0..total_tokens)701 .map(|_| create_item_data.clone())702 .collect();703704 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)705 .map_err(dispatch_to_evm::<T>)?;706 Ok(true)707 }708709 /// @notice Function to mint multiple tokens with the given tokenUris.710 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive711 /// numbers and first number should be obtained with `nextTokenId` method712 /// @param to The new owner713 /// @param tokens array of pairs of token ID and token URI for minted tokens714 #[solidity(rename_selector = "mintBulkWithTokenURI")]715 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]716 fn mint_bulk_with_token_uri(717 &mut self,718 caller: caller,719 to: address,720 tokens: Vec<(uint256, string)>,721 ) -> Result<bool> {722 let key = key::url();723 let caller = T::CrossAccountId::from_eth(caller);724 let to = T::CrossAccountId::from_eth(to);725 let mut expected_index = <TokensMinted<T>>::get(self.id)726 .checked_add(1)727 .ok_or("item id overflow")?;728 let budget = self729 .recorder730 .weight_calls_budget(<StructureWeight<T>>::find_parent());731732 let mut data = Vec::with_capacity(tokens.len());733 let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]734 .into_iter()735 .collect::<BTreeMap<_, _>>()736 .try_into()737 .unwrap();738 for (id, token_uri) in tokens {739 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;740 if id != expected_index {741 return Err("item id should be next".into());742 }743 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;744745 let mut properties = CollectionPropertiesVec::default();746 properties747 .try_push(Property {748 key: key.clone(),749 value: token_uri750 .into_bytes()751 .try_into()752 .map_err(|_| "token uri is too long")?,753 })754 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;755756 let create_item_data = CreateItemData::<T::CrossAccountId> {757 users: users.clone(),758 properties,759 };760 data.push(create_item_data);761 }762763 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)764 .map_err(dispatch_to_evm::<T>)?;765 Ok(true)766 }767768 /// Returns EVM address for refungible token769 ///770 /// @param token ID of the token771 fn token_contract_address(&self, token: uint256) -> Result<address> {772 Ok(T::EvmTokenAddressMapping::token_to_address(773 self.id,774 token.try_into().map_err(|_| "token id overflow")?,775 ))776 }777}778779#[solidity_interface(780 name = UniqueRefungible,781 is(782 ERC721,783 ERC721Metadata,784 ERC721Enumerable,785 ERC721UniqueExtensions,786 ERC721Mintable,787 ERC721Burnable,788 Collection(via(common_mut returns CollectionHandle<T>)),789 TokenProperties,790 )791)]792impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}793794// Not a tests, but code generators795generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);796generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);797798impl<T: Config> CommonEvmHandler for RefungibleHandle<T>799where800 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,801{802 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");803 fn call(804 self,805 handle: &mut impl PrecompileHandle,806 ) -> Option<pallet_common::erc::PrecompileResult> {807 call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)808 }809}