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.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.8//9// 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/>.1617import nonFungibleAbi from './nonFungibleAbi.json';18import {ApiPromise} from '@polkadot/api';19import {evmToAddress} from '@polkadot/util-crypto';20import {expect} from 'chai';21import {getCreatedCollectionCount, getDetailedCollectionInfo} from '../util/helpers';22import {23 collectionHelper,24 collectionIdFromAddress,25 collectionIdToAddress,26 createEthAccount,27 createEthAccountWithBalance,28 GAS_ARGS,29 itWeb3,30 normalizeAddress,31 normalizeEvents,32} from './util/helpers';3334async function getCollectionAddressFromResult(api: ApiPromise, result: any) {35 const collectionIdAddress = normalizeAddress(result.events[0].raw.topics[2]);36 const collectionId = collectionIdFromAddress(collectionIdAddress); 37 const collection = (await getDetailedCollectionInfo(api, collectionId))!;38 return {collectionIdAddress, collectionId, collection};39}4041describe('Create collection from EVM', () => {42 itWeb3('Create collection', async ({api, web3}) => {43 const owner = await createEthAccountWithBalance(api, web3);44 const helper = collectionHelper(web3, owner);45 const collectionName = 'CollectionEVM';46 const description = 'Some description';47 const tokenPrefix = 'token prefix';48 49 const collectionCountBefore = await getCreatedCollectionCount(api);50 const result = await helper.methods51 .create721Collection(collectionName, description, tokenPrefix)52 .send();53 const collectionCountAfter = await getCreatedCollectionCount(api);54 55 const {collectionId, collection} = await getCollectionAddressFromResult(api, result);56 expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);57 expect(collectionId).to.be.eq(collectionCountAfter);58 expect(collection.name.map(v => String.fromCharCode(v.toNumber())).join('')).to.be.eq(collectionName);59 expect(collection.description.map(v => String.fromCharCode(v.toNumber())).join('')).to.be.eq(description);60 expect(collection.tokenPrefix.toHuman()).to.be.eq(tokenPrefix);61 expect(collection.schemaVersion.type).to.be.eq('ImageURL');62 });63 64 itWeb3('Set sponsorship', async ({api, web3}) => {65 const owner = await createEthAccountWithBalance(api, web3);66 const helper = collectionHelper(web3, owner);67 let result = await helper.methods.create721Collection('Sponsor collection', '1', '1').send();68 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);69 const sponsor = await createEthAccountWithBalance(api, web3);70 result = await helper.methods.setSponsor(collectionIdAddress, sponsor).send();71 let collection = (await getDetailedCollectionInfo(api, collectionId))!;72 expect(collection.sponsorship.isUnconfirmed).to.be.true;73 expect(collection.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));74 await expect(helper.methods.confirmSponsorship(collectionIdAddress).call()).to.be.rejectedWith('Caller is not set as sponsor');75 const sponsorHelper = collectionHelper(web3, sponsor);76 await sponsorHelper.methods.confirmSponsorship(collectionIdAddress).send();77 collection = (await getDetailedCollectionInfo(api, collectionId))!;78 expect(collection.sponsorship.isConfirmed).to.be.true;79 expect(collection.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));80 });8182 itWeb3('Set limits', async ({api, web3}) => {83 const owner = await createEthAccountWithBalance(api, web3);84 const helper = collectionHelper(web3, owner);85 const result = await helper.methods.create721Collection('Const collection', '5', '5').send();86 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);87 const limits = {88 accountTokenOwnershipLimit: 1000,89 sponsoredDataSize: 1024,90 sponsoredDataRateLimit: {Blocks: 30},91 tokenLimit: 1000000,92 sponsorTransferTimeout: 6,93 sponsorApproveTimeout: 6,94 ownerCanTransfer: false,95 ownerCanDestroy: false,96 transfersEnabled: false,97 };9899 const limitsJson = JSON.stringify(limits, null, 1);100 await helper.methods.setLimits(collectionIdAddress, limitsJson).send();101 102 const collection = (await getDetailedCollectionInfo(api, collectionId))!;103 expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.eq(limits.accountTokenOwnershipLimit);104 expect(collection.limits.sponsoredDataSize.unwrap().toNumber()).to.be.eq(limits.sponsoredDataSize);105 expect(collection.limits.sponsoredDataRateLimit.unwrap().asBlocks.toNumber()).to.be.eq(limits.sponsoredDataRateLimit.Blocks);106 expect(collection.limits.tokenLimit.unwrap().toNumber()).to.be.eq(limits.tokenLimit);107 expect(collection.limits.sponsorTransferTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorTransferTimeout);108 expect(collection.limits.sponsorApproveTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorApproveTimeout);109 expect(collection.limits.ownerCanTransfer.toHuman()).to.be.eq(limits.ownerCanTransfer);110 expect(collection.limits.ownerCanDestroy.toHuman()).to.be.eq(limits.ownerCanDestroy);111 expect(collection.limits.transfersEnabled.toHuman()).to.be.eq(limits.transfersEnabled);112 });113114 itWeb3('Check tokenURI', async ({web3, api}) => {115 const owner = await createEthAccountWithBalance(api, web3);116 const helper = collectionHelper(web3, owner);117 let result = await helper.methods.create721Collection('Mint collection', '6', '6').send();118 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);119 const receiver = createEthAccount(web3);120 const contract = new web3.eth.Contract(nonFungibleAbi as any, collectionIdAddress, {from: owner, ...GAS_ARGS});121 const nextTokenId = await contract.methods.nextTokenId().call();122123 expect(nextTokenId).to.be.equal('1');124 result = await contract.methods.mintWithTokenURI(125 receiver,126 nextTokenId,127 'Test URI',128 ).send();129130 const events = normalizeEvents(result.events);131 const address = collectionIdToAddress(collectionId);132133 expect(events).to.be.deep.equal([134 {135 address,136 event: 'Transfer',137 args: {138 from: '0x0000000000000000000000000000000000000000',139 to: receiver,140 tokenId: nextTokenId,141 },142 },143 ]);144145 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');146147 // TODO: this wont work right now, need release 919000 first148 // await helper.methods.setOffchainSchema(collectionIdAddress, 'https://offchain-service.local/token-info/{id}').send();149 // const tokenUri = await contract.methods.tokenURI(nextTokenId).call();150 // expect(tokenUri).to.be.equal(`https://offchain-service.local/token-info/${nextTokenId}`);151 });152});153154describe('(!negative tests!) Create collection from EVM', () => {155 itWeb3('(!negative test!) Create collection (bad lengths)', async ({api, web3}) => {156 const owner = await createEthAccountWithBalance(api, web3);157 const helper = collectionHelper(web3, owner);158 {159 const MAX_NAME_LENGHT = 64;160 const collectionName = 'A'.repeat(MAX_NAME_LENGHT + 1);161 const description = 'A';162 const tokenPrefix = 'A';163 164 await expect(helper.methods165 .create721Collection(collectionName, description, tokenPrefix)166 .call()).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGHT);167 168 }169 { 170 const MAX_DESCRIPTION_LENGHT = 256;171 const collectionName = 'A';172 const description = 'A'.repeat(MAX_DESCRIPTION_LENGHT + 1);173 const tokenPrefix = 'A';174 await expect(helper.methods175 .create721Collection(collectionName, description, tokenPrefix)176 .call()).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGHT);177 }178 { 179 const MAX_TOKEN_PREFIX_LENGHT = 16;180 const collectionName = 'A';181 const description = 'A';182 const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGHT + 1);183 await expect(helper.methods184 .create721Collection(collectionName, description, tokenPrefix)185 .call()).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGHT);186 }187 });188 189 itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {190 const owner = await createEthAccount(web3);191 const helper = collectionHelper(web3, owner);192 const collectionName = 'A';193 const description = 'A';194 const tokenPrefix = 'A';195 196 await expect(helper.methods197 .create721Collection(collectionName, description, tokenPrefix)198 .call()).to.be.rejectedWith('NotSufficientFounds');199 });200201 itWeb3('(!negative test!) Collection address (Contract is not an unique collection)', async ({api, web3}) => {202 const owner = await createEthAccountWithBalance(api, web3);203 const helper = collectionHelper(web3, owner);204 const collectionAddressWithBadPrefix = '0x00112233445566778899AABBCCDDEEFF00112233';205 const EXPECTED_ERROR = 'Contract is not an unique collection';206 {207 const sponsor = await createEthAccountWithBalance(api, web3);208 await expect(helper.methods209 .setSponsor(collectionAddressWithBadPrefix, sponsor)210 .call()).to.be.rejectedWith(EXPECTED_ERROR);211 212 const sponsorHelper = collectionHelper(web3, sponsor);213 await expect(sponsorHelper.methods214 .confirmSponsorship(collectionAddressWithBadPrefix)215 .call()).to.be.rejectedWith(EXPECTED_ERROR);216 }217 {218 const limits = '{"account_token_ownership_limit":1000}';219 await expect(helper.methods220 .setLimits(collectionAddressWithBadPrefix, limits)221 .call()).to.be.rejectedWith(EXPECTED_ERROR);222 }223 });224225 itWeb3('(!negative test!) Check owner', async ({api, web3}) => {226 const owner = await createEthAccountWithBalance(api, web3);227 const notOwner = await createEthAccount(web3);228 const helperFromOwner = collectionHelper(web3, owner);229 const helperFromNotOwner = collectionHelper(web3, notOwner);230 const result = await helperFromOwner.methods.create721Collection('A', 'A', 'A').send();231 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);232 const EXPECTED_ERROR = 'NoPermission';233 {234 const sponsor = await createEthAccountWithBalance(api, web3);235 await expect(helperFromNotOwner.methods236 .setSponsor(collectionIdAddress, sponsor)237 .call()).to.be.rejectedWith(EXPECTED_ERROR);238 239 const sponsorHelper = collectionHelper(web3, sponsor);240 await expect(sponsorHelper.methods241 .confirmSponsorship(collectionIdAddress)242 .call()).to.be.rejectedWith('Caller is not set as sponsor');243 }244 {245 const limits = '{"account_token_ownership_limit":1000}';246 await expect(helperFromNotOwner.methods247 .setLimits(collectionIdAddress, limits)248 .call()).to.be.rejectedWith(EXPECTED_ERROR);249 }250 });251252 itWeb3('(!negative test!) Set limits', async ({api, web3}) => {253 const owner = await createEthAccountWithBalance(api, web3);254 const helper = collectionHelper(web3, owner);255 const result = await helper.methods.create721Collection('Schema collection', 'A', 'A').send();256 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);257 const badJson = '{accountTokenOwnershipLimit: 1000}';258 await expect(helper.methods259 .setLimits(collectionIdAddress, badJson)260 .call()).to.be.rejectedWith('Parse JSON error:');261 });262});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.8//9// 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/>.1617import nonFungibleAbi from './nonFungibleAbi.json';18import {ApiPromise} from '@polkadot/api';19import {evmToAddress} from '@polkadot/util-crypto';20import {expect} from 'chai';21import {getCreatedCollectionCount, getDetailedCollectionInfo} from '../util/helpers';22import {23 evmCollectionHelper,24 collectionIdFromAddress,25 collectionIdToAddress,26 createEthAccount,27 createEthAccountWithBalance,28 evmCollection,29 GAS_ARGS,30 itWeb3,31 normalizeAddress,32 normalizeEvents,33} from './util/helpers';3435async function getCollectionAddressFromResult(api: ApiPromise, result: any) {36 const collectionIdAddress = normalizeAddress(result.events[0].raw.topics[2]);37 const collectionId = collectionIdFromAddress(collectionIdAddress); 38 const collection = (await getDetailedCollectionInfo(api, collectionId))!;39 return {collectionIdAddress, collectionId, collection};40}4142describe('Create collection from EVM', () => {43 itWeb3('Create collection', async ({api, web3}) => {44 const owner = await createEthAccountWithBalance(api, web3);45 const helper = evmCollectionHelper(web3, owner);46 const collectionName = 'CollectionEVM';47 const description = 'Some description';48 const tokenPrefix = 'token prefix';49 50 const collectionCountBefore = await getCreatedCollectionCount(api);51 const result = await helper.methods52 .create721Collection(collectionName, description, tokenPrefix)53 .send();54 const collectionCountAfter = await getCreatedCollectionCount(api);55 56 const {collectionId, collection} = await getCollectionAddressFromResult(api, result);57 expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);58 expect(collectionId).to.be.eq(collectionCountAfter);59 expect(collection.name.map(v => String.fromCharCode(v.toNumber())).join('')).to.be.eq(collectionName);60 expect(collection.description.map(v => String.fromCharCode(v.toNumber())).join('')).to.be.eq(description);61 expect(collection.tokenPrefix.toHuman()).to.be.eq(tokenPrefix);62 expect(collection.schemaVersion.type).to.be.eq('ImageURL');63 });64 65 itWeb3('Set sponsorship', async ({api, web3}) => {66 const owner = await createEthAccountWithBalance(api, web3);67 const collectionHelper = evmCollectionHelper(web3, owner);68 let result = await collectionHelper.methods.create721Collection('Sponsor collection', '1', '1').send();69 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);70 const sponsor = await createEthAccountWithBalance(api, web3);71 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);72 result = await collectionEvm.methods.setSponsor(sponsor).send();73 let collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;74 expect(collectionSub.sponsorship.isUnconfirmed).to.be.true;75 expect(collectionSub.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));76 await expect(collectionEvm.methods.confirmSponsorship().call()).to.be.rejectedWith('Caller is not set as sponsor');77 const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);78 await sponsorCollection.methods.confirmSponsorship().send();79 collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;80 expect(collectionSub.sponsorship.isConfirmed).to.be.true;81 expect(collectionSub.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));82 });8384 itWeb3('Set limits', async ({api, web3}) => {85 const owner = await createEthAccountWithBalance(api, web3);86 const collectionHelper = evmCollectionHelper(web3, owner);87 const result = await collectionHelper.methods.create721Collection('Const collection', '5', '5').send();88 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);89 const limits = {90 accountTokenOwnershipLimit: 1000,91 sponsoredDataSize: 1024,92 sponsoredDataRateLimit: {Blocks: 30},93 tokenLimit: 1000000,94 sponsorTransferTimeout: 6,95 sponsorApproveTimeout: 6,96 ownerCanTransfer: false,97 ownerCanDestroy: false,98 transfersEnabled: false,99 };100101 const limitsJson = JSON.stringify(limits, null, 1);102 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);103 await collectionEvm.methods.setLimits(limitsJson).send();104 105 const collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;106 expect(collectionSub.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.eq(limits.accountTokenOwnershipLimit);107 expect(collectionSub.limits.sponsoredDataSize.unwrap().toNumber()).to.be.eq(limits.sponsoredDataSize);108 expect(collectionSub.limits.sponsoredDataRateLimit.unwrap().asBlocks.toNumber()).to.be.eq(limits.sponsoredDataRateLimit.Blocks);109 expect(collectionSub.limits.tokenLimit.unwrap().toNumber()).to.be.eq(limits.tokenLimit);110 expect(collectionSub.limits.sponsorTransferTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorTransferTimeout);111 expect(collectionSub.limits.sponsorApproveTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorApproveTimeout);112 expect(collectionSub.limits.ownerCanTransfer.toHuman()).to.be.eq(limits.ownerCanTransfer);113 expect(collectionSub.limits.ownerCanDestroy.toHuman()).to.be.eq(limits.ownerCanDestroy);114 expect(collectionSub.limits.transfersEnabled.toHuman()).to.be.eq(limits.transfersEnabled);115 });116117 itWeb3('Check tokenURI', async ({web3, api}) => {118 const owner = await createEthAccountWithBalance(api, web3);119 const helper = evmCollectionHelper(web3, owner);120 let result = await helper.methods.create721Collection('Mint collection', '6', '6').send();121 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);122 const receiver = createEthAccount(web3);123 const contract = new web3.eth.Contract(nonFungibleAbi as any, collectionIdAddress, {from: owner, ...GAS_ARGS});124 const nextTokenId = await contract.methods.nextTokenId().call();125126 expect(nextTokenId).to.be.equal('1');127 result = await contract.methods.mintWithTokenURI(128 receiver,129 nextTokenId,130 'Test URI',131 ).send();132133 const events = normalizeEvents(result.events);134 const address = collectionIdToAddress(collectionId);135136 expect(events).to.be.deep.equal([137 {138 address,139 event: 'Transfer',140 args: {141 from: '0x0000000000000000000000000000000000000000',142 to: receiver,143 tokenId: nextTokenId,144 },145 },146 ]);147148 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');149150 // TODO: this wont work right now, need release 919000 first151 // await helper.methods.setOffchainSchema(collectionIdAddress, 'https://offchain-service.local/token-info/{id}').send();152 // const tokenUri = await contract.methods.tokenURI(nextTokenId).call();153 // expect(tokenUri).to.be.equal(`https://offchain-service.local/token-info/${nextTokenId}`);154 });155});156157describe('(!negative tests!) Create collection from EVM', () => {158 itWeb3('(!negative test!) Create collection (bad lengths)', async ({api, web3}) => {159 const owner = await createEthAccountWithBalance(api, web3);160 const helper = evmCollectionHelper(web3, owner);161 {162 const MAX_NAME_LENGHT = 64;163 const collectionName = 'A'.repeat(MAX_NAME_LENGHT + 1);164 const description = 'A';165 const tokenPrefix = 'A';166 167 await expect(helper.methods168 .create721Collection(collectionName, description, tokenPrefix)169 .call()).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGHT);170 171 }172 { 173 const MAX_DESCRIPTION_LENGHT = 256;174 const collectionName = 'A';175 const description = 'A'.repeat(MAX_DESCRIPTION_LENGHT + 1);176 const tokenPrefix = 'A';177 await expect(helper.methods178 .create721Collection(collectionName, description, tokenPrefix)179 .call()).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGHT);180 }181 { 182 const MAX_TOKEN_PREFIX_LENGHT = 16;183 const collectionName = 'A';184 const description = 'A';185 const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGHT + 1);186 await expect(helper.methods187 .create721Collection(collectionName, description, tokenPrefix)188 .call()).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGHT);189 }190 });191 192 itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {193 const owner = await createEthAccount(web3);194 const helper = evmCollectionHelper(web3, owner);195 const collectionName = 'A';196 const description = 'A';197 const tokenPrefix = 'A';198 199 await expect(helper.methods200 .create721Collection(collectionName, description, tokenPrefix)201 .call()).to.be.rejectedWith('NotSufficientFounds');202 });203204 itWeb3('(!negative test!) Collection address (Contract is not an unique collection)', async ({api, web3}) => {205 const owner = await createEthAccountWithBalance(api, web3);206 const collectionAddressWithBadPrefix = '0x00112233445566778899AABBCCDDEEFF00112233';207 const collectionEvm = evmCollection(web3, owner, collectionAddressWithBadPrefix);208 const EXPECTED_ERROR = 'Contract is not an unique collection';209 {210 const sponsor = await createEthAccountWithBalance(api, web3);211 await expect(collectionEvm.methods212 .setSponsor(sponsor)213 .call()).to.be.rejectedWith(EXPECTED_ERROR);214 215 const sponsorCollection = evmCollection(web3, sponsor, collectionAddressWithBadPrefix);216 await expect(sponsorCollection.methods217 .confirmSponsorship()218 .call()).to.be.rejectedWith(EXPECTED_ERROR);219 }220 {221 const limits = '{"account_token_ownership_limit":1000}';222 await expect(collectionEvm.methods223 .setLimits(limits)224 .call()).to.be.rejectedWith(EXPECTED_ERROR);225 }226 });227228 itWeb3('(!negative test!) Check owner', async ({api, web3}) => {229 const owner = await createEthAccountWithBalance(api, web3);230 const notOwner = await createEthAccount(web3);231 const collectionHelper = evmCollectionHelper(web3, owner);232 const result = await collectionHelper.methods.create721Collection('A', 'A', 'A').send();233 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);234 const contractEvmFromNotOwner = evmCollection(web3, notOwner, collectionIdAddress);235 const EXPECTED_ERROR = 'NoPermission';236 {237 const sponsor = await createEthAccountWithBalance(api, web3);238 await expect(contractEvmFromNotOwner.methods239 .setSponsor(sponsor)240 .call()).to.be.rejectedWith(EXPECTED_ERROR);241 242 const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);243 await expect(sponsorCollection.methods244 .confirmSponsorship()245 .call()).to.be.rejectedWith('Caller is not set as sponsor');246 }247 {248 const limits = '{"account_token_ownership_limit":1000}';249 await expect(contractEvmFromNotOwner.methods250 .setLimits(limits)251 .call()).to.be.rejectedWith(EXPECTED_ERROR);252 }253 });254255 itWeb3('(!negative test!) Set limits', async ({api, web3}) => {256 const owner = await createEthAccountWithBalance(api, web3);257 const collectionHelper = evmCollectionHelper(web3, owner);258 const result = await collectionHelper.methods.create721Collection('Schema collection', 'A', 'A').send();259 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);260 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);261 const badJson = '{accountTokenOwnershipLimit: 1000}';262 await expect(collectionEvm.methods263 .setLimits(badJson)264 .call()).to.be.rejectedWith('Parse JSON error:');265 });266});tests/src/eth/util/helpers.tsdiffbeforeafterboth--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -29,6 +29,7 @@
import privateKey from '../../substrate/privateKey';
import contractHelpersAbi from './contractHelpersAbi.json';
import collectionAbi from '../collectionAbi.json';
+import collectionHelperAbi from '../collectionHelperAbi.json';
import getBalance from '../../substrate/get-balance';
import waitNewBlocks from '../../substrate/wait-new-blocks';
@@ -283,13 +284,23 @@
}
/**
- * pallet evm_collection
+ * evm collection helper
* @param web3
* @param caller - eth address
* @returns
*/
-export function collectionHelper(web3: Web3, caller: string) {
- return new web3.eth.Contract(collectionAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});
+export function evmCollectionHelper(web3: Web3, caller: string) {
+ return new web3.eth.Contract(collectionHelperAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});
+}
+
+/**
+ * evm collection
+ * @param web3
+ * @param caller - eth address
+ * @returns
+ */
+export function evmCollection(web3: Web3, caller: string, collection: string) {
+ return new web3.eth.Contract(collectionAbi as any, collection, {from: caller, ...GAS_ARGS});
}
/**
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;