difftreelog
CORE-345 Split evm collection to collection and helper
in: master
16 files changed
Makefilediffbeforeafterboth--- a/Makefile
+++ b/Makefile
@@ -18,6 +18,9 @@
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
@@ -36,9 +39,13 @@
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::pallet_evm_collection::collection_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
- PACKAGE=pallet-unique NAME=eth::pallet_evm_collection::collection_impl OUTPUT=$(COLLECTION_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
+ 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
+
UniqueFungible: UniqueFungible.sol
INPUT=$(FUNGIBLE_EVM_STUBS)/$< OUTPUT=$(FUNGIBLE_EVM_STUBS)/UniqueFungible.raw ./.maintain/scripts/compile_stub.sh
INPUT=$(FUNGIBLE_EVM_STUBS)/$< OUTPUT=$(FUNGIBLE_EVM_ABI) ./.maintain/scripts/generate_abi.sh
@@ -55,7 +62,11 @@
INPUT=$(COLLECTION_STUBS)/$< OUTPUT=$(COLLECTION_STUBS)/Collection.raw ./.maintain/scripts/compile_stub.sh
INPUT=$(COLLECTION_STUBS)/$< OUTPUT=$(COLLECTION_ABI) ./.maintain/scripts/generate_abi.sh
-evm_stubs: UniqueFungible UniqueNFT ContractHelpers Collection
+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
.PHONY: _bench
_bench:
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -112,7 +112,6 @@
use sp_std::{vec::Vec, rc::Rc};
use alloc::format;
- // #[pallet::config]
pub trait Config:
frame_system::Config
+ pallet_evm_coder_substrate::Config
@@ -122,8 +121,8 @@
type ContractAddress: Get<H160>;
}
- struct EvmCollection<T: Config>(Rc<SubstrateRecorder<T>>);
- impl<T: Config> WithRecorder<T> for EvmCollection<T> {
+ struct EvmCollectionHelper<T: Config>(Rc<SubstrateRecorder<T>>);
+ impl<T: Config> WithRecorder<T> for EvmCollectionHelper<T> {
fn recorder(&self) -> &SubstrateRecorder<T> {
&self.0
}
@@ -132,19 +131,9 @@
self.0
}
}
-
- #[derive(ToLog)]
- pub enum EthCollectionEvent {
- CollectionCreated {
- #[indexed]
- owner: address,
- #[indexed]
- collection_id: address,
- },
- }
-
- #[solidity_interface(name = "Collection")]
- impl<T: Config> EvmCollection<T> {
+
+ #[solidity_interface(name = "CollectionHelper")]
+ impl<T: Config> EvmCollectionHelper<T> {
fn create_721_collection(
&self,
caller: caller,
@@ -188,14 +177,37 @@
});
Ok(address)
}
+ }
+
+ struct EvmCollection<T: Config>(Rc<SubstrateRecorder<T>>);
+ impl<T: Config> WithRecorder<T> for EvmCollection<T> {
+ fn recorder(&self) -> &SubstrateRecorder<T> {
+ &self.0
+ }
+
+ fn into_recorder(self) -> Rc<SubstrateRecorder<T>> {
+ self.0
+ }
+ }
+
+ #[derive(ToLog)]
+ pub enum EthCollectionEvent {
+ CollectionCreated {
+ #[indexed]
+ owner: address,
+ #[indexed]
+ collection_id: address,
+ },
+ }
+ #[solidity_interface(name = "Collection")]
+ impl<T: Config> EvmCollection<T> {
fn set_sponsor(
&self,
caller: caller,
- collection_address: address,
sponsor: address,
) -> Result<void> {
- let mut collection = collection_from_address(collection_address, &self.0)?;
+ let mut collection = collection_from_address(self.contract_address(caller).unwrap(), &self.0)?;
check_is_owner(caller, &collection)?;
let sponsor = T::CrossAccountId::from_eth(sponsor);
@@ -203,8 +215,8 @@
save_eth(collection)
}
- fn confirm_sponsorship(&self, caller: caller, collection_address: address) -> Result<void> {
- let mut collection = collection_from_address(collection_address, &self.0)?;
+ fn confirm_sponsorship(&self, caller: caller) -> Result<void> {
+ let mut collection = collection_from_address(self.contract_address(caller).unwrap(), &self.0)?;
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()));
@@ -215,10 +227,9 @@
fn set_limits(
&self,
caller: caller,
- collection_address: address,
limits_json: string,
) -> Result<void> {
- let mut collection = collection_from_address(collection_address, &self.0)?;
+ let mut collection = collection_from_address(self.contract_address(caller).unwrap(), &self.0)?;
check_is_owner(caller, &collection)?;
let limits = serde_json_core::from_str(limits_json.as_ref())
@@ -226,6 +237,10 @@
collection.limits = limits.0;
save_eth(collection)
}
+
+ fn contract_address(&self, _caller: caller) -> Result<address> {
+ Ok(self.0.contract())
+ }
}
fn error_feild_too_long(feild: &str, bound: u32) -> Error {
@@ -251,9 +266,9 @@
.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
Ok(())
}
-
- pub struct CollectionOnMethodCall<T: Config>(PhantomData<*const T>);
- impl<T: Config> OnMethodCall<T> for CollectionOnMethodCall<T> {
+
+ pub struct CollectionHelperOnMethodCall<T: Config>(PhantomData<*const T>);
+ impl<T: Config> OnMethodCall<T> for CollectionHelperOnMethodCall<T> {
fn is_reserved(contract: &sp_core::H160) -> bool {
contract == &T::ContractAddress::get()
}
@@ -273,6 +288,36 @@
return None;
}
+ let helpers = EvmCollectionHelper::<T>(Rc::new(SubstrateRecorder::<T>::new(*target, 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/CollectionHelper.raw").to_vec())
+ }
+ }
+
+ 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> {
let helpers = EvmCollection::<T>(Rc::new(SubstrateRecorder::<T>::new(*target, gas_left)));
pallet_evm_coder_substrate::call(*source, helpers, value, input)
}
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
+++ b/pallets/unique/src/eth/stubs/Collection.sol
@@ -21,48 +21,32 @@
}
}
-// Selector: 1e95830f
+// Selector: 15cc740e
contract Collection is Dummy, ERC165 {
- // Selector: create721Collection(string,string,string) 951c0151
- function create721Collection(
- string memory name,
- string memory description,
- string memory tokenPrefix
- ) public view returns (address) {
+ // Selector: setSponsor(address) 59753fb1
+ function setSponsor(address sponsor) public view {
require(false, stub_error);
- name;
- description;
- tokenPrefix;
+ sponsor;
dummy;
- return 0x0000000000000000000000000000000000000000;
}
- // Selector: setSponsor(address,address) f01fba93
- function setSponsor(address collectionAddress, address sponsor)
- public
- view
- {
+ // Selector: confirmSponsorship() c8c6a056
+ function confirmSponsorship() public view {
require(false, stub_error);
- collectionAddress;
- sponsor;
dummy;
}
- // Selector: confirmSponsorship(address) abc00001
- function confirmSponsorship(address collectionAddress) public view {
+ // Selector: setLimits(string) 72cb345d
+ function setLimits(string memory limitsJson) public view {
require(false, stub_error);
- collectionAddress;
+ limitsJson;
dummy;
}
- // Selector: setLimits(address,string) d05638cc
- function setLimits(address collectionAddress, string memory limitsJson)
- public
- view
- {
+ // Selector: contractAddress() f6b4dfb4
+ function contractAddress() public view returns (address) {
require(false, stub_error);
- collectionAddress;
- limitsJson;
dummy;
+ return 0x0000000000000000000000000000000000000000;
}
}
pallets/unique/src/eth/stubs/CollectionHelper.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelper.soldiffbeforeafterboth--- /dev/null
+++ b/pallets/unique/src/eth/stubs/CollectionHelper.sol
@@ -0,0 +1,39 @@
+// 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: 951c0151
+contract CollectionHelper is Dummy, ERC165 {
+ // Selector: create721Collection(string,string,string) 951c0151
+ function create721Collection(
+ string memory name,
+ string memory description,
+ string memory tokenPrefix
+ ) public view returns (address) {
+ require(false, stub_error);
+ name;
+ description;
+ tokenPrefix;
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+}
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -308,6 +308,7 @@
pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
CollectionDispatchT<Self>,
evm_collection::CollectionOnMethodCall<Self>,
+ evm_collection::CollectionHelperOnMethodCall<Self>,
);
type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
type ChainId = ChainId;
@@ -978,7 +979,7 @@
]);
// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
- pub const EvmCollectionAddress: H160 = H160([
+ pub const EvmCollectionHelperAddress: H160 = H160([
0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
]);
}
@@ -989,7 +990,7 @@
}
impl evm_collection::Config for Runtime {
- type ContractAddress = EvmCollectionAddress;
+ type ContractAddress = EvmCollectionHelperAddress;
}
construct_runtime!(
runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -280,6 +280,7 @@
pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
CollectionDispatchT<Self>,
evm_collection::CollectionOnMethodCall<Self>,
+ evm_collection::CollectionHelperOnMethodCall<Self>,
);
type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
type ChainId = ChainId;
@@ -955,7 +956,7 @@
]);
// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
- pub const EvmCollectionAddress: H160 = H160([
+ pub const EvmCollectionHelperAddress: H160 = H160([
0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
]);
}
@@ -966,7 +967,7 @@
}
impl evm_collection::Config for Runtime {
- type ContractAddress = EvmCollectionAddress;
+ type ContractAddress = EvmCollectionHelperAddress;
}
construct_runtime!(
runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -284,6 +284,7 @@
pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
CollectionDispatchT<Self>,
evm_collection::CollectionOnMethodCall<Self>,
+ evm_collection::CollectionHelperOnMethodCall<Self>,
);
type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
type ChainId = ChainId;
@@ -960,7 +961,7 @@
]);
// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
- pub const EvmCollectionAddress: H160 = H160([
+ pub const EvmCollectionHelperAddress: H160 = H160([
0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
]);
}
@@ -971,7 +972,7 @@
}
impl evm_collection::Config for Runtime {
- type ContractAddress = EvmCollectionAddress;
+ type ContractAddress = EvmCollectionHelperAddress;
}
construct_runtime!(
tests/src/eth/api/Collection.soldiffbeforeafterboth--- a/tests/src/eth/api/Collection.sol
+++ b/tests/src/eth/api/Collection.sol
@@ -12,25 +12,17 @@
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
-// Selector: 1e95830f
+// Selector: 15cc740e
interface Collection is Dummy, ERC165 {
- // Selector: create721Collection(string,string,string) 951c0151
- function create721Collection(
- string memory name,
- string memory description,
- string memory tokenPrefix
- ) external view returns (address);
+ // Selector: setSponsor(address) 59753fb1
+ function setSponsor(address sponsor) external view;
- // Selector: setSponsor(address,address) f01fba93
- function setSponsor(address collectionAddress, address sponsor)
- external
- view;
+ // Selector: confirmSponsorship() c8c6a056
+ function confirmSponsorship() external view;
- // Selector: confirmSponsorship(address) abc00001
- function confirmSponsorship(address collectionAddress) external view;
+ // Selector: setLimits(string) 72cb345d
+ function setLimits(string memory limitsJson) external view;
- // Selector: setLimits(address,string) d05638cc
- function setLimits(address collectionAddress, string memory limitsJson)
- external
- view;
+ // Selector: contractAddress() f6b4dfb4
+ function contractAddress() external view returns (address);
}
tests/src/eth/api/CollectionHelper.soldiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/api/CollectionHelper.sol
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: OTHER
+// This code is automatically generated
+
+pragma solidity >=0.8.0 <0.9.0;
+
+// Common stubs holder
+interface Dummy {
+
+}
+
+interface ERC165 is Dummy {
+ function supportsInterface(bytes4 interfaceID) external view returns (bool);
+}
+
+// Selector: 951c0151
+interface CollectionHelper is Dummy, ERC165 {
+ // Selector: create721Collection(string,string,string) 951c0151
+ function create721Collection(
+ string memory name,
+ string memory description,
+ string memory tokenPrefix
+ ) external view returns (address);
+}
tests/src/eth/collectionAbi.jsondiffbeforeafterboth--- a/tests/src/eth/collectionAbi.json
+++ b/tests/src/eth/collectionAbi.json
@@ -1,35 +1,20 @@
[
{
- "inputs": [
- {
- "internalType": "address",
- "name": "collectionAddress",
- "type": "address"
- }
- ],
+ "inputs": [],
"name": "confirmSponsorship",
"outputs": [],
"stateMutability": "view",
"type": "function"
},
{
- "inputs": [
- { "internalType": "string", "name": "name", "type": "string" },
- { "internalType": "string", "name": "description", "type": "string" },
- { "internalType": "string", "name": "tokenPrefix", "type": "string" }
- ],
- "name": "create721Collection",
+ "inputs": [],
+ "name": "contractAddress",
"outputs": [{ "internalType": "address", "name": "", "type": "address" }],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
- {
- "internalType": "address",
- "name": "collectionAddress",
- "type": "address"
- },
{ "internalType": "string", "name": "limitsJson", "type": "string" }
],
"name": "setLimits",
@@ -39,11 +24,6 @@
},
{
"inputs": [
- {
- "internalType": "address",
- "name": "collectionAddress",
- "type": "address"
- },
{ "internalType": "address", "name": "sponsor", "type": "address" }
],
"name": "setSponsor",
tests/src/eth/collectionHelperAbi.jsondiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/collectionHelperAbi.json
@@ -0,0 +1,22 @@
+[
+ {
+ "inputs": [
+ { "internalType": "string", "name": "name", "type": "string" },
+ { "internalType": "string", "name": "description", "type": "string" },
+ { "internalType": "string", "name": "tokenPrefix", "type": "string" }
+ ],
+ "name": "create721Collection",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "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
@@ -20,11 +20,12 @@
import {expect} from 'chai';
import {getCreatedCollectionCount, getDetailedCollectionInfo} from '../util/helpers';
import {
- collectionHelper,
+ evmCollectionHelper,
collectionIdFromAddress,
collectionIdToAddress,
createEthAccount,
createEthAccountWithBalance,
+ evmCollection,
GAS_ARGS,
itWeb3,
normalizeAddress,
@@ -41,7 +42,7 @@
describe('Create collection from EVM', () => {
itWeb3('Create collection', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = collectionHelper(web3, owner);
+ const helper = evmCollectionHelper(web3, owner);
const collectionName = 'CollectionEVM';
const description = 'Some description';
const tokenPrefix = 'token prefix';
@@ -63,26 +64,27 @@
itWeb3('Set sponsorship', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = collectionHelper(web3, owner);
- let result = await helper.methods.create721Collection('Sponsor collection', '1', '1').send();
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ let result = await collectionHelper.methods.create721Collection('Sponsor collection', '1', '1').send();
const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
const sponsor = await createEthAccountWithBalance(api, web3);
- result = await helper.methods.setSponsor(collectionIdAddress, sponsor).send();
- let collection = (await getDetailedCollectionInfo(api, collectionId))!;
- expect(collection.sponsorship.isUnconfirmed).to.be.true;
- expect(collection.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
- await expect(helper.methods.confirmSponsorship(collectionIdAddress).call()).to.be.rejectedWith('Caller is not set as sponsor');
- const sponsorHelper = collectionHelper(web3, sponsor);
- await sponsorHelper.methods.confirmSponsorship(collectionIdAddress).send();
- collection = (await getDetailedCollectionInfo(api, collectionId))!;
- expect(collection.sponsorship.isConfirmed).to.be.true;
- expect(collection.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
+ const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+ result = await collectionEvm.methods.setSponsor(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');
+ const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
+ await sponsorCollection.methods.confirmSponsorship().send();
+ collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collectionSub.sponsorship.isConfirmed).to.be.true;
+ expect(collectionSub.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
});
itWeb3('Set limits', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = collectionHelper(web3, owner);
- const result = await helper.methods.create721Collection('Const collection', '5', '5').send();
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ const result = await collectionHelper.methods.create721Collection('Const collection', '5', '5').send();
const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
const limits = {
accountTokenOwnershipLimit: 1000,
@@ -97,23 +99,24 @@
};
const limitsJson = JSON.stringify(limits, null, 1);
- await helper.methods.setLimits(collectionIdAddress, limitsJson).send();
+ const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+ await collectionEvm.methods.setLimits(limitsJson).send();
- const collection = (await getDetailedCollectionInfo(api, collectionId))!;
- expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.eq(limits.accountTokenOwnershipLimit);
- expect(collection.limits.sponsoredDataSize.unwrap().toNumber()).to.be.eq(limits.sponsoredDataSize);
- expect(collection.limits.sponsoredDataRateLimit.unwrap().asBlocks.toNumber()).to.be.eq(limits.sponsoredDataRateLimit.Blocks);
- expect(collection.limits.tokenLimit.unwrap().toNumber()).to.be.eq(limits.tokenLimit);
- expect(collection.limits.sponsorTransferTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorTransferTimeout);
- expect(collection.limits.sponsorApproveTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorApproveTimeout);
- expect(collection.limits.ownerCanTransfer.toHuman()).to.be.eq(limits.ownerCanTransfer);
- expect(collection.limits.ownerCanDestroy.toHuman()).to.be.eq(limits.ownerCanDestroy);
- expect(collection.limits.transfersEnabled.toHuman()).to.be.eq(limits.transfersEnabled);
+ const collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collectionSub.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.eq(limits.accountTokenOwnershipLimit);
+ expect(collectionSub.limits.sponsoredDataSize.unwrap().toNumber()).to.be.eq(limits.sponsoredDataSize);
+ expect(collectionSub.limits.sponsoredDataRateLimit.unwrap().asBlocks.toNumber()).to.be.eq(limits.sponsoredDataRateLimit.Blocks);
+ expect(collectionSub.limits.tokenLimit.unwrap().toNumber()).to.be.eq(limits.tokenLimit);
+ expect(collectionSub.limits.sponsorTransferTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorTransferTimeout);
+ expect(collectionSub.limits.sponsorApproveTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorApproveTimeout);
+ expect(collectionSub.limits.ownerCanTransfer.toHuman()).to.be.eq(limits.ownerCanTransfer);
+ expect(collectionSub.limits.ownerCanDestroy.toHuman()).to.be.eq(limits.ownerCanDestroy);
+ expect(collectionSub.limits.transfersEnabled.toHuman()).to.be.eq(limits.transfersEnabled);
});
itWeb3('Check tokenURI', async ({web3, api}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = collectionHelper(web3, owner);
+ const helper = evmCollectionHelper(web3, owner);
let result = await helper.methods.create721Collection('Mint collection', '6', '6').send();
const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
const receiver = createEthAccount(web3);
@@ -154,7 +157,7 @@
describe('(!negative tests!) Create collection from EVM', () => {
itWeb3('(!negative test!) Create collection (bad lengths)', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = collectionHelper(web3, owner);
+ const helper = evmCollectionHelper(web3, owner);
{
const MAX_NAME_LENGHT = 64;
const collectionName = 'A'.repeat(MAX_NAME_LENGHT + 1);
@@ -188,7 +191,7 @@
itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {
const owner = await createEthAccount(web3);
- const helper = collectionHelper(web3, owner);
+ const helper = evmCollectionHelper(web3, owner);
const collectionName = 'A';
const description = 'A';
const tokenPrefix = 'A';
@@ -200,24 +203,24 @@
itWeb3('(!negative test!) Collection address (Contract is not an unique collection)', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = collectionHelper(web3, owner);
const collectionAddressWithBadPrefix = '0x00112233445566778899AABBCCDDEEFF00112233';
+ const collectionEvm = evmCollection(web3, owner, collectionAddressWithBadPrefix);
const EXPECTED_ERROR = 'Contract is not an unique collection';
{
const sponsor = await createEthAccountWithBalance(api, web3);
- await expect(helper.methods
- .setSponsor(collectionAddressWithBadPrefix, sponsor)
+ await expect(collectionEvm.methods
+ .setSponsor(sponsor)
.call()).to.be.rejectedWith(EXPECTED_ERROR);
- const sponsorHelper = collectionHelper(web3, sponsor);
- await expect(sponsorHelper.methods
- .confirmSponsorship(collectionAddressWithBadPrefix)
+ const sponsorCollection = evmCollection(web3, sponsor, collectionAddressWithBadPrefix);
+ await expect(sponsorCollection.methods
+ .confirmSponsorship()
.call()).to.be.rejectedWith(EXPECTED_ERROR);
}
{
const limits = '{"account_token_ownership_limit":1000}';
- await expect(helper.methods
- .setLimits(collectionAddressWithBadPrefix, limits)
+ await expect(collectionEvm.methods
+ .setLimits(limits)
.call()).to.be.rejectedWith(EXPECTED_ERROR);
}
});
@@ -225,38 +228,39 @@
itWeb3('(!negative test!) Check owner', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
const notOwner = await createEthAccount(web3);
- const helperFromOwner = collectionHelper(web3, owner);
- const helperFromNotOwner = collectionHelper(web3, notOwner);
- const result = await helperFromOwner.methods.create721Collection('A', 'A', 'A').send();
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ const result = await collectionHelper.methods.create721Collection('A', 'A', 'A').send();
const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+ const contractEvmFromNotOwner = evmCollection(web3, notOwner, collectionIdAddress);
const EXPECTED_ERROR = 'NoPermission';
{
const sponsor = await createEthAccountWithBalance(api, web3);
- await expect(helperFromNotOwner.methods
- .setSponsor(collectionIdAddress, sponsor)
+ await expect(contractEvmFromNotOwner.methods
+ .setSponsor(sponsor)
.call()).to.be.rejectedWith(EXPECTED_ERROR);
- const sponsorHelper = collectionHelper(web3, sponsor);
- await expect(sponsorHelper.methods
- .confirmSponsorship(collectionIdAddress)
+ const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
+ await expect(sponsorCollection.methods
+ .confirmSponsorship()
.call()).to.be.rejectedWith('Caller is not set as sponsor');
}
{
const limits = '{"account_token_ownership_limit":1000}';
- await expect(helperFromNotOwner.methods
- .setLimits(collectionIdAddress, limits)
+ await expect(contractEvmFromNotOwner.methods
+ .setLimits(limits)
.call()).to.be.rejectedWith(EXPECTED_ERROR);
}
});
itWeb3('(!negative test!) Set limits', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = collectionHelper(web3, owner);
- const result = await helper.methods.create721Collection('Schema collection', 'A', 'A').send();
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ const result = await collectionHelper.methods.create721Collection('Schema collection', 'A', 'A').send();
const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+ const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
const badJson = '{accountTokenOwnershipLimit: 1000}';
- await expect(helper.methods
- .setLimits(collectionIdAddress, badJson)
+ await expect(collectionEvm.methods
+ .setLimits(badJson)
.call()).to.be.rejectedWith('Parse JSON error:');
});
});
\ No newline at end of file
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 getBalance from '../../substrate/get-balance';33import waitNewBlocks from '../../substrate/wait-new-blocks';3435export const GAS_ARGS = {gas: 2500000};3637export enum SponsoringMode {38 Disabled = 0,39 Allowlisted = 1,40 Generous = 2,41}4243let web3Connected = false;44export async function usingWeb3<T>(cb: (web3: Web3) => Promise<T> | T): Promise<T> {45 if (web3Connected) throw new Error('do not nest usingWeb3 calls');46 web3Connected = true;4748 const provider = new Web3.providers.WebsocketProvider(config.substrateUrl);49 const web3 = new Web3(provider);5051 try {52 return await cb(web3);53 } finally {54 // provider.disconnect(3000, 'normal disconnect');55 provider.connection.close();56 web3Connected = false;57 }58}5960function encodeIntBE(v: number): number[] {61 if (v >= 0xffffffff || v < 0) throw new Error('id overflow');62 return [63 v >> 24,64 (v >> 16) & 0xff,65 (v >> 8) & 0xff,66 v & 0xff,67 ];68}6970export function collectionIdToAddress(collection: number): string {71 const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,72 ...encodeIntBE(collection),73 ]);74 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));75}76export function collectionIdFromAddress(address: string): number {77 if (!address.startsWith('0x'))78 throw 'address not starts with "0x"';79 if (address.length > 42)80 throw 'address length is more than 20 bytes';81 return Number('0x' + address.substring(address.length - 8));82}83 84export function normalizeAddress(address: string): string {85 return '0x' + address.substring(address.length - 40);86}8788export function tokenIdToAddress(collection: number, token: number): string {89 const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,90 ...encodeIntBE(collection),91 ...encodeIntBE(token),92 ]);93 return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));94}95export function tokenIdToCross(collection: number, token: number): CrossAccountId {96 return {97 Ethereum: tokenIdToAddress(collection, token),98 };99100export function createEthAccount(web3: Web3) {101 const account = web3.eth.accounts.create();102 web3.eth.accounts.wallet.add(account.privateKey);103 return account.address;104}105106export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {107 const alice = privateKey('//Alice');108 const account = createEthAccount(web3);109 await transferBalanceToEth(api, alice, account);110111 return account;112}113114export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {115 const tx = api.tx.balances.transfer(evmToAddress(target), amount);116 const events = await submitTransactionAsync(source, tx);117 const result = getGenericResult(events);118 expect(result.success).to.be.true;119}120121export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {122 let i: any = it;123 if (opts.only) i = i.only;124 else if (opts.skip) i = i.skip;125 i(name, async () => {126 await usingApi(async api => {127 await usingWeb3(async web3 => {128 await cb({api, web3});129 });130 });131 });132}133itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});134itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});135136export async function generateSubstrateEthPair(web3: Web3) {137 const account = web3.eth.accounts.create();138 evmToAddress(account.address);139}140141type NormalizedEvent = {142 address: string,143 event: string,144 args: { [key: string]: string }145};146147export function normalizeEvents(events: any): NormalizedEvent[] {148 const output = [];149 for (const key of Object.keys(events)) {150 if (key.match(/^[0-9]+$/)) {151 output.push(events[key]);152 } else if (Array.isArray(events[key])) {153 output.push(...events[key]);154 } else {155 output.push(events[key]);156 }157 }158 output.sort((a, b) => a.logIndex - b.logIndex);159 return output.map(({address, event, returnValues}) => {160 const args: { [key: string]: string } = {};161 for (const key of Object.keys(returnValues)) {162 if (!key.match(/^[0-9]+$/)) {163 args[key] = returnValues[key];164 }165 }166 return {167 address,168 event,169 args,170 };171 });172}173174export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {175 const out: any = [];176 contract.events.allEvents((_: any, event: any) => {177 out.push(event);178 });179 await action();180 return normalizeEvents(out);181}182183export function subToEthLowercase(eth: string): string {184 const bytes = addressToEvm(eth);185 return '0x' + Buffer.from(bytes).toString('hex');186}187188export function subToEth(eth: string): string {189 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));190}191192export function compileContract(name: string, src: string) {193 const out = JSON.parse(solc.compile(JSON.stringify({194 language: 'Solidity',195 sources: {196 [`${name}.sol`]: {197 content: `198 // SPDX-License-Identifier: UNLICENSED199 pragma solidity ^0.8.6;200201 ${src}202 `,203 },204 },205 settings: {206 outputSelection: {207 '*': {208 '*': ['*'],209 },210 },211 },212 }))).contracts[`${name}.sol`][name];213214 return {215 abi: out.abi,216 object: '0x' + out.evm.bytecode.object,217 };218}219220export async function deployFlipper(web3: Web3, deployer: string) {221 const compiled = compileContract('Flipper', `222 contract Flipper {223 bool value = false;224 function flip() public {225 value = !value;226 }227 function getValue() public view returns (bool) {228 return value;229 }230 }231 `);232 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {233 data: compiled.object,234 from: deployer,235 ...GAS_ARGS,236 });237 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});238239 return flipper;240}241242export async function deployCollector(web3: Web3, deployer: string) {243 const compiled = compileContract('Collector', `244 contract Collector {245 uint256 collected;246 fallback() external payable {247 giveMoney();248 }249 function giveMoney() public payable {250 collected += msg.value;251 }252 function getCollected() public view returns (uint256) {253 return collected;254 }255 function getUnaccounted() public view returns (uint256) {256 return address(this).balance - collected;257 }258259 function withdraw(address payable target) public {260 target.transfer(collected);261 collected = 0;262 }263 }264 `);265 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {266 data: compiled.object,267 from: deployer,268 ...GAS_ARGS,269 });270 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});271272 return collector;273}274275/** 276 * pallet evm_contract_helpers277 * @param web3 278 * @param caller - eth address279 * @returns 280 */281export function contractHelpers(web3: Web3, caller: string) {282 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});283}284285/** 286 * pallet evm_collection287 * @param web3 288 * @param caller - eth address289 * @returns 290 */291export function collectionHelper(web3: Web3, caller: string) {292 return new web3.eth.Contract(collectionAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});293}294295/**296 * Execute ethereum method call using substrate account297 * @param to target contract298 * @param mkTx - closure, receiving `contract.methods`, and returning method call,299 * to be used as following (assuming `to` = erc20 contract):300 * `m => m.transfer(to, amount)`301 *302 * # Example303 * ```ts304 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));305 * ```306 */307export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {308 const tx = api.tx.evm.call(309 subToEth(from.address),310 to.options.address,311 mkTx(to.methods).encodeABI(),312 value,313 GAS_ARGS.gas,314 await web3.eth.getGasPrice(),315 null,316 null,317 [],318 );319 const events = await submitTransactionAsync(from, tx);320 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;321}322323export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {324 return (await getBalance(api, [evmToAddress(address)]))[0];325}326327/**328 * Measure how much gas given closure consumes329 *330 * @param user which user balance will be checked331 */332export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {333 const before = await ethBalanceViaSub(api, user);334335 await call();336337 // In dev mode, the transaction might not finish processing in time338 await waitNewBlocks(api, 1);339 const after = await ethBalanceViaSub(api, user);340341 // Can't use .to.be.less, because chai doesn't supports bigint342 expect(after < before).to.be.true;343344 return before - after;345}346347type ElementOf<A> = A extends readonly (infer T)[] ? T : never;348// I want a fancier api, not a memory efficiency349export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {350 if(args.length === 0) {351 yield internalRest as any;352 return;353 }354 for(const value of args[0]) {355 yield* cartesian([...internalRest, value], ...args.slice(1)) as any;356 }357}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 '../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 };100101export function createEthAccount(web3: Web3) {102 const account = web3.eth.accounts.create();103 web3.eth.accounts.wallet.add(account.privateKey);104 return account.address;105}106107export async function createEthAccountWithBalance(api: ApiPromise, web3: Web3) {108 const alice = privateKey('//Alice');109 const account = createEthAccount(web3);110 await transferBalanceToEth(api, alice, account);111112 return account;113}114115export async function transferBalanceToEth(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {116 const tx = api.tx.balances.transfer(evmToAddress(target), amount);117 const events = await submitTransactionAsync(source, tx);118 const result = getGenericResult(events);119 expect(result.success).to.be.true;120}121122export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any, opts: { only?: boolean, skip?: boolean } = {}) {123 let i: any = it;124 if (opts.only) i = i.only;125 else if (opts.skip) i = i.skip;126 i(name, async () => {127 await usingApi(async api => {128 await usingWeb3(async web3 => {129 await cb({api, web3});130 });131 });132 });133}134itWeb3.only = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {only: true});135itWeb3.skip = (name: string, cb: (apis: { web3: Web3, api: ApiPromise }) => any) => itWeb3(name, cb, {skip: true});136137export async function generateSubstrateEthPair(web3: Web3) {138 const account = web3.eth.accounts.create();139 evmToAddress(account.address);140}141142type NormalizedEvent = {143 address: string,144 event: string,145 args: { [key: string]: string }146};147148export function normalizeEvents(events: any): NormalizedEvent[] {149 const output = [];150 for (const key of Object.keys(events)) {151 if (key.match(/^[0-9]+$/)) {152 output.push(events[key]);153 } else if (Array.isArray(events[key])) {154 output.push(...events[key]);155 } else {156 output.push(events[key]);157 }158 }159 output.sort((a, b) => a.logIndex - b.logIndex);160 return output.map(({address, event, returnValues}) => {161 const args: { [key: string]: string } = {};162 for (const key of Object.keys(returnValues)) {163 if (!key.match(/^[0-9]+$/)) {164 args[key] = returnValues[key];165 }166 }167 return {168 address,169 event,170 args,171 };172 });173}174175export async function recordEvents(contract: any, action: () => Promise<void>): Promise<NormalizedEvent[]> {176 const out: any = [];177 contract.events.allEvents((_: any, event: any) => {178 out.push(event);179 });180 await action();181 return normalizeEvents(out);182}183184export function subToEthLowercase(eth: string): string {185 const bytes = addressToEvm(eth);186 return '0x' + Buffer.from(bytes).toString('hex');187}188189export function subToEth(eth: string): string {190 return Web3.utils.toChecksumAddress(subToEthLowercase(eth));191}192193export function compileContract(name: string, src: string) {194 const out = JSON.parse(solc.compile(JSON.stringify({195 language: 'Solidity',196 sources: {197 [`${name}.sol`]: {198 content: `199 // SPDX-License-Identifier: UNLICENSED200 pragma solidity ^0.8.6;201202 ${src}203 `,204 },205 },206 settings: {207 outputSelection: {208 '*': {209 '*': ['*'],210 },211 },212 },213 }))).contracts[`${name}.sol`][name];214215 return {216 abi: out.abi,217 object: '0x' + out.evm.bytecode.object,218 };219}220221export async function deployFlipper(web3: Web3, deployer: string) {222 const compiled = compileContract('Flipper', `223 contract Flipper {224 bool value = false;225 function flip() public {226 value = !value;227 }228 function getValue() public view returns (bool) {229 return value;230 }231 }232 `);233 const flipperContract = new web3.eth.Contract(compiled.abi, undefined, {234 data: compiled.object,235 from: deployer,236 ...GAS_ARGS,237 });238 const flipper = await flipperContract.deploy({data: compiled.object}).send({from: deployer});239240 return flipper;241}242243export async function deployCollector(web3: Web3, deployer: string) {244 const compiled = compileContract('Collector', `245 contract Collector {246 uint256 collected;247 fallback() external payable {248 giveMoney();249 }250 function giveMoney() public payable {251 collected += msg.value;252 }253 function getCollected() public view returns (uint256) {254 return collected;255 }256 function getUnaccounted() public view returns (uint256) {257 return address(this).balance - collected;258 }259260 function withdraw(address payable target) public {261 target.transfer(collected);262 collected = 0;263 }264 }265 `);266 const collectorContract = new web3.eth.Contract(compiled.abi, undefined, {267 data: compiled.object,268 from: deployer,269 ...GAS_ARGS,270 });271 const collector = await collectorContract.deploy({data: compiled.object}).send({from: deployer});272273 return collector;274}275276/** 277 * pallet evm_contract_helpers278 * @param web3 279 * @param caller - eth address280 * @returns 281 */282export function contractHelpers(web3: Web3, caller: string) {283 return new web3.eth.Contract(contractHelpersAbi as any, '0x842899ECF380553E8a4de75bF534cdf6fBF64049', {from: caller, ...GAS_ARGS});284}285286/** 287 * evm collection helper288 * @param web3 289 * @param caller - eth address290 * @returns 291 */292export function evmCollectionHelper(web3: Web3, caller: string) {293 return new web3.eth.Contract(collectionHelperAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});294}295296/** 297 * evm collection298 * @param web3 299 * @param caller - eth address300 * @returns 301 */302export function evmCollection(web3: Web3, caller: string, collection: string) {303 return new web3.eth.Contract(collectionAbi as any, collection, {from: caller, ...GAS_ARGS});304}305306/**307 * Execute ethereum method call using substrate account308 * @param to target contract309 * @param mkTx - closure, receiving `contract.methods`, and returning method call,310 * to be used as following (assuming `to` = erc20 contract):311 * `m => m.transfer(to, amount)`312 *313 * # Example314 * ```ts315 * executeEthTxOnSub(api, alice, erc20Contract, m => m.transfer(target, amount));316 * ```317 */318export async function executeEthTxOnSub(web3: Web3, api: ApiPromise, from: IKeyringPair, to: any, mkTx: (methods: any) => any, {value = 0}: {value?: bigint | number} = { }) {319 const tx = api.tx.evm.call(320 subToEth(from.address),321 to.options.address,322 mkTx(to.methods).encodeABI(),323 value,324 GAS_ARGS.gas,325 await web3.eth.getGasPrice(),326 null,327 null,328 [],329 );330 const events = await submitTransactionAsync(from, tx);331 expect(events.some(({event: {section, method}}) => section == 'evm' && method == 'Executed')).to.be.true;332}333334export async function ethBalanceViaSub(api: ApiPromise, address: string): Promise<bigint> {335 return (await getBalance(api, [evmToAddress(address)]))[0];336}337338/**339 * Measure how much gas given closure consumes340 *341 * @param user which user balance will be checked342 */343export async function recordEthFee(api: ApiPromise, user: string, call: () => Promise<any>): Promise<bigint> {344 const before = await ethBalanceViaSub(api, user);345346 await call();347348 // In dev mode, the transaction might not finish processing in time349 await waitNewBlocks(api, 1);350 const after = await ethBalanceViaSub(api, user);351352 // Can't use .to.be.less, because chai doesn't supports bigint353 expect(after < before).to.be.true;354355 return before - after;356}357358type ElementOf<A> = A extends readonly (infer T)[] ? T : never;359// I want a fancier api, not a memory efficiency360export function* cartesian<T extends Array<Array<any>>, R extends Array<any>>(internalRest: [...R], ...args: [...T]): Generator<[...R, ...{[K in keyof T]: ElementOf<T[K]>}]> {361 if(args.length === 0) {362 yield internalRest as any;363 return;364 }365 for(const value of args[0]) {366 yield* cartesian([...internalRest, value], ...args.slice(1)) as any;367 }368}tests/src/interfaces/unique/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/unique/types.ts
+++ b/tests/src/interfaces/unique/types.ts
@@ -6,9 +6,6 @@
import type { AccountId32, Call, H160, H256, MultiAddress, Perbill, Permill } from '@polkadot/types/interfaces/runtime';
import type { Event } from '@polkadot/types/interfaces/system';
-/** @name BTreeSet */
-export interface BTreeSet extends BTreeSet<Bytes> {}
-
/** @name CumulusPalletDmpQueueCall */
export interface CumulusPalletDmpQueueCall extends Enum {
readonly isServiceOverweight: boolean;