difftreelog
CORE-302 Refactor collection for eth
in: master
20 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5467,9 +5467,9 @@
[[package]]
name = "once_cell"
-version = "1.11.0"
+version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7b10983b38c53aebdf33f542c6275b0f58a238129d00c4ae0e6fb59738d783ca"
+checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225"
[[package]]
name = "opal-runtime"
@@ -6830,7 +6830,6 @@
"parity-scale-codec 3.1.2",
"scale-info",
"serde",
- "serde-json-core",
"sp-core",
"sp-io",
"sp-runtime",
@@ -10735,16 +10734,6 @@
]
[[package]]
-name = "serde-json-core"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8014aeea272bca0f0779778d43253f2f3375b414185b30e6ecc4d3e4a9994781"
-dependencies = [
- "ryu",
- "serde",
-]
-
-[[package]]
name = "serde_derive"
version = "1.0.137"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -12025,9 +12014,9 @@
[[package]]
name = "target-lexicon"
-version = "0.12.3"
+version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d7fa7e55043acb85fca6b3c01485a2eeb6b69c5d21002e273c79e465f43b7ac1"
+checksum = "c02424087780c9b71cc96799eaeddff35af2bc513278cda5c99fc1f5d026d3c1"
[[package]]
name = "tempfile"
Makefilediffbeforeafterboth--- a/Makefile
+++ b/Makefile
@@ -15,16 +15,13 @@
CONTRACT_HELPERS_STUBS=./pallets/evm-contract-helpers/src/stubs/
CONTRACT_HELPERS_ABI=./tests/src/eth/util/contractHelpersAbi.json
-COLLECTION_STUBS=./pallets/unique/src/eth/stubs/
-COLLECTION_ABI=./tests/src/eth/collectionAbi.json
-
COLLECTION_HELPER_STUBS=$(COLLECTION_STUBS)
COLLECTION_HELPER_ABI=./tests/src/eth/collectionHelperAbi.json
TESTS_API=./tests/src/eth/api/
.PHONY: regenerate_solidity
-regenerate_solidity: UniqueFungible.sol UniqueNFT.sol ContractHelpers.sol Collection.sol CollectionHelper.sol
+regenerate_solidity: UniqueFungible.sol UniqueNFT.sol ContractHelpers.sol CollectionHelper.sol
UniqueFungible.sol:
PACKAGE=pallet-fungible NAME=erc::gen_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
@@ -38,10 +35,6 @@
PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_impl OUTPUT=$(CONTRACT_HELPERS_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
-Collection.sol:
- PACKAGE=pallet-unique NAME=eth::evm_collection::collection_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
- PACKAGE=pallet-unique NAME=eth::evm_collection::collection_impl OUTPUT=$(COLLECTION_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
-
CollectionHelper.sol:
PACKAGE=pallet-unique NAME=eth::evm_collection::collection_helper_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
PACKAGE=pallet-unique NAME=eth::evm_collection::collection_helper_impl OUTPUT=$(COLLECTION_HELPER_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
@@ -58,15 +51,11 @@
INPUT=$(CONTRACT_HELPERS_STUBS)/$< OUTPUT=$(CONTRACT_HELPERS_STUBS)/ContractHelpers.raw ./.maintain/scripts/compile_stub.sh
INPUT=$(CONTRACT_HELPERS_STUBS)/$< OUTPUT=$(CONTRACT_HELPERS_ABI) ./.maintain/scripts/generate_abi.sh
-Collection: Collection.sol
- INPUT=$(COLLECTION_STUBS)/$< OUTPUT=$(COLLECTION_STUBS)/Collection.raw ./.maintain/scripts/compile_stub.sh
- INPUT=$(COLLECTION_STUBS)/$< OUTPUT=$(COLLECTION_ABI) ./.maintain/scripts/generate_abi.sh
-
CollectionHelper: CollectionHelper.sol
INPUT=$(COLLECTION_HELPER_STUBS)/$< OUTPUT=$(COLLECTION_HELPER_STUBS)/CollectionHelper.raw ./.maintain/scripts/compile_stub.sh
INPUT=$(COLLECTION_HELPER_STUBS)/$< OUTPUT=$(COLLECTION_HELPER_ABI) ./.maintain/scripts/generate_abi.sh
-evm_stubs: UniqueFungible UniqueNFT ContractHelpers Collection CollectionHelper
+evm_stubs: UniqueFungible UniqueNFT ContractHelpers CollectionHelper
.PHONY: _bench
_bench:
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -14,9 +14,9 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-use evm_coder::{solidity_interface, types::*, execution::Result};
+use evm_coder::{solidity_interface, types::*, execution::{Result, Error}};
pub use pallet_evm::{PrecompileOutput, PrecompileResult, account::CrossAccountId};
-use pallet_evm_coder_substrate::dispatch_to_evm;
+use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder};
use sp_core::{H160, U256};
use sp_std::vec::Vec;
use up_data_structs::Property;
@@ -31,7 +31,7 @@
fn call(self, source: &H160, input: &[u8], value: U256) -> Option<PrecompileResult>;
}
-#[solidity_interface(name = "CollectionProperties")]
+#[solidity_interface(name = "Collection")]
impl<T: Config> CollectionHandle<T> {
fn set_collection_property(&mut self, caller: caller, key: string, value: bytes) -> Result<()> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -64,4 +64,70 @@
Ok(prop.to_vec())
}
+
+ fn eth_set_sponsor(
+ &mut self,
+ caller: caller,
+ sponsor: address,
+ ) -> Result<void> {
+ check_is_owner(caller, self)?;
+
+ let sponsor = T::CrossAccountId::from_eth(sponsor);
+ self.set_sponsor(sponsor.as_sub().clone());
+ save(self);
+ Ok(())
+ }
+
+ fn eth_confirm_sponsorship(&mut self, caller: caller) -> Result<void> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ if !self.confirm_sponsorship(caller.as_sub()) {
+ return Err(Error::Revert("Caller is not set as sponsor".into()));
+ }
+ save(self);
+ Ok(())
+ }
+
+ fn set_limits(
+ &self,
+ caller: caller,
+ limits_json: string,
+ ) -> Result<void> {
+ // let mut collection = collection_from_address::<T>(self.contract_address(caller).unwrap(), self.1.gas_left())?;
+ // check_is_owner(caller, &collection)?;
+
+ // let limits = serde_json_core::from_str(limits_json.as_ref())
+ // .map_err(|e| Error::Revert(format!("Parse JSON error: {}", e)))?;
+ // collection.limits = limits.0;
+ // collection.save().map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
+ fn contract_address(&self, _caller: caller) -> Result<address> {
+ Ok(crate::eth::collection_id_to_address(self.id))
+ }
+}
+
+fn collection_from_address<T: Config>(
+ collection_address: address,
+ gas_limit: u64
+) -> Result<CollectionHandle<T>> {
+ let collection_id = crate::eth::map_eth_to_id(&collection_address)
+ .ok_or(Error::Revert("Contract is not an unique collection".into()))?;
+ let recorder = <SubstrateRecorder<T>>::new(gas_limit);
+ let collection =
+ CollectionHandle::new_with_recorder(collection_id, recorder)
+ .ok_or(Error::Revert("Create collection handle error".into()))?;
+ Ok(collection)
+}
+
+fn check_is_owner<T: Config>(caller: caller, collection: &CollectionHandle<T>) -> Result<()> {
+ let caller = T::CrossAccountId::from_eth(caller);
+ collection
+ .check_is_owner(&caller)
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ Ok(())
}
+
+fn save<T: Config>(collection: &CollectionHandle<T>) {
+ <crate::CollectionById<T>>::insert(collection.id, collection.collection.clone());
+}
\ No newline at end of file
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -20,7 +20,7 @@
use core::ops::{Deref, DerefMut};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
-use sp_std::{vec::Vec, rc::Rc};
+use sp_std::vec::Vec;
use pallet_evm::account::CrossAccountId;
use frame_support::{
dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -24,7 +24,7 @@
use pallet_evm::account::CrossAccountId;
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
-use pallet_common::{CollectionHandle, erc::CollectionPropertiesCall};
+use pallet_common::{CollectionHandle, erc::CollectionCall};
use crate::{
Allowance, Balance, Config, FungibleHandle, Pallet, SelfWeightOf, TotalSupply,
@@ -150,7 +150,7 @@
is(
ERC20,
ERC20UniqueExtensions,
- via("CollectionHandle<T>", common_mut, CollectionProperties)
+ via("CollectionHandle<T>", common_mut, Collection)
)
)]
impl<T: Config> FungibleHandle<T> {}
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -26,7 +26,7 @@
use sp_core::{H160, U256};
use sp_std::vec::Vec;
use pallet_common::{
- erc::{CommonEvmHandler, PrecompileResult, CollectionPropertiesCall},
+ erc::{CommonEvmHandler, PrecompileResult, CollectionCall},
CollectionHandle,
};
use pallet_evm::account::CrossAccountId;
@@ -513,7 +513,7 @@
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
- via("CollectionHandle<T>", common_mut, CollectionProperties),
+ via("CollectionHandle<T>", common_mut, Collection),
TokenProperties,
)
)]
pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -51,6 +51,67 @@
event MintingFinished();
}
+// Selector: 38e33c60
+contract Collection is Dummy, ERC165 {
+ // Selector: setCollectionProperty(string,bytes) 2f073f66
+ function setCollectionProperty(string memory key, bytes memory value)
+ public
+ {
+ require(false, stub_error);
+ key;
+ value;
+ dummy = 0;
+ }
+
+ // Selector: deleteCollectionProperty(string) 7b7debce
+ function deleteCollectionProperty(string memory key) public {
+ require(false, stub_error);
+ key;
+ dummy = 0;
+ }
+
+ // Throws error if key not found
+ //
+ // Selector: collectionProperty(string) cf24fd6d
+ function collectionProperty(string memory key)
+ public
+ view
+ returns (bytes memory)
+ {
+ require(false, stub_error);
+ key;
+ dummy;
+ return hex"";
+ }
+
+ // Selector: ethSetSponsor(address) 8f9af356
+ function ethSetSponsor(address sponsor) public {
+ require(false, stub_error);
+ sponsor;
+ dummy = 0;
+ }
+
+ // Selector: ethConfirmSponsorship() a8580d1a
+ function ethConfirmSponsorship() public {
+ require(false, stub_error);
+ dummy = 0;
+ }
+
+ // Selector: setLimits(string) 72cb345d
+ function setLimits(string memory limitsJson) public view {
+ require(false, stub_error);
+ limitsJson;
+ dummy;
+ }
+
+ // Selector: contractAddress() f6b4dfb4
+ function contractAddress() public view returns (address) {
+ require(false, stub_error);
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+}
+
// Selector: 41369377
contract TokenProperties is Dummy, ERC165 {
// Selector: setTokenPropertyPermission(string,bool,bool,bool) 222d97fa
@@ -327,40 +388,6 @@
require(false, stub_error);
dummy;
return 0;
- }
-}
-
-// Selector: 9b5e29c5
-contract CollectionProperties is Dummy, ERC165 {
- // Selector: setCollectionProperty(string,bytes) 2f073f66
- function setCollectionProperty(string memory key, bytes memory value)
- public
- {
- require(false, stub_error);
- key;
- value;
- dummy = 0;
- }
-
- // Selector: deleteCollectionProperty(string) 7b7debce
- function deleteCollectionProperty(string memory key) public {
- require(false, stub_error);
- key;
- dummy = 0;
- }
-
- // Throws error if key not found
- //
- // Selector: collectionProperty(string) cf24fd6d
- function collectionProperty(string memory key)
- public
- view
- returns (bytes memory)
- {
- require(false, stub_error);
- key;
- dummy;
- return hex"";
}
}
@@ -423,6 +450,6 @@
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
- CollectionProperties,
+ Collection,
TokenProperties
{}
pallets/unique/Cargo.tomldiffbeforeafterboth--- a/pallets/unique/Cargo.toml
+++ b/pallets/unique/Cargo.toml
@@ -20,7 +20,6 @@
std = [
'codec/std',
'serde/std',
- 'serde-json-core/std',
'frame-support/std',
'frame-system/std',
'pallet-evm/std',
@@ -42,10 +41,6 @@
default-features = false
features = ['derive']
version = '1.0.130'
-
-[dependencies.serde-json-core]
-default-features = false
-version = "0.4"
[dependencies.ethereum]
version = "0.12.0"
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -110,17 +110,6 @@
}
}
- struct EvmCollection<T: Config>(H160, SubstrateRecorder<T>);
- impl<T: Config> WithRecorder<T> for EvmCollection<T> {
- fn recorder(&self) -> &SubstrateRecorder<T> {
- &self.1
- }
-
- fn into_recorder(self) -> SubstrateRecorder<T> {
- self.1
- }
- }
-
#[derive(ToLog)]
pub enum EthCollectionEvent {
CollectionCreated {
@@ -129,78 +118,7 @@
#[indexed]
collection_id: address,
},
- }
-
- #[solidity_interface(name = "Collection")]
- impl<T: Config> EvmCollection<T> {
- fn set_sponsor(
- &self,
- caller: caller,
- sponsor: address,
- ) -> Result<void> {
- let mut collection = collection_from_address::<T>(self.contract_address(caller).unwrap(), self.1.gas_left())?;
- check_is_owner(caller, &collection)?;
-
- let sponsor = T::CrossAccountId::from_eth(sponsor);
- collection.set_sponsor(sponsor.as_sub().clone());
- collection.save().map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
- Ok(())
- }
-
- fn confirm_sponsorship(&self, caller: caller) -> Result<void> {
- let mut collection = collection_from_address::<T>(self.contract_address(caller).unwrap(), self.1.gas_left())?;
- let caller = T::CrossAccountId::from_eth(caller);
- if !collection.confirm_sponsorship(caller.as_sub()) {
- return Err(Error::Revert("Caller is not set as sponsor".into()));
- }
- collection.save().map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
- Ok(())
- }
-
- fn set_limits(
- &self,
- caller: caller,
- limits_json: string,
- ) -> Result<void> {
- let mut collection = collection_from_address::<T>(self.contract_address(caller).unwrap(), self.1.gas_left())?;
- check_is_owner(caller, &collection)?;
-
- let limits = serde_json_core::from_str(limits_json.as_ref())
- .map_err(|e| Error::Revert(format!("Parse JSON error: {}", e)))?;
- collection.limits = limits.0;
- collection.save().map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
- Ok(())
- }
-
- fn contract_address(&self, _caller: caller) -> Result<address> {
- Ok(self.0)
- }
- }
-
- fn error_feild_too_long(feild: &str, bound: u32) -> Error {
- Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))
}
-
- fn collection_from_address<T: Config>(
- collection_address: address,
- gas_limit: u64
- ) -> Result<CollectionHandle<T>> {
- let collection_id = pallet_common::eth::map_eth_to_id(&collection_address)
- .ok_or(Error::Revert("Contract is not an unique collection".into()))?;
- let recorder = <SubstrateRecorder<T>>::new(gas_limit);
- let collection =
- pallet_common::CollectionHandle::new_with_recorder(collection_id, recorder)
- .ok_or(Error::Revert("Create collection handle error".into()))?;
- Ok(collection)
- }
-
- fn check_is_owner<T: Config>(caller: caller, collection: &CollectionHandle<T>) -> Result<()> {
- let caller = T::CrossAccountId::from_eth(caller);
- collection
- .check_is_owner(&caller)
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
- Ok(())
- }
pub struct CollectionHelperOnMethodCall<T: Config>(PhantomData<*const T>);
impl<T: Config> OnMethodCall<T> for CollectionHelperOnMethodCall<T> {
@@ -235,38 +153,8 @@
generate_stubgen!(collection_helper_impl, CollectionHelperCall<()>, true);
generate_stubgen!(collection_helper_iface, CollectionHelperCall<()>, false);
-
- pub struct CollectionOnMethodCall<T: Config>(PhantomData<*const T>);
- impl<T: Config> OnMethodCall<T> for CollectionOnMethodCall<T> {
- fn is_reserved(contract: &sp_core::H160) -> bool {
- contract == &T::ContractAddress::get()
- }
-
- fn is_used(contract: &sp_core::H160) -> bool {
- contract == &T::ContractAddress::get()
- }
-
- fn call(
- source: &sp_core::H160,
- target: &sp_core::H160,
- gas_left: u64,
- input: &[u8],
- value: sp_core::U256,
- ) -> Option<PrecompileResult> {
- if !pallet_common::eth::is_collection(target) {
- return None;
- }
- let helpers = EvmCollection::<T>(*target, SubstrateRecorder::<T>::new(gas_left));
- pallet_evm_coder_substrate::call(*source, helpers, value, input)
- }
-
- fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {
- (contract == &T::ContractAddress::get())
- .then(|| include_bytes!("./stubs/Collection.raw").to_vec())
- }
+ fn error_feild_too_long(feild: &str, bound: u32) -> Error {
+ Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))
}
-
- generate_stubgen!(collection_impl, CollectionCall<()>, true);
- generate_stubgen!(collection_iface, CollectionCall<()>, false);
}
pallets/unique/src/eth/stubs/Collection.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/Collection.soldiffbeforeafterboth--- a/pallets/unique/src/eth/stubs/Collection.sol
+++ /dev/null
@@ -1,52 +0,0 @@
-// SPDX-License-Identifier: OTHER
-// This code is automatically generated
-
-pragma solidity >=0.8.0 <0.9.0;
-
-// Common stubs holder
-contract Dummy {
- uint8 dummy;
- string stub_error = "this contract is implemented in native";
-}
-
-contract ERC165 is Dummy {
- function supportsInterface(bytes4 interfaceID)
- external
- view
- returns (bool)
- {
- require(false, stub_error);
- interfaceID;
- return true;
- }
-}
-
-// Selector: 15cc740e
-contract Collection is Dummy, ERC165 {
- // Selector: setSponsor(address) 59753fb1
- function setSponsor(address sponsor) public view {
- require(false, stub_error);
- sponsor;
- dummy;
- }
-
- // Selector: confirmSponsorship() c8c6a056
- function confirmSponsorship() public view {
- require(false, stub_error);
- dummy;
- }
-
- // Selector: setLimits(string) 72cb345d
- function setLimits(string memory limitsJson) public view {
- require(false, stub_error);
- limitsJson;
- dummy;
- }
-
- // Selector: contractAddress() f6b4dfb4
- function contractAddress() public view returns (address) {
- require(false, stub_error);
- dummy;
- return 0x0000000000000000000000000000000000000000;
- }
-}
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -307,7 +307,6 @@
pallet_evm_migration::OnMethodCall<Self>,
pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
CollectionDispatchT<Self>,
- evm_collection::CollectionOnMethodCall<Self>,
evm_collection::CollectionHelperOnMethodCall<Self>,
);
type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -286,7 +286,6 @@
pallet_evm_migration::OnMethodCall<Self>,
pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
CollectionDispatchT<Self>,
- evm_collection::CollectionOnMethodCall<Self>,
evm_collection::CollectionHelperOnMethodCall<Self>,
);
type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -291,7 +291,6 @@
pallet_evm_migration::OnMethodCall<Self>,
pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
CollectionDispatchT<Self>,
- evm_collection::CollectionOnMethodCall<Self>,
evm_collection::CollectionHelperOnMethodCall<Self>,
);
type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -42,6 +42,36 @@
event MintingFinished();
}
+// Selector: 38e33c60
+interface Collection is Dummy, ERC165 {
+ // Selector: setCollectionProperty(string,bytes) 2f073f66
+ function setCollectionProperty(string memory key, bytes memory value)
+ external;
+
+ // Selector: deleteCollectionProperty(string) 7b7debce
+ function deleteCollectionProperty(string memory key) external;
+
+ // Throws error if key not found
+ //
+ // Selector: collectionProperty(string) cf24fd6d
+ function collectionProperty(string memory key)
+ external
+ view
+ returns (bytes memory);
+
+ // Selector: ethSetSponsor(address) 8f9af356
+ function ethSetSponsor(address sponsor) external;
+
+ // Selector: ethConfirmSponsorship() a8580d1a
+ function ethConfirmSponsorship() external;
+
+ // Selector: setLimits(string) 72cb345d
+ function setLimits(string memory limitsJson) external view;
+
+ // Selector: contractAddress() f6b4dfb4
+ function contractAddress() external view returns (address);
+}
+
// Selector: 41369377
interface TokenProperties is Dummy, ERC165 {
// Selector: setTokenPropertyPermission(string,bool,bool,bool) 222d97fa
@@ -191,24 +221,6 @@
function totalSupply() external view returns (uint256);
}
-// Selector: 9b5e29c5
-interface CollectionProperties is Dummy, ERC165 {
- // Selector: setCollectionProperty(string,bytes) 2f073f66
- function setCollectionProperty(string memory key, bytes memory value)
- external;
-
- // Selector: deleteCollectionProperty(string) 7b7debce
- function deleteCollectionProperty(string memory key) external;
-
- // Throws error if key not found
- //
- // Selector: collectionProperty(string) cf24fd6d
- function collectionProperty(string memory key)
- external
- view
- returns (bytes memory);
-}
-
// Selector: d74d154f
interface ERC721UniqueExtensions is Dummy, ERC165 {
// Selector: transfer(address,uint256) a9059cbb
@@ -240,6 +252,6 @@
ERC721UniqueExtensions,
ERC721Mintable,
ERC721Burnable,
- CollectionProperties,
+ Collection,
TokenProperties
{}
tests/src/eth/collectionAbi.jsondiffbeforeafterboth--- a/tests/src/eth/collectionAbi.json
+++ /dev/null
@@ -1,43 +0,0 @@
-[
- {
- "inputs": [],
- "name": "confirmSponsorship",
- "outputs": [],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [],
- "name": "contractAddress",
- "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- { "internalType": "string", "name": "limitsJson", "type": "string" }
- ],
- "name": "setLimits",
- "outputs": [],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- { "internalType": "address", "name": "sponsor", "type": "address" }
- ],
- "name": "setSponsor",
- "outputs": [],
- "stateMutability": "view",
- "type": "function"
- },
- {
- "inputs": [
- { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
- ],
- "name": "supportsInterface",
- "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
- "stateMutability": "view",
- "type": "function"
- }
-]
tests/src/eth/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createCollection.test.ts
+++ b/tests/src/eth/createCollection.test.ts
@@ -88,13 +88,13 @@
const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
const sponsor = await createEthAccountWithBalance(api, web3);
const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
- result = await collectionEvm.methods.setSponsor(sponsor).send();
+ result = await collectionEvm.methods.ethSetSponsor(sponsor).send();
let collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
expect(collectionSub.sponsorship.isUnconfirmed).to.be.true;
expect(collectionSub.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
- await expect(collectionEvm.methods.confirmSponsorship().call()).to.be.rejectedWith('Caller is not set as sponsor');
+ await expect(collectionEvm.methods.ethConfirmSponsorship().call()).to.be.rejectedWith('Caller is not set as sponsor');
const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
- await sponsorCollection.methods.confirmSponsorship().send();
+ await sponsorCollection.methods.ethConfirmSponsorship().send();
collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
expect(collectionSub.sponsorship.isConfirmed).to.be.true;
expect(collectionSub.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -126,6 +126,13 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "contractAddress",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "deleteCollectionProperty",
"outputs": [],
@@ -144,6 +151,22 @@
},
{
"inputs": [],
+ "name": "ethConfirmSponsorship",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "sponsor", "type": "address" }
+ ],
+ "name": "ethSetSponsor",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [],
"name": "finishMinting",
"outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
"stateMutability": "nonpayable",
@@ -302,6 +325,15 @@
},
{
"inputs": [
+ { "internalType": "string", "name": "limitsJson", "type": "string" }
+ ],
+ "name": "setLimits",
+ "outputs": [],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" },
{ "internalType": "string", "name": "key", "type": "string" },
{ "internalType": "bytes", "name": "value", "type": "bytes" }
tests/src/eth/util/helpers.tsdiffbeforeafterboth1// 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// eslint-disable-next-line @typescript-eslint/triple-slash-reference18/// <reference path="helpers.d.ts" />1920import {ApiPromise} from '@polkadot/api';21import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';22import Web3 from 'web3';23import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';24import {IKeyringPair} from '@polkadot/types/types';25import {expect} from 'chai';26import {CrossAccountId, getGenericResult, UNIQUE} from '../../util/helpers';27import * as solc from 'solc';28import config from '../../config';29import privateKey from '../../substrate/privateKey';30import contractHelpersAbi from './contractHelpersAbi.json';31import collectionAbi from '../collectionAbi.json';32import collectionHelperAbi from '../collectionHelperAbi.json';33import getBalance from '../../substrate/get-balance';34import waitNewBlocks from '../../substrate/wait-new-blocks';3536export const GAS_ARGS = {gas: 2500000};3738export enum SponsoringMode {39 Disabled = 0,40 Allowlisted = 1,41 Generous = 2,42}4344let web3Connected = false;45export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {46 if (web3Connected) throw new Error('do not nest usingWeb3 calls');47 web3Connected = true;4849 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);50 const web3 = new Web3(provider);5152 try {53 return await cb(web3);54 } finally {55 // provider.disconnect(3000, 'normal disconnect');56 provider.connection.close();57 web3Connected = false;58 }59}6061function encodeIntBE(v: number): number[] {62 if (v >= 0xffffffff || v < 0) throw new Error('id overflow');63 return [64 v >> 24,65 (v >> 16) & 0xff,66 (v >> 8) & 0xff,67 v & 0xff,68 ];69}7071export function collectionIdToAddress(collection: number): string {72 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,73 ...encodeIntBE(collection),74 ]);75 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));76}77export function collectionIdFromAddress(address: string): number {78 if (!address.startsWith('0x'))79 throw 'address not starts with "0x"';80 if (address.length > 42)81 throw 'address length is more than 20 bytes';82 return Number('0x' + address.substring(address.length - 8));83}84 85export function normalizeAddress(address: string): string {86 return '0x' + address.substring(address.length - 40);87}8889export function tokenIdToAddress(collection: number, token: number): string {90 const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,91 ...encodeIntBE(collection),92 ...encodeIntBE(token),93 ]);94 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));95}96export function tokenIdToCross(collection: number, token: number): CrossAccountId {97 return {98 Ethereum: tokenIdToAddress(collection, token),99 };100}101102export function createEthAccount(web3: Web3) {103 const account = web3.eth.accounts.create();104 web3.eth.accounts.wallet.add(account.privateKey);105 return account.address;106}107108export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {109 const alice = privateKey('//Alice');110 const account = createEthAccount(web3);111 await transferBalanceToEth(api, alice, account);112113 return account;114}115116export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {117 const tx = api.tx.balances.transfer(evmToAddress(target), amount);118 const events = await submitTransactionAsync(source, tx);119 const result = getGenericResult(events);120 expect(result.success).to.be.true;121}122123export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {124 let i: any = it;125 if (opts.only) i = i.only;126 else if (opts.skip) i = i.skip;127 i(name, async () => {128 await usingApi(async api => {129 await usingWeb3(async web3 => {130 await cb({api, web3});131 });132 });133 });134}135itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});136itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});137138export async function generateSubstrateEthPair(web3: Web3) {139 const account = web3.eth.accounts.create();140 evmToAddress(account.address);141}142143type NormalizedEvent = {144 address: string,145 event: string,146 args: { [key: string]: string }147};148149export function normalizeEvents(events: any): NormalizedEvent[] {150 const output = [];151 for (const key of Object.keys(events)) {152 if (key.match(/^[0-9]+$/)) {153 output.push(events[key]);154 } else if (Array.isArray(events[key])) {155 output.push(...events[key]);156 } else {157 output.push(events[key]);158 }159 }160 output.sort((a, b) => a.logIndex - b.logIndex);161 return output.map(({address, event, returnValues}) => {162 const args: { [key: string]: string } = {};163 for (const key of Object.keys(returnValues)) {164 if (!key.match(/^[0-9]+$/)) {165 args[key] = returnValues[key];166 }167 }168 return {169 address,170 event,171 args,172 };173 });174}175176export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {177 const out: any = [];178 contract.events.allEvents((_: any, event: any) => {179 out.push(event);180 });181 await action();182 return normalizeEvents(out);183}184185export function subToEthLowercase(eth: string): string {186 const bytes = addressToEvm(eth);187 return '0x' + Buffer.from(bytes).toString('hex');188}189190export function subToEth(eth: string): string {191 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));192}193194export function compileContract(name: string, src: string) {195 const out = JSON.parse(solc.compile(JSON.stringify({196 language: 'Solidity',197 sources: {198 [`${name}.sol`]: {199 content: `200 // SPDX-License-Identifier: UNLICENSED201 pragma solidity ^0.8.6;202203 ${src}204 `,205 },206 },207 settings: {208 outputSelection: {209 '*': {210 '*': ['*'],211 },212 },213 },214 }))).contracts[`${name}.sol`][name];215216 return {217 abi: out.abi,218 object: '0x' + out.evm.bytecode.object,219 };220}221222export async function deployFlipper(web3: Web3, deployer: string) {223 const compiled = compileContract('Flipper', `224 contract Flipper {225 bool value = false;226 function flip() public {227 value = !value;228 }229 function getValue() public view returns (bool) {230 return value;231 }232 }233 `);234 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {235 data: compiled.object,236 from: deployer,237 ...GAS_ARGS,238 });239 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});240241 return flipper;242}243244export async function deployCollector(web3: Web3, deployer: string) {245 const compiled = compileContract('Collector', `246 contract Collector {247 uint256 collected;248 fallback() external payable {249 giveMoney();250 }251 function giveMoney() public payable {252 collected += msg.value;253 }254 function getCollected() public view returns (uint256) {255 return collected;256 }257 function getUnaccounted() public view returns (uint256) {258 return address(this).balance - collected;259 }260261 function withdraw(address payable target) public {262 target.transfer(collected);263 collected = 0;264 }265 }266 `);267 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {268 data: compiled.object,269 from: deployer,270 ...GAS_ARGS,271 });272 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});273274 return collector;275}276277/** 278 * pallet evm_contract_helpers279 * @param web3 280 * @param caller - eth address281 * @returns 282 */283export function contractHelpers(web3: Web3, caller: string) {284 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});285}286287/** 288 * evm collection helper289 * @param web3 290 * @param caller - eth address291 * @returns 292 */293export function evmCollectionHelper(web3: Web3, caller: string) {294 return new web3.eth.Contract(collectionHelperAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});295}296297/** 298 * evm collection299 * @param web3 300 * @param caller - eth address301 * @returns 302 */303export function evmCollection(web3: Web3, caller: string, collection: string) {304 return new web3.eth.Contract(collectionAbi as any, collection, {from: caller, ...GAS_ARGS});305}306307/**308 * Execute ethereum method call using substrate account309 * @param to target contract310 * @param mkTx - closure, receiving `contract.methods`, and returning method call,311 * to be used as following (assuming `to` = erc20 contract):312 * `m => m.transfer(to, amount)`313 *314 * # Example315 * ```ts316 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));317 * ```318 */319export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {320 const tx = api.tx.evm.call(321 subToEth(from.address),322 to.options.address,323 mkTx(to.methods).encodeABI(),324 value,325 GAS_ARGS.gas,326 await web3.eth.getGasPrice(),327 null,328 null,329 [],330 );331 const events = await submitTransactionAsync(from, tx);332 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;333}334335export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {336 return (await getBalance(api, [evmToAddress(address)]))[0];337}338339/**340 * Measure how much gas given closure consumes341 *342 * @param user which user balance will be checked343 */344export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {345 const before = await ethBalanceViaSub(api, user);346347 await call();348349 // In dev mode, the transaction might not finish processing in time350 await waitNewBlocks(api, 1);351 const after = await ethBalanceViaSub(api, user);352353 // Can't use .to.be.less, because chai doesn't supports bigint354 expect(after < before).to.be.true;355356 return before - after;357}358359type ElementOf<A> = A extends readonly (infer T)[] ? T : never;360// I want a fancier api, not a memory efficiency361export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {362 if(args.length === 0) {363 yield internalRest as any;364 return;365 }366 for(const value of args[0]) {367 yield* cartesian([...internalRest, value], ...args.slice(1)) as any;368 }369}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// eslint-disable-next-line @typescript-eslint/triple-slash-reference18/// <reference path="helpers.d.ts" />1920import {ApiPromise} from '@polkadot/api';21import {addressToEvm, evmToAddress} from '@polkadot/util-crypto';22import Web3 from 'web3';23import usingApi, {submitTransactionAsync} from '../../substrate/substrate-api';24import {IKeyringPair} from '@polkadot/types/types';25import {expect} from 'chai';26import {CrossAccountId, getGenericResult, UNIQUE} from '../../util/helpers';27import * as solc from 'solc';28import config from '../../config';29import privateKey from '../../substrate/privateKey';30import contractHelpersAbi from './contractHelpersAbi.json';31import collectionAbi from '../nonFungibleAbi.json';32import collectionHelperAbi from '../collectionHelperAbi.json';33import getBalance from '../../substrate/get-balance';34import waitNewBlocks from '../../substrate/wait-new-blocks';3536export const GAS_ARGS = {gas: 2500000};3738export enum SponsoringMode {39 Disabled = 0,40 Allowlisted = 1,41 Generous = 2,42}4344let web3Connected = false;45export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {46 if (web3Connected) throw new Error('do not nest usingWeb3 calls');47 web3Connected = true;4849 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);50 const web3 = new Web3(provider);5152 try {53 return await cb(web3);54 } finally {55 // provider.disconnect(3000, 'normal disconnect');56 provider.connection.close();57 web3Connected = false;58 }59}6061function encodeIntBE(v: number): number[] {62 if (v >= 0xffffffff || v < 0) throw new Error('id overflow');63 return [64 v >> 24,65 (v >> 16) & 0xff,66 (v >> 8) & 0xff,67 v & 0xff,68 ];69}7071export function collectionIdToAddress(collection: number): string {72 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,73 ...encodeIntBE(collection),74 ]);75 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));76}77export function collectionIdFromAddress(address: string): number {78 if (!address.startsWith('0x'))79 throw 'address not starts with "0x"';80 if (address.length > 42)81 throw 'address length is more than 20 bytes';82 return Number('0x' + address.substring(address.length - 8));83}84 85export function normalizeAddress(address: string): string {86 return '0x' + address.substring(address.length - 40);87}8889export function tokenIdToAddress(collection: number, token: number): string {90 const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,91 ...encodeIntBE(collection),92 ...encodeIntBE(token),93 ]);94 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));95}96export function tokenIdToCross(collection: number, token: number): CrossAccountId {97 return {98 Ethereum: tokenIdToAddress(collection, token),99 };100}101102export function createEthAccount(web3: Web3) {103 const account = web3.eth.accounts.create();104 web3.eth.accounts.wallet.add(account.privateKey);105 return account.address;106}107108export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {109 const alice = privateKey('//Alice');110 const account = createEthAccount(web3);111 await transferBalanceToEth(api, alice, account);112113 return account;114}115116export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {117 const tx = api.tx.balances.transfer(evmToAddress(target), amount);118 const events = await submitTransactionAsync(source, tx);119 const result = getGenericResult(events);120 expect(result.success).to.be.true;121}122123export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {124 let i: any = it;125 if (opts.only) i = i.only;126 else if (opts.skip) i = i.skip;127 i(name, async () => {128 await usingApi(async api => {129 await usingWeb3(async web3 => {130 await cb({api, web3});131 });132 });133 });134}135itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});136itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});137138export async function generateSubstrateEthPair(web3: Web3) {139 const account = web3.eth.accounts.create();140 evmToAddress(account.address);141}142143type NormalizedEvent = {144 address: string,145 event: string,146 args: { [key: string]: string }147};148149export function normalizeEvents(events: any): NormalizedEvent[] {150 const output = [];151 for (const key of Object.keys(events)) {152 if (key.match(/^[0-9]+$/)) {153 output.push(events[key]);154 } else if (Array.isArray(events[key])) {155 output.push(...events[key]);156 } else {157 output.push(events[key]);158 }159 }160 output.sort((a, b) => a.logIndex - b.logIndex);161 return output.map(({address, event, returnValues}) => {162 const args: { [key: string]: string } = {};163 for (const key of Object.keys(returnValues)) {164 if (!key.match(/^[0-9]+$/)) {165 args[key] = returnValues[key];166 }167 }168 return {169 address,170 event,171 args,172 };173 });174}175176export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {177 const out: any = [];178 contract.events.allEvents((_: any, event: any) => {179 out.push(event);180 });181 await action();182 return normalizeEvents(out);183}184185export function subToEthLowercase(eth: string): string {186 const bytes = addressToEvm(eth);187 return '0x' + Buffer.from(bytes).toString('hex');188}189190export function subToEth(eth: string): string {191 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));192}193194export function compileContract(name: string, src: string) {195 const out = JSON.parse(solc.compile(JSON.stringify({196 language: 'Solidity',197 sources: {198 [`${name}.sol`]: {199 content: `200 // SPDX-License-Identifier: UNLICENSED201 pragma solidity ^0.8.6;202203 ${src}204 `,205 },206 },207 settings: {208 outputSelection: {209 '*': {210 '*': ['*'],211 },212 },213 },214 }))).contracts[`${name}.sol`][name];215216 return {217 abi: out.abi,218 object: '0x' + out.evm.bytecode.object,219 };220}221222export async function deployFlipper(web3: Web3, deployer: string) {223 const compiled = compileContract('Flipper', `224 contract Flipper {225 bool value = false;226 function flip() public {227 value = !value;228 }229 function getValue() public view returns (bool) {230 return value;231 }232 }233 `);234 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {235 data: compiled.object,236 from: deployer,237 ...GAS_ARGS,238 });239 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});240241 return flipper;242}243244export async function deployCollector(web3: Web3, deployer: string) {245 const compiled = compileContract('Collector', `246 contract Collector {247 uint256 collected;248 fallback() external payable {249 giveMoney();250 }251 function giveMoney() public payable {252 collected += msg.value;253 }254 function getCollected() public view returns (uint256) {255 return collected;256 }257 function getUnaccounted() public view returns (uint256) {258 return address(this).balance - collected;259 }260261 function withdraw(address payable target) public {262 target.transfer(collected);263 collected = 0;264 }265 }266 `);267 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {268 data: compiled.object,269 from: deployer,270 ...GAS_ARGS,271 });272 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});273274 return collector;275}276277/** 278 * pallet evm_contract_helpers279 * @param web3 280 * @param caller - eth address281 * @returns 282 */283export function contractHelpers(web3: Web3, caller: string) {284 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});285}286287/** 288 * evm collection helper289 * @param web3 290 * @param caller - eth address291 * @returns 292 */293export function evmCollectionHelper(web3: Web3, caller: string) {294 return new web3.eth.Contract(collectionHelperAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});295}296297/** 298 * evm collection299 * @param web3 300 * @param caller - eth address301 * @returns 302 */303export function evmCollection(web3: Web3, caller: string, collection: string) {304 return new web3.eth.Contract(collectionAbi as any, collection, {from: caller, ...GAS_ARGS});305}306307/**308 * Execute ethereum method call using substrate account309 * @param to target contract310 * @param mkTx - closure, receiving `contract.methods`, and returning method call,311 * to be used as following (assuming `to` = erc20 contract):312 * `m => m.transfer(to, amount)`313 *314 * # Example315 * ```ts316 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));317 * ```318 */319export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {320 const tx = api.tx.evm.call(321 subToEth(from.address),322 to.options.address,323 mkTx(to.methods).encodeABI(),324 value,325 GAS_ARGS.gas,326 await web3.eth.getGasPrice(),327 null,328 null,329 [],330 );331 const events = await submitTransactionAsync(from, tx);332 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;333}334335export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {336 return (await getBalance(api, [evmToAddress(address)]))[0];337}338339/**340 * Measure how much gas given closure consumes341 *342 * @param user which user balance will be checked343 */344export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {345 const before = await ethBalanceViaSub(api, user);346347 await call();348349 // In dev mode, the transaction might not finish processing in time350 await waitNewBlocks(api, 1);351 const after = await ethBalanceViaSub(api, user);352353 // Can't use .to.be.less, because chai doesn't supports bigint354 expect(after < before).to.be.true;355356 return before - after;357}358359type ElementOf<A> = A extends readonly (infer T)[] ? T : never;360// I want a fancier api, not a memory efficiency361export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {362 if(args.length === 0) {363 yield internalRest as any;364 return;365 }366 for(const value of args[0]) {367 yield* cartesian([...internalRest, value], ...args.slice(1)) as any;368 }369}