git.delta.rocks / unique-network / refs/commits / 7ed3eb8cb302

difftreelog

CORE-337 Rewrite set limits

Trubnikov Sergey2022-05-24parent: #686ae35.patch.diff
in: master

9 files changed

modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -16,10 +16,11 @@
 
 use evm_coder::{solidity_interface, types::*, execution::{Result, Error}};
 pub use pallet_evm::{PrecompileOutput, PrecompileResult, account::CrossAccountId};
-use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder};
+use pallet_evm_coder_substrate::dispatch_to_evm;
 use sp_core::{H160, U256};
 use sp_std::vec::Vec;
-use up_data_structs::Property;
+use up_data_structs::{Property, SponsoringRateLimit};
+use alloc::format;
 
 use crate::{Pallet, CollectionHandle, Config, CollectionProperties};
 
@@ -87,37 +88,53 @@
 		Ok(())
 	}
 
-	fn set_limits(
-		&self,
+	fn set_limit(
+		&mut self,
 		caller: caller,
-		limits_json: string,
+		limit: string,
+		value: string,
 	) -> Result<void> {
-		// let mut collection = collection_from_address::<T>(self.contract_address(caller).unwrap(), self.1.gas_left())?;
-		// check_is_owner(caller, &collection)?;
+		check_is_owner(caller, self)?;
+		let mut limits = self.limits.clone();
 
-		// let limits = serde_json_core::from_str(limits_json.as_ref())
-		// 	.map_err(|e| Error::Revert(format!("Parse JSON error: {}", e)))?;
-		// collection.limits = limits.0;
-		// collection.save().map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+		match limit.as_str() {
+			"accountTokenOwnershipLimit" => {
+				limits.account_token_ownership_limit = parse_int(value)?;
+			},
+			"sponsoredDataSize" => {
+				limits.sponsored_data_size = parse_int(value)?;
+			},
+			"sponsoredDataRateLimit" => {
+				limits.sponsored_data_rate_limit = Some(SponsoringRateLimit::Blocks(parse_int(value)?.unwrap()));
+			},
+			"tokenLimit" => {
+				limits.token_limit = parse_int(value)?;
+			},
+			"sponsorTransferTimeout" => {
+				limits.sponsor_transfer_timeout = parse_int(value)?;
+			},
+			"sponsorApproveTimeout" => {
+				limits.sponsor_approve_timeout = parse_int(value)?;
+			},
+			"ownerCanTransfer" => {
+				limits.owner_can_transfer = parse_bool(value)?;
+			},
+			"ownerCanDestroy" => {
+				limits.owner_can_destroy = parse_bool(value)?;
+			},
+			"transfersEnabled" => {
+				limits.transfers_enabled = parse_bool(value)?;
+			},
+			_ => return Err(Error::Revert(format!("Unknown limit \"{}\"", limit)))
+		}
+		self.limits = limits;
+		save(self);
 		Ok(())
 	}
 
 	fn contract_address(&self, _caller: caller) -> Result<address> {
 		Ok(crate::eth::collection_id_to_address(self.id))
 	}
-}
-
-fn collection_from_address<T: Config>(
-	collection_address: address,
-	gas_limit: u64
-) -> Result<CollectionHandle<T>> {
-	let collection_id = crate::eth::map_eth_to_id(&collection_address)
-	.ok_or(Error::Revert("Contract is not an unique collection".into()))?;
-	let recorder = <SubstrateRecorder<T>>::new(gas_limit);
-	let collection =
-		CollectionHandle::new_with_recorder(collection_id, recorder)
-			.ok_or(Error::Revert("Create collection handle error".into()))?;
-	Ok(collection)
 }
 
 fn check_is_owner<T: Config>(caller: caller, collection: &CollectionHandle<T>) -> Result<()> {
@@ -130,4 +147,16 @@
 
 fn save<T: Config>(collection: &CollectionHandle<T>) {
 	<crate::CollectionById<T>>::insert(collection.id, collection.collection.clone());
+}
+
+fn parse_int(value: string) -> Result<Option<u32>> {
+	value.parse::<u32>()
+		.map_err(|e| Error::Revert(format!("Int value \"{}\" parse error: {}", value, e)))
+		.map(|value| Some(value))
+}
+
+fn parse_bool(value: string) -> Result<Option<bool>> {
+	value.parse::<bool>()
+		.map_err(|e| Error::Revert(format!("Bool value \"{}\" parse error: {}", value, e)))
+		.map(|value| Some(value))
 }
\ No newline at end of file
modifiedpallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth
--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -51,67 +51,6 @@
 	event MintingFinished();
 }
 
-// Selector: 38e33c60
-contract Collection is Dummy, ERC165 {
-	// Selector: setCollectionProperty(string,bytes) 2f073f66
-	function setCollectionProperty(string memory key, bytes memory value)
-		public
-	{
-		require(false, stub_error);
-		key;
-		value;
-		dummy = 0;
-	}
-
-	// Selector: deleteCollectionProperty(string) 7b7debce
-	function deleteCollectionProperty(string memory key) public {
-		require(false, stub_error);
-		key;
-		dummy = 0;
-	}
-
-	// Throws error if key not found
-	//
-	// Selector: collectionProperty(string) cf24fd6d
-	function collectionProperty(string memory key)
-		public
-		view
-		returns (bytes memory)
-	{
-		require(false, stub_error);
-		key;
-		dummy;
-		return hex"";
-	}
-
-	// Selector: ethSetSponsor(address) 8f9af356
-	function ethSetSponsor(address sponsor) public {
-		require(false, stub_error);
-		sponsor;
-		dummy = 0;
-	}
-
-	// Selector: ethConfirmSponsorship() a8580d1a
-	function ethConfirmSponsorship() public {
-		require(false, stub_error);
-		dummy = 0;
-	}
-
-	// Selector: setLimits(string) 72cb345d
-	function setLimits(string memory limitsJson) public view {
-		require(false, stub_error);
-		limitsJson;
-		dummy;
-	}
-
-	// Selector: contractAddress() f6b4dfb4
-	function contractAddress() public view returns (address) {
-		require(false, stub_error);
-		dummy;
-		return 0x0000000000000000000000000000000000000000;
-	}
-}
-
 // Selector: 41369377
 contract TokenProperties is Dummy, ERC165 {
 	// Selector: setTokenPropertyPermission(string,bool,bool,bool) 222d97fa
@@ -441,6 +380,68 @@
 	}
 }
 
+// Selector: f5652829
+contract Collection is Dummy, ERC165 {
+	// Selector: setCollectionProperty(string,bytes) 2f073f66
+	function setCollectionProperty(string memory key, bytes memory value)
+		public
+	{
+		require(false, stub_error);
+		key;
+		value;
+		dummy = 0;
+	}
+
+	// Selector: deleteCollectionProperty(string) 7b7debce
+	function deleteCollectionProperty(string memory key) public {
+		require(false, stub_error);
+		key;
+		dummy = 0;
+	}
+
+	// Throws error if key not found
+	//
+	// Selector: collectionProperty(string) cf24fd6d
+	function collectionProperty(string memory key)
+		public
+		view
+		returns (bytes memory)
+	{
+		require(false, stub_error);
+		key;
+		dummy;
+		return hex"";
+	}
+
+	// Selector: ethSetSponsor(address) 8f9af356
+	function ethSetSponsor(address sponsor) public {
+		require(false, stub_error);
+		sponsor;
+		dummy = 0;
+	}
+
+	// Selector: ethConfirmSponsorship() a8580d1a
+	function ethConfirmSponsorship() public {
+		require(false, stub_error);
+		dummy = 0;
+	}
+
+	// Selector: setLimit(string,string) bf4d2014
+	function setLimit(string memory limit, string memory value) public {
+		require(false, stub_error);
+		limit;
+		value;
+		dummy = 0;
+	}
+
+	// Selector: contractAddress() f6b4dfb4
+	function contractAddress() public view returns (address) {
+		require(false, stub_error);
+		dummy;
+		return 0x0000000000000000000000000000000000000000;
+	}
+}
+
 contract UniqueNFT is
 	Dummy,
 	ERC165,
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -26,7 +26,7 @@
 	};
 	use frame_support::traits::Get;
 	use sp_core::H160;
-	use pallet_common::{CollectionHandle, CollectionById};
+	use pallet_common::CollectionById;
 	
 	use sp_std::vec::Vec;
 	use alloc::format;
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -368,30 +368,21 @@
 #[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub struct CollectionLimits {
-	#[serde(alias = "accountTokenOwnershipLimit")]
 	pub account_token_ownership_limit: Option<u32>,
-	#[serde(alias = "sponsoredDataSize")]
 	pub sponsored_data_size: Option<u32>,
 
 	/// FIXME should we delete this or repurpose it?
 	/// None - setVariableMetadata is not sponsored
 	/// Some(v) - setVariableMetadata is sponsored
 	///           if there is v block between txs
-	#[serde(alias = "sponsoredDataRateLimit")]
 	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,
-	#[serde(alias = "tokenLimit")]
 	pub token_limit: Option<u32>,
 
 	// Timeouts for item types in passed blocks
-	#[serde(alias = "sponsorTransferTimeout")]
 	pub sponsor_transfer_timeout: Option<u32>,
-	#[serde(alias = "sponsorApproveTimeout")]
 	pub sponsor_approve_timeout: Option<u32>,
-	#[serde(alias = "ownerCanTransfer")]
 	pub owner_can_transfer: Option<bool>,
-	#[serde(alias = "ownerCanDestroy")]
 	pub owner_can_destroy: Option<bool>,
-	#[serde(alias = "transfersEnabled")]
 	pub transfers_enabled: Option<bool>,
 }
 
deletedtests/src/eth/api/Collection.soldiffbeforeafterboth
--- a/tests/src/eth/api/Collection.sol
+++ /dev/null
@@ -1,28 +0,0 @@
-// 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: 15cc740e
-interface Collection is Dummy, ERC165 {
-	// Selector: setSponsor(address) 59753fb1
-	function setSponsor(address sponsor) external view;
-
-	// Selector: confirmSponsorship() c8c6a056
-	function confirmSponsorship() external view;
-
-	// Selector: setLimits(string) 72cb345d
-	function setLimits(string memory limitsJson) external view;
-
-	// Selector: contractAddress() f6b4dfb4
-	function contractAddress() external view returns (address);
-}
modifiedtests/src/eth/api/UniqueNFT.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -42,36 +42,6 @@
 	event MintingFinished();
 }
 
-// Selector: 38e33c60
-interface Collection is Dummy, ERC165 {
-	// Selector: setCollectionProperty(string,bytes) 2f073f66
-	function setCollectionProperty(string memory key, bytes memory value)
-		external;
-
-	// Selector: deleteCollectionProperty(string) 7b7debce
-	function deleteCollectionProperty(string memory key) external;
-
-	// Throws error if key not found
-	//
-	// Selector: collectionProperty(string) cf24fd6d
-	function collectionProperty(string memory key)
-		external
-		view
-		returns (bytes memory);
-
-	// Selector: ethSetSponsor(address) 8f9af356
-	function ethSetSponsor(address sponsor) external;
-
-	// Selector: ethConfirmSponsorship() a8580d1a
-	function ethConfirmSponsorship() external;
-
-	// Selector: setLimits(string) 72cb345d
-	function setLimits(string memory limitsJson) external view;
-
-	// Selector: contractAddress() f6b4dfb4
-	function contractAddress() external view returns (address);
-}
-
 // Selector: 41369377
 interface TokenProperties is Dummy, ERC165 {
 	// Selector: setTokenPropertyPermission(string,bool,bool,bool) 222d97fa
@@ -243,6 +213,36 @@
 		returns (bool);
 }
 
+// Selector: f5652829
+interface Collection is Dummy, ERC165 {
+	// Selector: setCollectionProperty(string,bytes) 2f073f66
+	function setCollectionProperty(string memory key, bytes memory value)
+		external;
+
+	// Selector: deleteCollectionProperty(string) 7b7debce
+	function deleteCollectionProperty(string memory key) external;
+
+	// Throws error if key not found
+	//
+	// Selector: collectionProperty(string) cf24fd6d
+	function collectionProperty(string memory key)
+		external
+		view
+		returns (bytes memory);
+
+	// Selector: ethSetSponsor(address) 8f9af356
+	function ethSetSponsor(address sponsor) external;
+
+	// Selector: ethConfirmSponsorship() a8580d1a
+	function ethConfirmSponsorship() external;
+
+	// Selector: setLimit(string,string) bf4d2014
+	function setLimit(string memory limit, string memory value) external;
+
+	// Selector: contractAddress() f6b4dfb4
+	function contractAddress() external view returns (address);
+}
+
 interface UniqueNFT is
 	Dummy,
 	ERC165,
modifiedtests/src/eth/createCollection.test.tsdiffbeforeafterboth
108 const limits = {108 const limits = {
109 accountTokenOwnershipLimit: 1000,109 accountTokenOwnershipLimit: 1000,
110 sponsoredDataSize: 1024,110 sponsoredDataSize: 1024,
111 sponsoredDataRateLimit: {Blocks: 30},111 sponsoredDataRateLimit: 30,
112 tokenLimit: 1000000,112 tokenLimit: 1000000,
113 sponsorTransferTimeout: 6,113 sponsorTransferTimeout: 6,
114 sponsorApproveTimeout: 6,114 sponsorApproveTimeout: 6,
117 transfersEnabled: false,117 transfersEnabled: false,
118 };118 };
119119
120 const limitsJson = JSON.stringify(limits, null, 1);
121 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);120 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
122 await collectionEvm.methods.setLimits(limitsJson).send();121 await collectionEvm.methods.setLimit('accountTokenOwnershipLimit', limits.accountTokenOwnershipLimit.toString()).send();
123 122 await collectionEvm.methods.setLimit('sponsoredDataSize', limits.sponsoredDataSize.toString()).send();
123 await collectionEvm.methods.setLimit('sponsoredDataRateLimit', limits.sponsoredDataRateLimit.toString()).send();
124 await collectionEvm.methods.setLimit('tokenLimit', limits.tokenLimit.toString()).send();
125 await collectionEvm.methods.setLimit('sponsorTransferTimeout', limits.sponsorTransferTimeout.toString()).send();
126 await collectionEvm.methods.setLimit('sponsorApproveTimeout', limits.sponsorApproveTimeout.toString()).send();
127 await collectionEvm.methods.setLimit('ownerCanTransfer', limits.ownerCanTransfer.toString()).send();
128 await collectionEvm.methods.setLimit('ownerCanDestroy', limits.ownerCanDestroy.toString()).send();
129 await collectionEvm.methods.setLimit('transfersEnabled', limits.transfersEnabled.toString()).send();
130
124 const collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;131 const collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
125 expect(collectionSub.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.eq(limits.accountTokenOwnershipLimit);132 expect(collectionSub.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.eq(limits.accountTokenOwnershipLimit);
126 expect(collectionSub.limits.sponsoredDataSize.unwrap().toNumber()).to.be.eq(limits.sponsoredDataSize);133 expect(collectionSub.limits.sponsoredDataSize.unwrap().toNumber()).to.be.eq(limits.sponsoredDataSize);
127 expect(collectionSub.limits.sponsoredDataRateLimit.unwrap().asBlocks.toNumber()).to.be.eq(limits.sponsoredDataRateLimit.Blocks);134 expect(collectionSub.limits.sponsoredDataRateLimit.unwrap().asBlocks.toNumber()).to.be.eq(limits.sponsoredDataRateLimit);
128 expect(collectionSub.limits.tokenLimit.unwrap().toNumber()).to.be.eq(limits.tokenLimit);135 expect(collectionSub.limits.tokenLimit.unwrap().toNumber()).to.be.eq(limits.tokenLimit);
129 expect(collectionSub.limits.sponsorTransferTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorTransferTimeout);136 expect(collectionSub.limits.sponsorTransferTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorTransferTimeout);
130 expect(collectionSub.limits.sponsorApproveTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorApproveTimeout);137 expect(collectionSub.limits.sponsorApproveTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorApproveTimeout);
172 // expect(tokenUri).to.be.equal(`https://offchain-service.local/token-info/${nextTokenId}`);179 // expect(tokenUri).to.be.equal(`https://offchain-service.local/token-info/${nextTokenId}`);
173 });180 });
181
182 itWeb3('Collection address exist', async ({api, web3}) => {
183 const owner = await createEthAccountWithBalance(api, web3);
184 const collectionAddressForNonexistentCollection = '0x17C4E6453CC49AAAAEACA894E6D9683E00112233';
185 const collectionHelper = evmCollectionHelper(web3, owner);
186 expect(await collectionHelper.methods
187 .isCollectionExist(collectionAddressForNonexistentCollection).call())
188 .to.be.false;
189
190 const result = await collectionHelper.methods.create721Collection('Const collection', '5', '5').send();
191 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
192 expect(await collectionHelper.methods
193 .isCollectionExist(collectionIdAddress).call())
194 .to.be.true;
195 });
174});196});
175197
176describe('(!negative tests!) Create collection from EVM', () => {198describe('(!negative tests!) Create collection from EVM', () => {
220 .call()).to.be.rejectedWith('NotSufficientFounds');242 .call()).to.be.rejectedWith('NotSufficientFounds');
221 });243 });
222
223 itWeb3('(!negative test!) Collection address (Create collection handle error)', async ({api, web3}) => {
224 const owner = await createEthAccountWithBalance(api, web3);
225 const collectionAddressForNonexistentCollection = '0x17C4E6453CC49AAAAEACA894E6D9683E00112233';
226 const collectionEvm = evmCollection(web3, owner, collectionAddressForNonexistentCollection);
227 const EXPECTED_ERROR = 'Create collection handle error';
228 {
229 const sponsor = await createEthAccountWithBalance(api, web3);
230 await expect(collectionEvm.methods
231 .setSponsor(sponsor)
232 .call()).to.be.rejectedWith(EXPECTED_ERROR);
233
234 const sponsorCollection = evmCollection(web3, sponsor, collectionAddressForNonexistentCollection);
235 await expect(sponsorCollection.methods
236 .confirmSponsorship()
237 .call()).to.be.rejectedWith(EXPECTED_ERROR);
238 }
239 {
240 const limits = '{"account_token_ownership_limit":1000}';
241 await expect(collectionEvm.methods
242 .setLimits(limits)
243 .call()).to.be.rejectedWith(EXPECTED_ERROR);
244 }
245 });
246244
247 itWeb3('(!negative test!) Check owner', async ({api, web3}) => {245 itWeb3('(!negative test!) Check owner', async ({api, web3}) => {
248 const owner = await createEthAccountWithBalance(api, web3);246 const owner = await createEthAccountWithBalance(api, web3);
255 {253 {
256 const sponsor = await createEthAccountWithBalance(api, web3);254 const sponsor = await createEthAccountWithBalance(api, web3);
257 await expect(contractEvmFromNotOwner.methods255 await expect(contractEvmFromNotOwner.methods
258 .setSponsor(sponsor)256 .ethSetSponsor(sponsor)
259 .call()).to.be.rejectedWith(EXPECTED_ERROR);257 .call()).to.be.rejectedWith(EXPECTED_ERROR);
260 258
261 const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);259 const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
262 await expect(sponsorCollection.methods260 await expect(sponsorCollection.methods
263 .confirmSponsorship()261 .ethConfirmSponsorship()
264 .call()).to.be.rejectedWith('Caller is not set as sponsor');262 .call()).to.be.rejectedWith('Caller is not set as sponsor');
265 }263 }
266 {264 {
267 const limits = '{"account_token_ownership_limit":1000}';
268 await expect(contractEvmFromNotOwner.methods265 await expect(contractEvmFromNotOwner.methods
269 .setLimits(limits)266 .setLimit('account_token_ownership_limit', '1000')
270 .call()).to.be.rejectedWith(EXPECTED_ERROR);267 .call()).to.be.rejectedWith(EXPECTED_ERROR);
271 }268 }
272 });269 });
277 const result = await collectionHelper.methods.create721Collection('Schema collection', 'A', 'A').send();274 const result = await collectionHelper.methods.create721Collection('Schema collection', 'A', 'A').send();
278 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);275 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
279 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);276 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
277 await expect(collectionEvm.methods
278 .setLimit('badLimit', 'true')
280 const badJson = '{accountTokenOwnershipLimit: 1000}';279 .call()).to.be.rejectedWith('Unknown limit "badLimit"');
281 await expect(collectionEvm.methods280 await expect(collectionEvm.methods
282 .setLimits(badJson)281 .setLimit('sponsoredDataSize', 'badValue')
283 .call()).to.be.rejectedWith('Parse JSON error:');282 .call()).to.be.rejectedWith('Int value "badValue" parse error:');
283 await expect(collectionEvm.methods
284 .setLimit('ownerCanTransfer', 'badValue')
285 .call()).to.be.rejectedWith('Bool value "badValue" parse error:');
284 });286 });
285});287});
modifiedtests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -325,11 +325,12 @@
   },
   {
     "inputs": [
-      { "internalType": "string", "name": "limitsJson", "type": "string" }
+      { "internalType": "string", "name": "limit", "type": "string" },
+      { "internalType": "string", "name": "value", "type": "string" }
     ],
-    "name": "setLimits",
+    "name": "setLimit",
     "outputs": [],
-    "stateMutability": "view",
+    "stateMutability": "nonpayable",
     "type": "function"
   },
   {