difftreelog
test tests for contract fees
in: master
3 files changed
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -114,7 +114,7 @@
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
-use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap, collections::btree_set::BTreeSet};
+use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
use core::ops::Deref;
use codec::{Encode, Decode, MaxEncodedLen};
use scale_info::TypeInfo;
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,25 dispatch::CollectionDispatch,26 erc::{27 CollectionHelpersEvents,28 static_property::{key, value as property_value},29 },30};31use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};32use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};33use up_data_structs::{34 CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,35 CollectionMode, PropertyValue,36};3738use crate::{Config, SelfWeightOf, weights::WeightInfo};3940use sp_std::vec::Vec;41use alloc::format;4243/// See [`CollectionHelpersCall`]44pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);45impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {46 fn recorder(&self) -> &SubstrateRecorder<T> {47 &self.048 }4950 fn into_recorder(self) -> SubstrateRecorder<T> {51 self.052 }53}5455fn convert_data<T: Config>(56 caller: caller,57 name: string,58 description: string,59 token_prefix: string,60 base_uri: string,61) -> Result<(62 T::CrossAccountId,63 CollectionName,64 CollectionDescription,65 CollectionTokenPrefix,66 PropertyValue,67)> {68 let caller = T::CrossAccountId::from_eth(caller);69 let name = name70 .encode_utf16()71 .collect::<Vec<u16>>()72 .try_into()73 .map_err(|_| error_field_too_long(stringify!(name), CollectionName::bound()))?;74 let description = description75 .encode_utf16()76 .collect::<Vec<u16>>()77 .try_into()78 .map_err(|_| {79 error_field_too_long(stringify!(description), CollectionDescription::bound())80 })?;81 let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {82 error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())83 })?;84 let base_uri_value = base_uri85 .into_bytes()86 .try_into()87 .map_err(|_| error_field_too_long(stringify!(token_prefix), PropertyValue::bound()))?;88 Ok((caller, name, description, token_prefix, base_uri_value))89}9091fn make_data<T: Config>(92 name: CollectionName,93 mode: CollectionMode,94 description: CollectionDescription,95 token_prefix: CollectionTokenPrefix,96 base_uri_value: PropertyValue,97 add_properties: bool,98) -> Result<CreateCollectionData<T::AccountId>> {99 let mut properties = up_data_structs::CollectionPropertiesVec::default();100 let mut token_property_permissions =101 up_data_structs::CollectionPropertiesPermissionsVec::default();102103 token_property_permissions104 .try_push(up_data_structs::PropertyKeyPermission {105 key: key::url(),106 permission: up_data_structs::PropertyPermission {107 mutable: false,108 collection_admin: true,109 token_owner: false,110 },111 })112 .map_err(|e| Error::Revert(format!("{:?}", e)))?;113114 if add_properties {115 token_property_permissions116 .try_push(up_data_structs::PropertyKeyPermission {117 key: key::suffix(),118 permission: up_data_structs::PropertyPermission {119 mutable: false,120 collection_admin: true,121 token_owner: false,122 },123 })124 .map_err(|e| Error::Revert(format!("{:?}", e)))?;125126 properties127 .try_push(up_data_structs::Property {128 key: key::schema_name(),129 value: property_value::erc721(),130 })131 .map_err(|e| Error::Revert(format!("{:?}", e)))?;132133 if !base_uri_value.is_empty() {134 properties135 .try_push(up_data_structs::Property {136 key: key::base_uri(),137 value: base_uri_value,138 })139 .map_err(|e| Error::Revert(format!("{:?}", e)))?;140 }141 }142143 let data = CreateCollectionData {144 name,145 mode,146 description,147 token_prefix,148 token_property_permissions,149 properties,150 ..Default::default()151 };152 Ok(data)153}154155fn create_refungible_collection_internal<156 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,157>(158 caller: caller,159 name: string,160 description: string,161 token_prefix: string,162 base_uri: string,163 add_properties: bool,164) -> Result<address> {165 let (caller, name, description, token_prefix, base_uri_value) =166 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;167 let data = make_data::<T>(168 name,169 CollectionMode::ReFungible,170 description,171 token_prefix,172 base_uri_value,173 add_properties,174 )?;175176 let collection_id = T::CollectionDispatch::create(caller.clone(), data)177 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;178 let address = pallet_common::eth::collection_id_to_address(collection_id);179 Ok(address)180}181182/// @title Contract, which allows users to operate with collections183#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]184impl<T> EvmCollectionHelpers<T>185where186 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,187{188 /// Create an NFT collection189 /// @param name Name of the collection190 /// @param description Informative description of the collection191 /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications192 /// @return address Address of the newly created collection193 #[weight(<SelfWeightOf<T>>::create_collection())]194 fn create_nonfungible_collection(195 &mut self,196 caller: caller,197 name: string,198 description: string,199 token_prefix: string,200 ) -> Result<address> {201 let (caller, name, description, token_prefix, _base_uri_value) =202 convert_data::<T>(caller, name, description, token_prefix, "".into())?;203 let data = make_data::<T>(204 name,205 CollectionMode::NFT,206 description,207 token_prefix,208 Default::default(),209 false,210 )?;211 let collection_id = T::CollectionDispatch::create(caller, data)212 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;213214 let address = pallet_common::eth::collection_id_to_address(collection_id);215 Ok(address)216 }217218 #[weight(<SelfWeightOf<T>>::create_collection())]219 #[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]220 fn create_nonfungible_collection_with_properties(221 &mut self,222 caller: caller,223 name: string,224 description: string,225 token_prefix: string,226 base_uri: string,227 ) -> Result<address> {228 let (caller, name, description, token_prefix, base_uri_value) =229 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;230 let data = make_data::<T>(231 name,232 CollectionMode::NFT,233 description,234 token_prefix,235 base_uri_value,236 true,237 )?;238 let collection_id = T::CollectionDispatch::create(caller, data)239 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;240241 let address = pallet_common::eth::collection_id_to_address(collection_id);242 Ok(address)243 }244245 #[weight(<SelfWeightOf<T>>::create_collection())]246 #[solidity(rename_selector = "createRFTCollection")]247 fn create_refungible_collection(248 &mut self,249 caller: caller,250 name: string,251 description: string,252 token_prefix: string,253 ) -> Result<address> {254 create_refungible_collection_internal::<T>(255 caller,256 name,257 description,258 token_prefix,259 Default::default(),260 false,261 )262 }263264 #[weight(<SelfWeightOf<T>>::create_collection())]265 #[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]266 fn create_refungible_collection_with_properties(267 &mut self,268 caller: caller,269 name: string,270 description: string,271 token_prefix: string,272 base_uri: string,273 ) -> Result<address> {274 create_refungible_collection_internal::<T>(275 caller,276 name,277 description,278 token_prefix,279 base_uri,280 true,281 )282 }283284 /// Check if a collection exists285 /// @param collectionAddress Address of the collection in question286 /// @return bool Does the collection exist?287 fn is_collection_exist(&self, _caller: caller, collection_address: address) -> Result<bool> {288 if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {289 let collection_id = id;290 return Ok(<CollectionById<T>>::contains_key(collection_id));291 }292293 Ok(false)294 }295}296297/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]298pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);299impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>300 for CollectionHelpersOnMethodCall<T>301{302 fn is_reserved(contract: &sp_core::H160) -> bool {303 contract == &T::ContractAddress::get()304 }305306 fn is_used(contract: &sp_core::H160) -> bool {307 contract == &T::ContractAddress::get()308 }309310 fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {311 if handle.code_address() != T::ContractAddress::get() {312 return None;313 }314315 let helpers =316 EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));317 pallet_evm_coder_substrate::call(handle, helpers)318 }319320 fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {321 (contract == &T::ContractAddress::get())322 .then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())323 }324}325326generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);327generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);328329fn error_field_too_long(feild: &str, bound: usize) -> Error {330 Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))331}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,25 dispatch::CollectionDispatch,26 erc::{27 CollectionHelpersEvents,28 static_property::{key, value as property_value},29 },30};31use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};32use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};33use up_data_structs::{34 CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,35 CollectionMode, PropertyValue,36};3738use crate::{Config, SelfWeightOf, weights::WeightInfo};3940use sp_std::vec::Vec;41use alloc::format;4243/// See [`CollectionHelpersCall`]44pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);45impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {46 fn recorder(&self) -> &SubstrateRecorder<T> {47 &self.048 }4950 fn into_recorder(self) -> SubstrateRecorder<T> {51 self.052 }53}5455fn convert_data<T: Config>(56 caller: caller,57 name: string,58 description: string,59 token_prefix: string,60 base_uri: string,61) -> Result<(62 T::CrossAccountId,63 CollectionName,64 CollectionDescription,65 CollectionTokenPrefix,66 PropertyValue,67)> {68 let caller = T::CrossAccountId::from_eth(caller);69 let name = name70 .encode_utf16()71 .collect::<Vec<u16>>()72 .try_into()73 .map_err(|_| error_field_too_long(stringify!(name), CollectionName::bound()))?;74 let description = description75 .encode_utf16()76 .collect::<Vec<u16>>()77 .try_into()78 .map_err(|_| {79 error_field_too_long(stringify!(description), CollectionDescription::bound())80 })?;81 let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {82 error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())83 })?;84 let base_uri_value = base_uri85 .into_bytes()86 .try_into()87 .map_err(|_| error_field_too_long(stringify!(token_prefix), PropertyValue::bound()))?;88 Ok((caller, name, description, token_prefix, base_uri_value))89}9091fn make_data<T: Config>(92 name: CollectionName,93 mode: CollectionMode,94 description: CollectionDescription,95 token_prefix: CollectionTokenPrefix,96 base_uri_value: PropertyValue,97 add_properties: bool,98) -> Result<CreateCollectionData<T::AccountId>> {99 let mut properties = up_data_structs::CollectionPropertiesVec::default();100 let mut token_property_permissions =101 up_data_structs::CollectionPropertiesPermissionsVec::default();102103 token_property_permissions104 .try_push(up_data_structs::PropertyKeyPermission {105 key: key::url(),106 permission: up_data_structs::PropertyPermission {107 mutable: false,108 collection_admin: true,109 token_owner: false,110 },111 })112 .map_err(|e| Error::Revert(format!("{:?}", e)))?;113114 if add_properties {115 token_property_permissions116 .try_push(up_data_structs::PropertyKeyPermission {117 key: key::suffix(),118 permission: up_data_structs::PropertyPermission {119 mutable: false,120 collection_admin: true,121 token_owner: false,122 },123 })124 .map_err(|e| Error::Revert(format!("{:?}", e)))?;125126 properties127 .try_push(up_data_structs::Property {128 key: key::schema_name(),129 value: property_value::erc721(),130 })131 .map_err(|e| Error::Revert(format!("{:?}", e)))?;132133 if !base_uri_value.is_empty() {134 properties135 .try_push(up_data_structs::Property {136 key: key::base_uri(),137 value: base_uri_value,138 })139 .map_err(|e| Error::Revert(format!("{:?}", e)))?;140 }141 }142143 let data = CreateCollectionData {144 name,145 mode,146 description,147 token_prefix,148 token_property_permissions,149 properties,150 ..Default::default()151 };152 Ok(data)153}154155fn create_refungible_collection_internal<156 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,157>(158 caller: caller,159 name: string,160 description: string,161 token_prefix: string,162 base_uri: string,163 add_properties: bool,164) -> Result<address> {165 let (caller, name, description, token_prefix, base_uri_value) =166 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;167 let data = make_data::<T>(168 name,169 CollectionMode::ReFungible,170 description,171 token_prefix,172 base_uri_value,173 add_properties,174 )?;175176 let collection_id = T::CollectionDispatch::create(caller.clone(), data)177 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;178 let address = pallet_common::eth::collection_id_to_address(collection_id);179 Ok(address)180}181182/// @title Contract, which allows users to operate with collections183#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents))]184impl<T> EvmCollectionHelpers<T>185where186 T: Config + pallet_nonfungible::Config + pallet_refungible::Config,187{188 /// Create an NFT collection189 /// @param name Name of the collection190 /// @param description Informative description of the collection191 /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications192 /// @return address Address of the newly created collection193 #[weight(<SelfWeightOf<T>>::create_collection())]194 fn create_nonfungible_collection(195 &mut self,196 caller: caller,197 value: value,198 name: string,199 description: string,200 token_prefix: string,201 ) -> Result<address> {202 let (caller, name, description, token_prefix, _base_uri_value) =203 convert_data::<T>(caller, name, description, token_prefix, "".into())?;204 let data = make_data::<T>(205 name,206 CollectionMode::NFT,207 description,208 token_prefix,209 Default::default(),210 false,211 )?;212 let collection_id = T::CollectionDispatch::create(caller, data)213 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;214215 let address = pallet_common::eth::collection_id_to_address(collection_id);216 Ok(address)217 }218219 #[weight(<SelfWeightOf<T>>::create_collection())]220 #[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]221 fn create_nonfungible_collection_with_properties(222 &mut self,223 caller: caller,224 name: string,225 description: string,226 token_prefix: string,227 base_uri: string,228 ) -> Result<address> {229 let (caller, name, description, token_prefix, base_uri_value) =230 convert_data::<T>(caller, name, description, token_prefix, base_uri)?;231 let data = make_data::<T>(232 name,233 CollectionMode::NFT,234 description,235 token_prefix,236 base_uri_value,237 true,238 )?;239 let collection_id = T::CollectionDispatch::create(caller, data)240 .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;241242 let address = pallet_common::eth::collection_id_to_address(collection_id);243 Ok(address)244 }245246 #[weight(<SelfWeightOf<T>>::create_collection())]247 #[solidity(rename_selector = "createRFTCollection")]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}tests/src/eth/payable.test.tsdiffbeforeafterboth--- a/tests/src/eth/payable.test.ts
+++ b/tests/src/eth/payable.test.ts
@@ -16,7 +16,7 @@
import {IKeyringPair} from '@polkadot/types/types';
-import {itEth, expect, usingEthPlaygrounds} from './util/playgrounds';
+import {itEth, expect, usingEthPlaygrounds, EthUniqueHelper} from './util/playgrounds';
describe('EVM payable contracts', () => {
let donor: IKeyringPair;
@@ -104,3 +104,147 @@
}
});
});
+
+describe('EVM transaction fees', () => {
+ let donor: IKeyringPair;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (_, privateKey) => {
+ donor = privateKey('//Alice');
+ });
+ });
+
+ itEth('Fee is withdrawn from the user', async({helper}) => {
+ const deployer = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const contract = await helper.eth.deployFlipper(deployer);
+
+ const initialCallerBalance = await helper.balance.getEthereum(caller);
+ await contract.methods.flip().send({from: caller});
+ const finalCallerBalance = await helper.balance.getEthereum(caller);
+ expect(finalCallerBalance < initialCallerBalance).to.be.true;
+ });
+
+ itEth('Fee for nested calls is withdrawn from the user', async({helper}) => {
+ const deployer = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const contract = await deployProxyContract(helper, deployer);
+
+ const initialCallerBalance = await helper.balance.getEthereum(caller);
+ const initialContractBalance = await helper.balance.getEthereum(contract.options.address);
+ await contract.methods.flip().send({from: caller});
+ const finalCallerBalance = await helper.balance.getEthereum(caller);
+ const finalContractBalance = await helper.balance.getEthereum(contract.options.address);
+ expect(finalCallerBalance < initialCallerBalance).to.be.true;
+ expect(finalContractBalance == initialContractBalance).to.be.true;
+ });
+
+ itEth('Fee for nested calls to native methods is withdrawn from the user', async({helper}) => {
+ const CONTRACT_BALANCE = 3n * helper.balance.getOneTokenNominal();
+
+ const deployer = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const contract = await deployProxyContract(helper, deployer);
+
+ const web3 = helper.getWeb3();
+ await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: CONTRACT_BALANCE.toString(), gas: helper.eth.DEFAULT_GAS});
+
+ const collectionAddress = (await contract.methods.createNonfungibleCollection().send({from: caller})).events.CollectionCreated.returnValues.collection;
+ const initialCallerBalance = await helper.balance.getEthereum(caller);
+ const initialContractBalance = await helper.balance.getEthereum(contract.options.address);
+ await contract.methods.mintNftToken(collectionAddress).send({from: caller});
+ const finalCallerBalance = await helper.balance.getEthereum(caller);
+ const finalContractBalance = await helper.balance.getEthereum(contract.options.address);
+ expect(finalCallerBalance < initialCallerBalance).to.be.true;
+ expect(finalContractBalance == initialContractBalance).to.be.true;
+ });
+
+ itEth('Fee for nested calls to create*Collection methods is withdrawn from the user and from the contract', async({helper}) => {
+ const CONTRACT_BALANCE = 3n * helper.balance.getOneTokenNominal();
+
+ const deployer = await helper.eth.createAccountWithBalance(donor);
+ const caller = await helper.eth.createAccountWithBalance(donor);
+ const contract = await deployProxyContract(helper, deployer);
+
+ const web3 = helper.getWeb3();
+ await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: CONTRACT_BALANCE.toString(), gas: helper.eth.DEFAULT_GAS});
+
+ const initialCallerBalance = await helper.balance.getEthereum(caller);
+ const initialContractBalance = await helper.balance.getEthereum(contract.options.address);
+ await contract.methods.createNonfungibleCollection().send({from: caller});
+ const finalCallerBalance = await helper.balance.getEthereum(caller);
+ const finalContractBalance = await helper.balance.getEthereum(contract.options.address);
+ expect(finalCallerBalance < initialCallerBalance).to.be.true;
+ expect(finalContractBalance < initialContractBalance).to.be.true;
+ });
+
+ async function deployProxyContract(helper: EthUniqueHelper, deployer: string) {
+ return await helper.ethContract.deployByCode(
+ deployer,
+ 'ProxyContract',
+ `
+ // SPDX-License-Identifier: UNLICENSED
+ pragma solidity ^0.8.6;
+
+ import {CollectionHelpers} from "../api/CollectionHelpers.sol";
+ import {UniqueNFT} from "../api/UniqueNFT.sol";
+
+ contract ProxyContract {
+ bool value = false;
+ address flipper;
+
+ event CollectionCreated(address collection);
+ event TokenMinted(uint256 tokenId);
+
+ receive() external payable {}
+
+ constructor() {
+ flipper = address(new Flipper());
+ }
+
+ function flip() public {
+ value = !value;
+ Flipper(flipper).flip();
+ }
+
+ function createNonfungibleCollection() public {
+ address collectionHelpers = 0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F;
+ address nftCollection = CollectionHelpers(collectionHelpers).createNonfungibleCollection("A", "B", "C");
+ emit CollectionCreated(nftCollection);
+ }
+
+ function mintNftToken(address collectionAddress) public {
+ UniqueNFT collection = UniqueNFT(collectionAddress);
+ uint256 tokenId = collection.nextTokenId();
+ collection.mint(msg.sender, tokenId);
+ emit TokenMinted(tokenId);
+ }
+
+ function getValue() public view returns (bool) {
+ return Flipper(flipper).getValue();
+ }
+ }
+
+ contract Flipper {
+ bool value = false;
+ function flip() public {
+ value = !value;
+ }
+ function getValue() public view returns (bool) {
+ return value;
+ }
+ }
+ `,
+ [
+ {
+ solPath: 'api/CollectionHelpers.sol',
+ fsPath: `${__dirname}/api/CollectionHelpers.sol`,
+ },
+ {
+ solPath: 'api/UniqueNFT.sol',
+ fsPath: `${__dirname}/api/UniqueNFT.sol`,
+ },
+ ],
+ );
+ }
+});