git.delta.rocks / unique-network / refs/commits / 0c9dfc515d68

difftreelog

CORE-302 Implement methods for setup collection.

Trubnikov Sergey2022-04-21parent: #d7a043d.patch.diff
in: master

8 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -115,7 +115,7 @@
 		})
 	}
 
-	pub fn new_with_recorder(id: CollectionId, recorder: Rc<SubstrateRecorder<T>>) -> Option<Self> {
+	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {
 		<CollectionById<T>>::get(id).map(|collection| Self {
 			id,
 			collection,
@@ -153,6 +153,15 @@
 	pub fn set_sponsor(&mut self, sponsor: T::AccountId) {
 		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);
 	}
+	
+	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> bool {
+		if self.collection.sponsorship.pending_sponsor() != Some(sender) {
+			return false;
+		};
+
+		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());
+		true
+	}
 }
 impl<T: Config> Deref for CollectionHandle<T> {
 	type Target = Collection<T::AccountId>;
modifiedpallets/evm-collection/src/eth.rsdiffbeforeafterboth
--- a/pallets/evm-collection/src/eth.rs
+++ b/pallets/evm-collection/src/eth.rs
@@ -17,7 +17,7 @@
 use core::marker::PhantomData;
 use evm_coder::{abi::AbiWriter, execution::*, generate_stubgen, solidity_interface, types::*, ToLog};
 use ethereum as _;
-use pallet_common::{CollectionById, CollectionHandle};
+use pallet_common::CollectionById;
 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
 use pallet_evm::{
 	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure,
@@ -26,7 +26,7 @@
 use sp_core::H160;
 use up_data_structs::{
 	CreateCollectionData, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
-	MAX_COLLECTION_NAME_LENGTH, SponsorshipState,
+	MAX_COLLECTION_NAME_LENGTH,
 };
 use crate::{Config, Pallet};
 use frame_support::traits::Get;
@@ -57,7 +57,6 @@
 
 #[solidity_interface(name = "Collection")]
 impl<T: Config> EvmCollection<T> {
-
 	fn create_721_collection(
 		&self,
 		caller: caller,
@@ -103,28 +102,16 @@
 		Ok(address)
 	}
 
-	fn set_sponsor(
-		&self,
-		caller: caller,
-		contract_address: address,
-		sponsor: address,
-	) -> Result<void> {
-		let collection_id =
-			pallet_common::eth::map_eth_to_id(&contract_address).ok_or(Error::Revert("".into()))?;
-		let mut collection =
-			pallet_common::CollectionHandle::new_with_recorder(collection_id, self.0.clone())
-				.ok_or(Error::Revert("".into()))?;
-		
-		let caller = T::CrossAccountId::from_eth(caller);
-		collection.check_is_owner(&caller).map_err(|e| Error::Revert(format!("{:?}", e)))?;
+	// fn set_sponsor(collection_id: address, sponsor: address) -> Result<void> {
+	// 	let collection_id =
+	// 		pallet_common::eth::map_eth_to_id(&collection_id).ok_or(Error::Revert("".into()))?;
+	// 	let mut collection = <CollectionById<T>>::get(collection_id).ok_or(Error::Revert("".into()))?;
+	// 	let sponsor = T::CrossAccountId::from_eth(sponsor);
+	// 	collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.as_sub().clone());
+	// 	<CollectionById<T>>::insert(collection_id, collection);
+	// 	Ok(())
+	// }
 
-		let sponsor = T::CrossAccountId::from_eth(sponsor);
-		collection.set_sponsor(sponsor.as_sub().clone());
-		collection
-			.save()
-			.map_err(|e| Error::Revert(format!("{:?}", e)))
-	}
-
 	// fn set_offchain_shema(shema: string) -> Result<void> {
 	// 	Ok(())
 	// }
@@ -168,7 +155,7 @@
 			return None;
 		}
 
-		let helpers = EvmCollection::<T>(SubstrateRecorder::<T>::new(gas_left));
+		let helpers = EvmCollection::<T>(SubstrateRecorder::new(gas_left));
 		pallet_evm_coder_substrate::call(*source, helpers, value, input)
 	}
 
modifiedpallets/evm-collection/src/stubs/Collection.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/evm-collection/src/stubs/Collection.soldiffbeforeafterboth
--- a/pallets/evm-collection/src/stubs/Collection.sol
+++ b/pallets/evm-collection/src/stubs/Collection.sol
@@ -21,7 +21,7 @@
 	}
 }
 
-// Selector: 6503bbc2
+// Selector: d32d5104
 contract Collection is Dummy, ERC165 {
 	// Selector: create721Collection(string,string,string) 951c0151
 	function create721Collection(
@@ -38,10 +38,53 @@
 	}
 
 	// Selector: setSponsor(address,address) f01fba93
-	function setSponsor(address contractAddress, address sponsor) public view {
+	function setSponsor(address collectionAddress, address sponsor)
+		public
+		view
+	{
 		require(false, stub_error);
-		contractAddress;
+		collectionAddress;
 		sponsor;
 		dummy;
 	}
+
+	// Selector: confirmSponsorship(address) abc00001
+	function confirmSponsorship(address collectionAddress) public view {
+		require(false, stub_error);
+		collectionAddress;
+		dummy;
+	}
+
+	// Selector: setOffchainShema(address,string) d7dc2de3
+	function setOffchainShema(address collectionAddress, string memory shema)
+		public
+		view
+	{
+		require(false, stub_error);
+		collectionAddress;
+		shema;
+		dummy;
+	}
+
+	// Selector: setVariableOnChainSchema(address,string) 582691c3
+	function setVariableOnChainSchema(
+		address collectionAddress,
+		string memory variable
+	) public view {
+		require(false, stub_error);
+		collectionAddress;
+		variable;
+		dummy;
+	}
+
+	// Selector: setConstOnChainSchema(address,string) 921456e7
+	function setConstOnChainSchema(
+		address collectionAddress,
+		string memory constOnChain
+	) public view {
+		require(false, stub_error);
+		collectionAddress;
+		constOnChain;
+		dummy;
+	}
 }
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -544,11 +544,9 @@
 
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
 			ensure!(
-				target_collection.sponsorship.pending_sponsor() == Some(&sender),
+				target_collection.confirm_sponsorship(&sender),
 				Error::<T>::ConfirmUnsetSponsorFail
 			);
-
-			target_collection.sponsorship = SponsorshipState::Confirmed(sender.clone());
 
 			<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(
 				collection_id,
modifiedtests/src/eth/api/Collection.soldiffbeforeafterboth
--- a/tests/src/eth/api/Collection.sol
+++ b/tests/src/eth/api/Collection.sol
@@ -12,7 +12,7 @@
 	function supportsInterface(bytes4 interfaceID) external view returns (bool);
 }
 
-// Selector: 6503bbc2
+// Selector: d32d5104
 interface Collection is Dummy, ERC165 {
 	// Selector: create721Collection(string,string,string) 951c0151
 	function create721Collection(
@@ -22,5 +22,27 @@
 	) external view returns (address);
 
 	// Selector: setSponsor(address,address) f01fba93
-	function setSponsor(address contractAddress, address sponsor) external view;
+	function setSponsor(address collectionAddress, address sponsor)
+		external
+		view;
+
+	// Selector: confirmSponsorship(address) abc00001
+	function confirmSponsorship(address collectionAddress) external view;
+
+	// Selector: setOffchainShema(address,string) d7dc2de3
+	function setOffchainShema(address collectionAddress, string memory shema)
+		external
+		view;
+
+	// Selector: setVariableOnChainSchema(address,string) 582691c3
+	function setVariableOnChainSchema(
+		address collectionAddress,
+		string memory variable
+	) external view;
+
+	// Selector: setConstOnChainSchema(address,string) 921456e7
+	function setConstOnChainSchema(
+		address collectionAddress,
+		string memory constOnChain
+	) external view;
 }
modifiedtests/src/eth/collectionAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/collectionAbi.json
+++ b/tests/src/eth/collectionAbi.json
@@ -1,6 +1,19 @@
 [
   {
     "inputs": [
+      {
+        "internalType": "address",
+        "name": "collectionAddress",
+        "type": "address"
+      }
+    ],
+    "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" }
@@ -14,7 +27,35 @@
     "inputs": [
       {
         "internalType": "address",
-        "name": "contractAddress",
+        "name": "collectionAddress",
+        "type": "address"
+      },
+      { "internalType": "string", "name": "constOnChain", "type": "string" }
+    ],
+    "name": "setConstOnChainSchema",
+    "outputs": [],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      {
+        "internalType": "address",
+        "name": "collectionAddress",
+        "type": "address"
+      },
+      { "internalType": "string", "name": "shema", "type": "string" }
+    ],
+    "name": "setOffchainShema",
+    "outputs": [],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      {
+        "internalType": "address",
+        "name": "collectionAddress",
         "type": "address"
       },
       { "internalType": "address", "name": "sponsor", "type": "address" }
@@ -26,6 +67,20 @@
   },
   {
     "inputs": [
+      {
+        "internalType": "address",
+        "name": "collectionAddress",
+        "type": "address"
+      },
+      { "internalType": "string", "name": "variable", "type": "string" }
+    ],
+    "name": "setVariableOnChainSchema",
+    "outputs": [],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [
       { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
     ],
     "name": "supportsInterface",
modifiedtests/src/eth/createCollection.test.tsdiffbeforeafterboth
before · tests/src/eth/createCollection.test.ts
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 {ApiPromise} from '@polkadot/api';18import {evmToAddress} from '@polkadot/util-crypto';19import {expect} from 'chai';20import {getCreatedCollectionCount, getDetailedCollectionInfo} from '../util/helpers';21import {collectionHelper, collectionIdFromAddress, createEthAccountWithBalance, itWeb3, normalizeAddress} from './util/helpers';2223async function getCollectionAddressFromResult(api: ApiPromise, result: any) {24  const collectionIdAddress = normalizeAddress(result.events[0].raw.topics[2]);25  const collectionId = collectionIdFromAddress(collectionIdAddress);  26  const collection = (await getDetailedCollectionInfo(api, collectionId))!;27  return {collectionIdAddress, collectionId, collection};28}2930describe('Create collection from EVM', () => {31  itWeb3('Create collection', async ({api, web3}) => {32    const owner = await createEthAccountWithBalance(api, web3);33    const helper = collectionHelper(web3, owner);34    const collectionName = 'CollectionEVM';35    const description = 'Some description';36    const tokenPrefix = 'token prefix';37  38    const collectionCountBefore = await getCreatedCollectionCount(api);39    const result = await helper.methods40      .create721Collection(collectionName, description, tokenPrefix)41      .send();42    const collectionCountAfter = await getCreatedCollectionCount(api);43  44    const {collectionId, collection} = await getCollectionAddressFromResult(api, result);45    expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);46    expect(collectionId).to.be.eq(collectionCountAfter);47    expect(collection.name.map(v => String.fromCharCode(v.toNumber())).join('')).to.be.eq(collectionName);48    expect(collection.description.map(v => String.fromCharCode(v.toNumber())).join('')).to.be.eq(description);49    expect(collection.tokenPrefix.toHuman()).to.be.eq(tokenPrefix);50    expect(collection.schemaVersion.type).to.be.eq('ImageURL');51  });52  53  itWeb3('Set sponsorship', async ({api, web3}) => {54    const owner = await createEthAccountWithBalance(api, web3);55    const helper = collectionHelper(web3, owner);56    let result = await helper.methods.create721Collection('Sponsor collection', '1', '1').send();57    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);58    const sponsor = await createEthAccountWithBalance(api, web3);59    result = await helper.methods.setSponsor(collectionIdAddress, sponsor).send();60    const collection = (await getDetailedCollectionInfo(api, collectionId))!;61    expect(collection.sponsorship.isUnconfirmed).to.be.true;62    expect(collection.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));63  });646566});
after · tests/src/eth/createCollection.test.ts
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 {ApiPromise} from '@polkadot/api';18import {evmToAddress} from '@polkadot/util-crypto';19import {expect} from 'chai';20import {getCreatedCollectionCount, getDetailedCollectionInfo} from '../util/helpers';21import {collectionHelper, collectionIdFromAddress, createEthAccountWithBalance, itWeb3, normalizeAddress} from './util/helpers';2223async function getCollectionAddressFromResult(api: ApiPromise, result: any) {24  const collectionIdAddress = normalizeAddress(result.events[0].raw.topics[2]);25  const collectionId = collectionIdFromAddress(collectionIdAddress);  26  const collection = (await getDetailedCollectionInfo(api, collectionId))!;27  return {collectionIdAddress, collectionId, collection};28}2930describe('Create collection from EVM', () => {31  itWeb3('Create collection', async ({api, web3}) => {32    const owner = await createEthAccountWithBalance(api, web3);33    const helper = collectionHelper(web3, owner);34    const collectionName = 'CollectionEVM';35    const description = 'Some description';36    const tokenPrefix = 'token prefix';37  38    const collectionCountBefore = await getCreatedCollectionCount(api);39    const result = await helper.methods40      .create721Collection(collectionName, description, tokenPrefix)41      .send();42    const collectionCountAfter = await getCreatedCollectionCount(api);43  44    const {collectionId, collection} = await getCollectionAddressFromResult(api, result);45    expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);46    expect(collectionId).to.be.eq(collectionCountAfter);47    expect(collection.name.map(v => String.fromCharCode(v.toNumber())).join('')).to.be.eq(collectionName);48    expect(collection.description.map(v => String.fromCharCode(v.toNumber())).join('')).to.be.eq(description);49    expect(collection.tokenPrefix.toHuman()).to.be.eq(tokenPrefix);50    expect(collection.schemaVersion.type).to.be.eq('ImageURL');51  });52  53  itWeb3('Set sponsorship', async ({api, web3}) => {54    const owner = await createEthAccountWithBalance(api, web3);55    const helper = collectionHelper(web3, owner);56    let result = await helper.methods.create721Collection('Sponsor collection', '1', '1').send();57    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);58    const sponsor = await createEthAccountWithBalance(api, web3);59    result = await helper.methods.setSponsor(collectionIdAddress, sponsor).send();60    let collection = (await getDetailedCollectionInfo(api, collectionId))!;61    expect(collection.sponsorship.isUnconfirmed).to.be.true;62    expect(collection.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));63    await expect(helper.methods.confirmSponsorship(collectionIdAddress).call()).to.be.rejectedWith('Caller is not set as sponsor');64    const sponsorHelper = collectionHelper(web3, sponsor);65    await sponsorHelper.methods.confirmSponsorship(collectionIdAddress).send();66    collection = (await getDetailedCollectionInfo(api, collectionId))!;67    expect(collection.sponsorship.isConfirmed).to.be.true;68    expect(collection.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));69  });70  71  itWeb3('Set offchain shema', async ({api, web3}) => {72    const owner = await createEthAccountWithBalance(api, web3);73    const helper = collectionHelper(web3, owner);74    let result = await helper.methods.create721Collection('Shema collection', '2', '2').send();75    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);76    const shema = 'Some shema';77    result = await helper.methods.setOffchainShema(collectionIdAddress, shema).send();78    const collection = (await getDetailedCollectionInfo(api, collectionId))!;79    expect(collection.offchainSchema.toHuman()).to.be.eq(shema);80  });81  82  itWeb3('Set variable on chain schema', async ({api, web3}) => {83    const owner = await createEthAccountWithBalance(api, web3);84    const helper = collectionHelper(web3, owner);85    let result = await helper.methods.create721Collection('Variable collection', '3', '3').send();86    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);87    const variable = 'Some variable';88    result = await helper.methods.setVariableOnChainSchema(collectionIdAddress, variable).send();89    const collection = (await getDetailedCollectionInfo(api, collectionId))!;90    expect(collection.variableOnChainSchema.toHuman()).to.be.eq(variable);91  });92  93  itWeb3('Set const on chain schema', async ({api, web3}) => {94    const owner = await createEthAccountWithBalance(api, web3);95    const helper = collectionHelper(web3, owner);96    let result = await helper.methods.create721Collection('Const collection', '4', '4').send();97    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);98    const constShema = 'Some const';99    result = await helper.methods.setConstOnChainSchema(collectionIdAddress, constShema).send();100    const collection = (await getDetailedCollectionInfo(api, collectionId))!;101    expect(collection.constOnChainSchema.toHuman()).to.be.eq(constShema);102  });103});