difftreelog
Merge pull request #542 from UniqueNetwork/fix/RFT_and_fractionalizer
in: master
14 files changed
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -281,15 +281,6 @@
let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;
}: {<Pallet<T>>::repartition(&collection, &owner, item, 200)?}
- set_parent_nft_unchecked {
- bench_init!{
- owner: sub; collection: collection(owner);
- sender: cross_from_sub(owner); owner: cross_sub;
- };
- let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;
-
- }: {<Pallet<T>>::set_parent_nft_unchecked(&collection, item, owner, T::CrossAccountId::from_eth(H160::default()))?}
-
token_owner {
bench_init!{
owner: sub; collection: collection(owner);
pallets/refungible/src/erc_token.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -29,22 +29,21 @@
convert::TryInto,
ops::Deref,
};
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
use pallet_common::{
CommonWeightInfo,
- erc::{CommonEvmHandler, PrecompileResult, static_property::key},
- eth::map_eth_to_id,
+ erc::{CommonEvmHandler, PrecompileResult},
+ eth::collection_id_to_address,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};
use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
-use sp_core::H160;
use sp_std::vec::Vec;
-use up_data_structs::{mapping::TokenAddressMapping, PropertyScope, TokenId};
+use up_data_structs::TokenId;
use crate::{
Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,
- TokenProperties, TotalSupply, weights::WeightInfo,
+ TotalSupply, weights::WeightInfo,
};
pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);
@@ -52,63 +51,14 @@
#[solidity_interface(name = ERC1633)]
impl<T: Config> RefungibleTokenHandle<T> {
fn parent_token(&self) -> Result<address> {
- self.consume_store_reads(2)?;
- let props = <TokenProperties<T>>::get((self.id, self.1));
- let key = key::parent_nft();
-
- let key_scoped = PropertyScope::Eth
- .apply(key)
- .expect("property key shouldn't exceed length limit");
- if let Some(value) = props.get(&key_scoped) {
- Ok(H160::from_slice(value.as_slice()))
- } else {
- Ok(*T::CrossTokenAddressMapping::token_to_address(self.id, self.1).as_eth())
- }
+ Ok(collection_id_to_address(self.id))
}
fn parent_token_id(&self) -> Result<uint256> {
- self.consume_store_reads(2)?;
- let props = <TokenProperties<T>>::get((self.id, self.1));
- let key = key::parent_nft();
-
- let key_scoped = PropertyScope::Eth
- .apply(key)
- .expect("property key shouldn't exceed length limit");
- if let Some(value) = props.get(&key_scoped) {
- let nft_token_address = H160::from_slice(value.as_slice());
- let nft_token_account = T::CrossAccountId::from_eth(nft_token_address);
- let (_, token_id) = T::CrossTokenAddressMapping::address_to_token(&nft_token_account)
- .ok_or("parent NFT should contain NFT token address")?;
-
- Ok(token_id.into())
- } else {
- Ok(self.1.into())
- }
+ Ok(self.1.into())
}
}
-#[solidity_interface(name = ERC1633UniqueExtensions)]
-impl<T: Config> RefungibleTokenHandle<T> {
- #[solidity(rename_selector = "setParentNFT")]
- #[weight(<CommonWeights<T>>::token_owner() + <SelfWeightOf<T>>::set_parent_nft_unchecked())]
- fn set_parent_nft(
- &mut self,
- caller: caller,
- collection: address,
- nft_id: uint256,
- ) -> Result<bool> {
- self.consume_store_reads(1)?;
- let caller = T::CrossAccountId::from_eth(caller);
- let nft_collection = map_eth_to_id(&collection).ok_or("collection not found")?;
- let nft_token = nft_id.try_into()?;
-
- <Pallet<T>>::set_parent_nft(&self.0, self.1, caller, nft_collection, nft_token)
- .map_err(dispatch_to_evm::<T>)?;
-
- Ok(true)
- }
-}
-
#[derive(ToLog)]
pub enum ERC20Events {
/// @dev This event is emitted when the amount of tokens (value) is sent
@@ -307,7 +257,7 @@
#[solidity_interface(
name = UniqueRefungibleToken,
- is(ERC20, ERC20UniqueExtensions, ERC1633, ERC1633UniqueExtensions)
+ is(ERC20, ERC20UniqueExtensions, ERC1633)
)]
impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1379,68 +1379,4 @@
Some(res)
}
}
-
- /// Sets the NFT token as a parent for the RFT token
- ///
- /// Throws if `sender` is not the owner of the NFT token.
- /// Throws if `sender` is not the owner of all of the RFT token pieces.
- pub fn set_parent_nft(
- collection: &RefungibleHandle<T>,
- rft_token_id: TokenId,
- sender: T::CrossAccountId,
- nft_collection: CollectionId,
- nft_token: TokenId,
- ) -> DispatchResult {
- let handle = <CollectionHandle<T>>::try_get(nft_collection)?;
- if handle.mode != CollectionMode::NFT {
- return Err("Only NFT token could be parent to RFT".into());
- }
- let dispatch = T::CollectionDispatch::dispatch(handle);
- let dispatch = dispatch.as_dyn();
-
- let owner = dispatch.token_owner(nft_token).ok_or("owner not found")?;
- if owner != sender {
- return Err("Only owned token could be set as parent".into());
- }
-
- let nft_token_address =
- T::CrossTokenAddressMapping::token_to_address(nft_collection, nft_token);
-
- Self::set_parent_nft_unchecked(collection, rft_token_id, sender, nft_token_address)
- }
-
- /// Sets the NFT token as a parent for the RFT token
- ///
- /// `sender` should be the owner of the NFT token.
- /// Throws if `sender` is not the owner of all of the RFT token pieces.
- pub fn set_parent_nft_unchecked(
- collection: &RefungibleHandle<T>,
- rft_token_id: TokenId,
- sender: T::CrossAccountId,
- nft_token_address: T::CrossAccountId,
- ) -> DispatchResult {
- let owner_balance = <Balance<T>>::get((collection.id, rft_token_id, &sender));
- let total_supply = <TotalSupply<T>>::get((collection.id, rft_token_id));
- if total_supply != owner_balance {
- return Err("token has multiple owners".into());
- }
-
- let parent_nft_property_key = key::parent_nft();
-
- let parent_nft_property_value =
- property_value_from_bytes(&nft_token_address.as_eth().to_fixed_bytes())
- .expect("address should fit in value length limit");
-
- <Pallet<T>>::set_scoped_token_property(
- collection.id,
- rft_token_id,
- PropertyScope::Eth,
- Property {
- key: parent_nft_property_key,
- value: parent_nft_property_value,
- },
- )?;
-
- Ok(())
- }
}
pallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungibleToken.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
@@ -21,22 +21,6 @@
}
}
-/// @dev the ERC-165 identifier for this interface is 0x042f1106
-contract ERC1633UniqueExtensions is Dummy, ERC165 {
- /// @dev EVM selector for this function is: 0x042f1106,
- /// or in textual repr: setParentNFT(address,uint256)
- function setParentNFT(address collection, uint256 nftId)
- public
- returns (bool)
- {
- require(false, stub_error);
- collection;
- nftId;
- dummy = 0;
- return false;
- }
-}
-
/// @dev the ERC-165 identifier for this interface is 0x5755c3f2
contract ERC1633 is Dummy, ERC165 {
/// @dev EVM selector for this function is: 0x80a54001,
@@ -222,6 +206,5 @@
ERC165,
ERC20,
ERC20UniqueExtensions,
- ERC1633,
- ERC1633UniqueExtensions
+ ERC1633
{}
pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -53,7 +53,6 @@
fn set_token_properties(b: u32, ) -> Weight;
fn delete_token_properties(b: u32, ) -> Weight;
fn repartition_item() -> Weight;
- fn set_parent_nft_unchecked() -> Weight;
fn token_owner() -> Weight;
}
@@ -254,14 +253,6 @@
(22_356_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
- }
- // Storage: Refungible Balance (r:1 w:0)
- // Storage: Refungible TotalSupply (r:1 w:0)
- // Storage: Refungible TokenProperties (r:1 w:1)
- fn set_parent_nft_unchecked() -> Weight {
- (12_015_000 as Weight)
- .saturating_add(T::DbWeight::get().reads(3 as Weight))
- .saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Refungible Balance (r:2 w:0)
fn token_owner() -> Weight {
@@ -466,14 +457,6 @@
(22_356_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
- }
- // Storage: Refungible Balance (r:1 w:0)
- // Storage: Refungible TotalSupply (r:1 w:0)
- // Storage: Refungible TokenProperties (r:1 w:1)
- fn set_parent_nft_unchecked() -> Weight {
- (12_015_000 as Weight)
- .saturating_add(RocksDbWeight::get().reads(3 as Weight))
- .saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Refungible Balance (r:2 w:0)
fn token_owner() -> Weight {
pallets/unique/src/eth/mod.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//! Implementation of CollectionHelpers contract.1819use core::marker::PhantomData;20use ethereum as _;21use evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};22use frame_support::traits::Get;23use pallet_common::{24 CollectionById, CollectionHandle,25 dispatch::CollectionDispatch,26 erc::{27 CollectionHelpersEvents,28 static_property::{key, value as property_value},29 },30 Pallet as PalletCommon,31};32use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};33use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};34use pallet_evm_coder_substrate::dispatch_to_evm;35use up_data_structs::{36 CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,37 CollectionMode, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,38};3940use crate::{Config, SelfWeightOf, weights::WeightInfo};4142use sp_std::{vec, vec::Vec};43use alloc::format;4445/// See [`CollectionHelpersCall`]46pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);47impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {48 fn recorder(&self) -> &SubstrateRecorder<T> {49 &self.050 }5152 fn into_recorder(self) -> SubstrateRecorder<T> {53 self.054 }55}5657fn convert_data<T: Config>(58 caller: caller,59 name: string,60 description: string,61 token_prefix: string,62 base_uri: string,63) -> Result<(64 T::CrossAccountId,65 CollectionName,66 CollectionDescription,67 CollectionTokenPrefix,68 PropertyValue,69)> {70 let caller = T::CrossAccountId::from_eth(caller);71 let name = name72 .encode_utf16()73 .collect::<Vec<u16>>()74 .try_into()75 .map_err(|_| error_field_too_long(stringify!(name), CollectionName::bound()))?;76 let description = description77 .encode_utf16()78 .collect::<Vec<u16>>()79 .try_into()80 .map_err(|_| {81 error_field_too_long(stringify!(description), CollectionDescription::bound())82 })?;83 let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {84 error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())85 })?;86 let base_uri_value = base_uri87 .into_bytes()88 .try_into()89 .map_err(|_| error_field_too_long(stringify!(token_prefix), PropertyValue::bound()))?;90 Ok((caller, name, description, token_prefix, base_uri_value))91}9293fn make_data<T: Config>(94 name: CollectionName,95 mode: CollectionMode,96 description: CollectionDescription,97 token_prefix: CollectionTokenPrefix,98 base_uri_value: PropertyValue,99 add_properties: bool,100) -> Result<CreateCollectionData<T::AccountId>> {101 let mut properties = up_data_structs::CollectionPropertiesVec::default();102 let mut token_property_permissions =103 up_data_structs::CollectionPropertiesPermissionsVec::default();104105 token_property_permissions106 .try_push(up_data_structs::PropertyKeyPermission {107 key: key::url(),108 permission: up_data_structs::PropertyPermission {109 mutable: false,110 collection_admin: true,111 token_owner: false,112 },113 })114 .map_err(|e| Error::Revert(format!("{:?}", e)))?;115116 if add_properties {117 token_property_permissions118 .try_push(up_data_structs::PropertyKeyPermission {119 key: key::suffix(),120 permission: up_data_structs::PropertyPermission {121 mutable: false,122 collection_admin: true,123 token_owner: false,124 },125 })126 .map_err(|e| Error::Revert(format!("{:?}", e)))?;127128 properties129 .try_push(up_data_structs::Property {130 key: key::schema_name(),131 value: property_value::erc721(),132 })133 .map_err(|e| Error::Revert(format!("{:?}", e)))?;134135 if !base_uri_value.is_empty() {136 properties137 .try_push(up_data_structs::Property {138 key: key::base_uri(),139 value: base_uri_value,140 })141 .map_err(|e| Error::Revert(format!("{:?}", e)))?;142 }143 }144145 let data = CreateCollectionData {146 name,147 mode,148 description,149 token_prefix,150 token_property_permissions,151 properties,152 ..Default::default()153 };154 Ok(data)155}156157fn parent_nft_property_permissions() -> PropertyKeyPermission {158 PropertyKeyPermission {159 key: key::parent_nft(),160 permission: PropertyPermission {161 mutable: false,162 collection_admin: false,163 token_owner: true,164 },165 }166}167168fn create_refungible_collection_internal<169 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,170>(171 caller: caller,172 name: string,173 description: string,174 token_prefix: string,175 base_uri: string,176 add_properties: bool,177) -> Result<address> {178 let (caller, name, description, token_prefix, base_uri_value) =179 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;180 let data = make_data::<T>(181 name,182 CollectionMode::ReFungible,183 description,184 token_prefix,185 base_uri_value,186 add_properties,187 )?;188189 let collection_id = T::CollectionDispatch::create(caller.clone(), data)190 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;191192 let handle = <CollectionHandle<T>>::try_get(collection_id).map_err(dispatch_to_evm::<T>)?;193 <PalletCommon<T>>::set_scoped_token_property_permissions(194 &handle,195 &caller,196 PropertyScope::Eth,197 vec![parent_nft_property_permissions()],198 )199 .map_err(dispatch_to_evm::<T>)?;200201 let address = pallet_common::eth::collection_id_to_address(collection_id);202 Ok(address)203}204205/// @title Contract, which allows users to operate with collections206#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]207impl<T> EvmCollectionHelpers<T>208where209 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,210{211 /// Create an NFT collection212 /// @param name Name of the collection213 /// @param description Informative description of the collection214 /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications215 /// @return address Address of the newly created collection216 #[weight(<SelfWeightOf<T>>::create_collection())]217 fn create_nonfungible_collection(218 &mut self,219 caller: caller,220 name: string,221 description: string,222 token_prefix: string,223 ) -> Result<address> {224 let (caller, name, description, token_prefix, _base_uri_value) =225 convert_data::<T>(caller, name, description, token_prefix, "".into())?;226 let data = make_data::<T>(227 name,228 CollectionMode::NFT,229 description,230 token_prefix,231 Default::default(),232 false,233 )?;234 let collection_id = T::CollectionDispatch::create(caller, data)235 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;236237 let address = pallet_common::eth::collection_id_to_address(collection_id);238 Ok(address)239 }240241 #[weight(<SelfWeightOf<T>>::create_collection())]242 #[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]243 fn create_nonfungible_collection_with_properties(244 &mut self,245 caller: caller,246 name: string,247 description: string,248 token_prefix: string,249 base_uri: string,250 ) -> Result<address> {251 let (caller, name, description, token_prefix, base_uri_value) =252 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;253 let data = make_data::<T>(254 name,255 CollectionMode::NFT,256 description,257 token_prefix,258 base_uri_value,259 true,260 )?;261 let collection_id = T::CollectionDispatch::create(caller, data)262 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;263264 let address = pallet_common::eth::collection_id_to_address(collection_id);265 Ok(address)266 }267268 #[weight(<SelfWeightOf<T>>::create_collection())]269 fn create_refungible_collection(270 &mut self,271 caller: caller,272 name: string,273 description: string,274 token_prefix: string,275 ) -> Result<address> {276 create_refungible_collection_internal::<T>(277 caller,278 name,279 description,280 token_prefix,281 Default::default(),282 false,283 )284 }285286 #[weight(<SelfWeightOf<T>>::create_collection())]287 #[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]288 fn create_refungible_collection_with_properties(289 &mut self,290 caller: caller,291 name: string,292 description: string,293 token_prefix: string,294 base_uri: string,295 ) -> Result<address> {296 create_refungible_collection_internal::<T>(297 caller,298 name,299 description,300 token_prefix,301 base_uri,302 true,303 )304 }305306 /// Check if a collection exists307 /// @param collectionAddress Address of the collection in question308 /// @return bool Does the collection exist?309 fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {310 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {311 let collection_id = id;312 return Ok(<CollectionById<T>>::contains_key(collection_id));313 }314315 Ok(false)316 }317}318319/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]320pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);321impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>322 for CollectionHelpersOnMethodCall<T>323{324 fn is_reserved(contract: &sp_core::H160) -> bool {325 contract == &T::ContractAddress::get()326 }327328 fn is_used(contract: &sp_core::H160) -> bool {329 contract == &T::ContractAddress::get()330 }331332 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {333 if handle.code_address() != T::ContractAddress::get() {334 return None;335 }336337 let helpers =338 EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));339 pallet_evm_coder_substrate::call(handle, helpers)340 }341342 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {343 (contract == &T::ContractAddress::get())344 .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())345 }346}347348generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);349generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);350351fn error_field_too_long(feild: &str, bound: usize) -> Error {352 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))353}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//! Implementation of CollectionHelpers contract.1819use core::marker::PhantomData;20use ethereum as _;21use evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};22use frame_support::traits::Get;23use pallet_common::{24 CollectionById, CollectionHandle,25 dispatch::CollectionDispatch,26 erc::{27 CollectionHelpersEvents,28 static_property::{key, value as property_value},29 },30 Pallet as PalletCommon,31};32use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};33use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};34use pallet_evm_coder_substrate::dispatch_to_evm;35use up_data_structs::{36 CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,37 CollectionMode, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,38};3940use crate::{Config, SelfWeightOf, weights::WeightInfo};4142use sp_std::{vec, vec::Vec};43use alloc::format;4445/// See [`CollectionHelpersCall`]46pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);47impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {48 fn recorder(&self) -> &SubstrateRecorder<T> {49 &self.050 }5152 fn into_recorder(self) -> SubstrateRecorder<T> {53 self.054 }55}5657fn convert_data<T: Config>(58 caller: caller,59 name: string,60 description: string,61 token_prefix: string,62 base_uri: string,63) -> Result<(64 T::CrossAccountId,65 CollectionName,66 CollectionDescription,67 CollectionTokenPrefix,68 PropertyValue,69)> {70 let caller = T::CrossAccountId::from_eth(caller);71 let name = name72 .encode_utf16()73 .collect::<Vec<u16>>()74 .try_into()75 .map_err(|_| error_field_too_long(stringify!(name), CollectionName::bound()))?;76 let description = description77 .encode_utf16()78 .collect::<Vec<u16>>()79 .try_into()80 .map_err(|_| {81 error_field_too_long(stringify!(description), CollectionDescription::bound())82 })?;83 let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {84 error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())85 })?;86 let base_uri_value = base_uri87 .into_bytes()88 .try_into()89 .map_err(|_| error_field_too_long(stringify!(token_prefix), PropertyValue::bound()))?;90 Ok((caller, name, description, token_prefix, base_uri_value))91}9293fn make_data<T: Config>(94 name: CollectionName,95 mode: CollectionMode,96 description: CollectionDescription,97 token_prefix: CollectionTokenPrefix,98 base_uri_value: PropertyValue,99 add_properties: bool,100) -> Result<CreateCollectionData<T::AccountId>> {101 let mut properties = up_data_structs::CollectionPropertiesVec::default();102 let mut token_property_permissions =103 up_data_structs::CollectionPropertiesPermissionsVec::default();104105 token_property_permissions106 .try_push(up_data_structs::PropertyKeyPermission {107 key: key::url(),108 permission: up_data_structs::PropertyPermission {109 mutable: false,110 collection_admin: true,111 token_owner: false,112 },113 })114 .map_err(|e| Error::Revert(format!("{:?}", e)))?;115116 if add_properties {117 token_property_permissions118 .try_push(up_data_structs::PropertyKeyPermission {119 key: key::suffix(),120 permission: up_data_structs::PropertyPermission {121 mutable: false,122 collection_admin: true,123 token_owner: false,124 },125 })126 .map_err(|e| Error::Revert(format!("{:?}", e)))?;127128 properties129 .try_push(up_data_structs::Property {130 key: key::schema_name(),131 value: property_value::erc721(),132 })133 .map_err(|e| Error::Revert(format!("{:?}", e)))?;134135 if !base_uri_value.is_empty() {136 properties137 .try_push(up_data_structs::Property {138 key: key::base_uri(),139 value: base_uri_value,140 })141 .map_err(|e| Error::Revert(format!("{:?}", e)))?;142 }143 }144145 let data = CreateCollectionData {146 name,147 mode,148 description,149 token_prefix,150 token_property_permissions,151 properties,152 ..Default::default()153 };154 Ok(data)155}156157fn create_refungible_collection_internal<158 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,159>(160 caller: caller,161 name: string,162 description: string,163 token_prefix: string,164 base_uri: string,165 add_properties: bool,166) -> Result<address> {167 let (caller, name, description, token_prefix, base_uri_value) =168 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;169 let data = make_data::<T>(170 name,171 CollectionMode::ReFungible,172 description,173 token_prefix,174 base_uri_value,175 add_properties,176 )?;177178 let collection_id = T::CollectionDispatch::create(caller.clone(), data)179 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;180 let address = pallet_common::eth::collection_id_to_address(collection_id);181 Ok(address)182}183184/// @title Contract, which allows users to operate with collections185#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]186impl<T> EvmCollectionHelpers<T>187where188 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,189{190 /// Create an NFT collection191 /// @param name Name of the collection192 /// @param description Informative description of the collection193 /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications194 /// @return address Address of the newly created collection195 #[weight(<SelfWeightOf<T>>::create_collection())]196 fn create_nonfungible_collection(197 &mut self,198 caller: caller,199 name: string,200 description: string,201 token_prefix: string,202 ) -> Result<address> {203 let (caller, name, description, token_prefix, _base_uri_value) =204 convert_data::<T>(caller, name, description, token_prefix, "".into())?;205 let data = make_data::<T>(206 name,207 CollectionMode::NFT,208 description,209 token_prefix,210 Default::default(),211 false,212 )?;213 let collection_id = T::CollectionDispatch::create(caller, data)214 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;215216 let address = pallet_common::eth::collection_id_to_address(collection_id);217 Ok(address)218 }219220 #[weight(<SelfWeightOf<T>>::create_collection())]221 #[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]222 fn create_nonfungible_collection_with_properties(223 &mut self,224 caller: caller,225 name: string,226 description: string,227 token_prefix: string,228 base_uri: string,229 ) -> Result<address> {230 let (caller, name, description, token_prefix, base_uri_value) =231 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;232 let data = make_data::<T>(233 name,234 CollectionMode::NFT,235 description,236 token_prefix,237 base_uri_value,238 true,239 )?;240 let collection_id = T::CollectionDispatch::create(caller, data)241 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;242243 let address = pallet_common::eth::collection_id_to_address(collection_id);244 Ok(address)245 }246247 #[weight(<SelfWeightOf<T>>::create_collection())]248 fn create_refungible_collection(249 &mut self,250 caller: caller,251 name: string,252 description: string,253 token_prefix: string,254 ) -> Result<address> {255 create_refungible_collection_internal::<T>(256 caller,257 name,258 description,259 token_prefix,260 Default::default(),261 false,262 )263 }264265 #[weight(<SelfWeightOf<T>>::create_collection())]266 #[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]267 fn create_refungible_collection_with_properties(268 &mut self,269 caller: caller,270 name: string,271 description: string,272 token_prefix: string,273 base_uri: string,274 ) -> Result<address> {275 create_refungible_collection_internal::<T>(276 caller,277 name,278 description,279 token_prefix,280 base_uri,281 true,282 )283 }284285 /// Check if a collection exists286 /// @param collectionAddress Address of the collection in question287 /// @return bool Does the collection exist?288 fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {289 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {290 let collection_id = id;291 return Ok(<CollectionById<T>>::contains_key(collection_id));292 }293294 Ok(false)295 }296}297298/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]299pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);300impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>301 for CollectionHelpersOnMethodCall<T>302{303 fn is_reserved(contract: &sp_core::H160) -> bool {304 contract == &T::ContractAddress::get()305 }306307 fn is_used(contract: &sp_core::H160) -> bool {308 contract == &T::ContractAddress::get()309 }310311 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {312 if handle.code_address() != T::ContractAddress::get() {313 return None;314 }315316 let helpers =317 EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));318 pallet_evm_coder_substrate::call(handle, helpers)319 }320321 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {322 (contract == &T::ContractAddress::get())323 .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())324 }325}326327generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);328generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);329330fn error_field_too_long(feild: &str, bound: usize) -> Error {331 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))332}primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -1050,7 +1050,6 @@
pub enum PropertyScope {
None,
Rmrk,
- Eth,
}
impl PropertyScope {
@@ -1059,7 +1058,6 @@
let scope_str: &[u8] = match self {
Self::None => return Ok(key),
Self::Rmrk => b"rmrk",
- Self::Eth => b"eth",
};
[scope_str, b":", key.as_slice()]
tests/src/eth/api/UniqueRefungibleToken.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungibleToken.sol
+++ b/tests/src/eth/api/UniqueRefungibleToken.sol
@@ -12,15 +12,6 @@
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
-/// @dev the ERC-165 identifier for this interface is 0x042f1106
-interface ERC1633UniqueExtensions is Dummy, ERC165 {
- /// @dev EVM selector for this function is: 0x042f1106,
- /// or in textual repr: setParentNFT(address,uint256)
- function setParentNFT(address collection, uint256 nftId)
- external
- returns (bool);
-}
-
/// @dev the ERC-165 identifier for this interface is 0x5755c3f2
interface ERC1633 is Dummy, ERC165 {
/// @dev EVM selector for this function is: 0x80a54001,
@@ -140,6 +131,5 @@
ERC165,
ERC20,
ERC20UniqueExtensions,
- ERC1633,
- ERC1633UniqueExtensions
+ ERC1633
{}
tests/src/eth/base.test.tsdiffbeforeafterboth--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -94,7 +94,7 @@
});
itWeb3('ERC721 support', async ({web3}) => {
- expect(await contract(web3).methods.supportsInterface('0x58800161').call()).to.be.true;
+ expect(await contract(web3).methods.supportsInterface('0x780e9d63').call()).to.be.true;
});
itWeb3('ERC721Metadata support', async ({web3}) => {
tests/src/eth/fractionalizer/Fractionalizer.soldiffbeforeafterboth--- a/tests/src/eth/fractionalizer/Fractionalizer.sol
+++ b/tests/src/eth/fractionalizer/Fractionalizer.sol
@@ -16,8 +16,8 @@
}
address rftCollection;
mapping(address => bool) nftCollectionAllowList;
- mapping(address => mapping(uint256 => uint256)) nft2rftMapping;
- mapping(address => Token) rft2nftMapping;
+ mapping(address => mapping(uint256 => uint256)) public nft2rftMapping;
+ mapping(address => Token) public rft2nftMapping;
bytes32 refungibleCollectionType = keccak256(bytes("ReFungible"));
receive() external payable onlyOwner {}
@@ -137,7 +137,6 @@
rft2nftMapping[rftTokenAddress] = Token(_collection, _token);
rftTokenContract = UniqueRefungibleToken(rftTokenAddress);
- rftTokenContract.setParentNFT(_collection, _token);
} else {
rftTokenId = nft2rftMapping[_collection][_token];
rftTokenAddress = rftCollectionContract.tokenContractAddress(rftTokenId);
tests/src/eth/fractionalizer/fractionalizer.test.tsdiffbeforeafterboth--- a/tests/src/eth/fractionalizer/fractionalizer.test.ts
+++ b/tests/src/eth/fractionalizer/fractionalizer.test.ts
@@ -223,6 +223,28 @@
},
});
});
+
+ itWeb3('Test fractionalizer NFT <-> RFT mapping ', async ({api, web3, privateKeyWrapper}) => {
+ const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+ const {fractionalizer, rftCollectionAddress} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
+ const {rftTokenAddress, nftCollectionAddress, nftTokenId} = await createRFTToken(api, web3, owner, fractionalizer, 100n);
+
+ const {collectionId, tokenId} = tokenIdFromAddress(rftTokenAddress);
+ const refungibleAddress = collectionIdToAddress(collectionId);
+ expect(rftCollectionAddress).to.be.equal(refungibleAddress);
+ const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);
+ await refungibleTokenContract.methods.approve(fractionalizer.options.address, 100).send();
+
+ const rft2nft = await fractionalizer.methods.rft2nftMapping(rftTokenAddress).call();
+ expect(rft2nft).to.be.like({
+ _collection: nftCollectionAddress,
+ _tokenId: nftTokenId,
+ });
+
+ const nft2rft = await fractionalizer.methods.nft2rftMapping(nftCollectionAddress, nftTokenId).call();
+ expect(nft2rft).to.be.eq(tokenId.toString());
+ });
});
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -655,31 +655,6 @@
await requirePallets(this, [Pallets.ReFungible]);
});
- itWeb3('Parent NFT token address and id', async ({api, web3, privateKeyWrapper}) => {
- const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
- const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);
- const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);
- const nftTokenId = await nftContract.methods.nextTokenId().call();
- await nftContract.methods.mint(owner, nftTokenId).send();
- const nftCollectionId = collectionIdFromAddress(nftCollectionAddress);
-
- const {collectionIdAddress, collectionId} = await createRefungibleCollection(api, web3, owner);
- const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);
- const refungibleTokenId = await refungibleContract.methods.nextTokenId().call();
- await refungibleContract.methods.mint(owner, refungibleTokenId).send();
-
- const rftTokenAddress = tokenIdToAddress(collectionId, refungibleTokenId);
- const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);
- await refungibleTokenContract.methods.setParentNFT(nftCollectionAddress, nftTokenId).send();
-
- const tokenAddress = await refungibleTokenContract.methods.parentToken().call();
- const tokenId = await refungibleTokenContract.methods.parentTokenId().call();
- const nftTokenAddress = tokenIdToAddress(nftCollectionId, nftTokenId);
- expect(tokenAddress).to.be.equal(nftTokenAddress);
- expect(tokenId).to.be.equal(nftTokenId);
- });
-
itWeb3('Default parent token address and id', async ({api, web3, privateKeyWrapper}) => {
const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
@@ -693,7 +668,7 @@
const tokenAddress = await refungibleTokenContract.methods.parentToken().call();
const tokenId = await refungibleTokenContract.methods.parentTokenId().call();
- expect(tokenAddress).to.be.equal(rftTokenAddress);
+ expect(tokenAddress).to.be.equal(collectionIdAddress);
expect(tokenId).to.be.equal(refungibleTokenId);
});
});
tests/src/eth/reFungibleTokenAbi.jsondiffbeforeafterboth--- a/tests/src/eth/reFungibleTokenAbi.json
+++ b/tests/src/eth/reFungibleTokenAbi.json
@@ -127,16 +127,6 @@
},
{
"inputs": [
- { "internalType": "address", "name": "collection", "type": "address" },
- { "internalType": "uint256", "name": "nftId", "type": "uint256" }
- ],
- "name": "setParentNFT",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
- "stateMutability": "nonpayable",
- "type": "function"
- },
- {
- "inputs": [
{ "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
],
"name": "supportsInterface",