git.delta.rocks / unique-network / refs/commits / 31962dd005a3

difftreelog

CORE-302 Implement setLimits

Trubnikov Sergey2022-04-22parent: #0c9dfc5.patch.diff
in: master

9 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6091,6 +6091,7 @@
  "pallet-nonfungible",
  "parity-scale-codec 3.1.2",
  "scale-info",
+ "serde_json",
  "sp-core",
  "sp-runtime",
  "sp-std",
modifiedpallets/evm-collection/Cargo.tomldiffbeforeafterboth
--- a/pallets/evm-collection/Cargo.toml
+++ b/pallets/evm-collection/Cargo.toml
@@ -10,6 +10,7 @@
 ] }
 ethereum = { version = "0.12.0", default-features = false }
 log = { default-features = false, version = "0.4.14" }
+serde_json = { version = "1.0.68", default-features = false, features = ["alloc"] }
 
 # Substrate
 frame-support = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.21' }
@@ -27,7 +28,7 @@
 pallet-common = { default-features = false, path = '../../pallets/common' }
 pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
 pallet-nonfungible = { default-features = false, path = '../../pallets/nonfungible' }
-up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
+up-data-structs = { default-features = false, path = '../../primitives/data-structs', features = ["serde1"] }
 
 [dependencies.codec]
 default-features = false
modifiedpallets/evm-collection/src/eth.rsdiffbeforeafterboth
before · pallets/evm-collection/src/eth.rs
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/>.1617use core::marker::PhantomData;18use evm_coder::{abi::AbiWriter, execution::*, generate_stubgen, solidity_interface, types::*, ToLog};19use ethereum as _;20use pallet_common::CollectionById;21use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};22use pallet_evm::{23	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure,24	account::CrossAccountId, Pallet as PalletEvm,25};26use sp_core::H160;27use up_data_structs::{28	CreateCollectionData, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,29	MAX_COLLECTION_NAME_LENGTH,30};31use crate::{Config, Pallet};32use frame_support::traits::Get;3334use sp_std::{vec::Vec, rc::Rc};35use alloc::format;3637struct EvmCollection<T: Config>(SubstrateRecorder<T>);38impl<T: Config> WithRecorder<T> for EvmCollection<T> {39	fn recorder(&self) -> &SubstrateRecorder<T> {40		&self.041	}4243	fn into_recorder(self) -> SubstrateRecorder<T> {44		self.045	}46}4748#[derive(ToLog)]49pub enum CollectionEvent {50	CollectionCreated {51		#[indexed]52		owner: address,53		#[indexed]54		collection_id: address,55	},56}5758#[solidity_interface(name = "Collection")]59impl<T: Config> EvmCollection<T> {60	fn create_721_collection(61		&self,62		caller: caller,63		name: string,64		description: string,65		token_prefix: string,66	) -> Result<address> {67		let caller = T::CrossAccountId::from_eth(caller);68		let name = name69			.encode_utf16()70			.collect::<Vec<u16>>()71			.try_into()72			.map_err(|_| error_feild_too_long("name", MAX_COLLECTION_NAME_LENGTH))?;73		let description = description74			.encode_utf16()75			.collect::<Vec<u16>>()76			.try_into()77			.map_err(|_| error_feild_too_long("description", MAX_COLLECTION_DESCRIPTION_LENGTH))?;78		let token_prefix = token_prefix79			.into_bytes()80			.try_into()81			.map_err(|_| error_feild_too_long("token_prefix", MAX_TOKEN_PREFIX_LENGTH))?;8283		let data = CreateCollectionData {84			name,85			description,86			token_prefix,87			..Default::default()88		};8990		let collection_id =91			<pallet_nonfungible::Pallet<T>>::init_collection(caller.as_sub().clone(), data)92				.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;9394		let address = pallet_common::eth::collection_id_to_address(collection_id);95		<PalletEvm<T>>::deposit_log(96			CollectionEvent::CollectionCreated {97				owner: *caller.as_eth(),98				collection_id: address,99			}100			.to_log(address),101		);102		Ok(address)103	}104105	// fn set_sponsor(collection_id: address, sponsor: address) -> Result<void> {106	// 	let collection_id =107	// 		pallet_common::eth::map_eth_to_id(&collection_id).ok_or(Error::Revert("".into()))?;108	// 	let mut collection = <CollectionById<T>>::get(collection_id).ok_or(Error::Revert("".into()))?;109	// 	let sponsor = T::CrossAccountId::from_eth(sponsor);110	// 	collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.as_sub().clone());111	// 	<CollectionById<T>>::insert(collection_id, collection);112	// 	Ok(())113	// }114115	// fn set_offchain_shema(shema: string) -> Result<void> {116	// 	Ok(())117	// }118119	// fn set_const_on_chain_schema(shema: string) -> Result<void> {120	// 	Ok(())121	// }122123	// fn set_variable_on_chain_schema(shema: string) -> Result<void> {124	// 	Ok(())125	// }126127	// fn set_limits(limits: string) -> Result<void> {128	// 	Ok(())129	// }130}131132fn error_feild_too_long(feild: &str, bound: u32) -> Error {133	Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))134}135136pub struct CollectionOnMethodCall<T: Config>(PhantomData<*const T>);137impl<T: Config> OnMethodCall<T> for CollectionOnMethodCall<T> {138	fn is_reserved(contract: &sp_core::H160) -> bool {139		contract == &T::ContractAddress::get()140	}141142	fn is_used(contract: &sp_core::H160) -> bool {143		contract == &T::ContractAddress::get()144	}145146	fn call(147		source: &sp_core::H160,148		target: &sp_core::H160,149		gas_left: u64,150		input: &[u8],151		value: sp_core::U256,152	) -> Option<PrecompileResult> {153		// TODO: Extract to another OnMethodCall handler154		if target != &T::ContractAddress::get() {155			return None;156		}157158		let helpers = EvmCollection::<T>(SubstrateRecorder::new(gas_left));159		pallet_evm_coder_substrate::call(*source, helpers, value, input)160	}161162	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {163		(contract == &T::ContractAddress::get())164			.then(|| include_bytes!("./stubs/Collection.raw").to_vec())165	}166}167168generate_stubgen!(collection_impl, CollectionCall<()>, true);169generate_stubgen!(collection_iface, CollectionCall<()>, false);
after · pallets/evm-collection/src/eth.rs
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/>.1617use core::marker::PhantomData;18use evm_coder::{abi::AbiWriter, execution::*, generate_stubgen, solidity_interface, types::*, ToLog};19use ethereum as _;20use pallet_common::CollectionById;21use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};22use pallet_evm::{23	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure,24	account::CrossAccountId, Pallet as PalletEvm,25};26use sp_core::H160;27use up_data_structs::{28	CreateCollectionData, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,29	MAX_COLLECTION_NAME_LENGTH,30};31use crate::{Config, Pallet};32use frame_support::traits::Get;3334use sp_std::{vec::Vec, rc::Rc};35use alloc::format;3637struct EvmCollection<T: Config>(SubstrateRecorder<T>);38impl<T: Config> WithRecorder<T> for EvmCollection<T> {39	fn recorder(&self) -> &SubstrateRecorder<T> {40		&self.041	}4243	fn into_recorder(self) -> SubstrateRecorder<T> {44		self.045	}46}4748#[derive(ToLog)]49pub enum CollectionEvent {50	CollectionCreated {51		#[indexed]52		owner: address,53		#[indexed]54		collection_id: address,55	},56}5758#[solidity_interface(name = "Collection")]59impl<T: Config> EvmCollection<T> {60	fn create_721_collection(61		&self,62		caller: caller,63		name: string,64		description: string,65		token_prefix: string,66	) -> Result<address> {67		let caller = T::CrossAccountId::from_eth(caller);68		let name = name69			.encode_utf16()70			.collect::<Vec<u16>>()71			.try_into()72			.map_err(|_| error_feild_too_long("name", MAX_COLLECTION_NAME_LENGTH))?;73		let description = description74			.encode_utf16()75			.collect::<Vec<u16>>()76			.try_into()77			.map_err(|_| error_feild_too_long("description", MAX_COLLECTION_DESCRIPTION_LENGTH))?;78		let token_prefix = token_prefix79			.into_bytes()80			.try_into()81			.map_err(|_| error_feild_too_long("token_prefix", MAX_TOKEN_PREFIX_LENGTH))?;8283		let data = CreateCollectionData {84			name,85			description,86			token_prefix,87			..Default::default()88		};8990		let collection_id =91			<pallet_nonfungible::Pallet<T>>::init_collection(caller.as_sub().clone(), data)92				.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;9394		let address = pallet_common::eth::collection_id_to_address(collection_id);95		<PalletEvm<T>>::deposit_log(96			CollectionEvent::CollectionCreated {97				owner: *caller.as_eth(),98				collection_id: address,99			}100			.to_log(address),101		);102		Ok(address)103	}104105	// fn set_sponsor(collection_id: address, sponsor: address) -> Result<void> {106	// 	let collection_id =107	// 		pallet_common::eth::map_eth_to_id(&collection_id).ok_or(Error::Revert("".into()))?;108	// 	let mut collection = <CollectionById<T>>::get(collection_id).ok_or(Error::Revert("".into()))?;109	// 	let sponsor = T::CrossAccountId::from_eth(sponsor);110	// 	collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.as_sub().clone());111	// 	<CollectionById<T>>::insert(collection_id, collection);112	// 	Ok(())113	// }114115	fn set_offchain_shema(shema: string) -> Result<void> {116		let shema = shema117			.into_bytes()118			.try_into()119			.map_err(|_| error_feild_too_long(stringify!(shema), OFFCHAIN_SCHEMA_LIMIT))?;120		collection.offchain_schema = shema;121		save(collection)122	}123124	fn confirm_sponsorship(&self, caller: caller, collection_address: address) -> Result<void> {125		let (_, mut collection) = collection_from_address(collection_address, &self.0)?;126		let caller = T::CrossAccountId::from_eth(caller);127		if !collection.confirm_sponsorship(caller.as_sub()) {128			return Err(Error::Revert("Caller is not set as sponsor".into()));129		}130		save(collection)131	}132133	// fn set_variable_on_chain_schema(shema: string) -> Result<void> {134	// 	Ok(())135	// }136137	fn set_variable_on_chain_schema(138		&self,139		caller: caller,140		collection_address: address,141		variable: string,142	) -> Result<void> {143		let (_, mut collection) = collection_from_address(collection_address, &self.0)?;144		check_is_owner(caller, &collection)?;145146		let variable = variable.into_bytes().try_into().map_err(|_| {147			error_feild_too_long(stringify!(variable), VARIABLE_ON_CHAIN_SCHEMA_LIMIT)148		})?;149		collection.variable_on_chain_schema = variable;150		save(collection)151	}152153	fn set_const_on_chain_schema(154		&self,155		caller: caller,156		collection_address: address,157		const_on_chain: string,158	) -> Result<void> {159		let (_, mut collection) = collection_from_address(collection_address, &self.0)?;160		check_is_owner(caller, &collection)?;161162		let const_on_chain = const_on_chain.into_bytes().try_into().map_err(|_| {163			error_feild_too_long(stringify!(const_on_chain), CONST_ON_CHAIN_SCHEMA_LIMIT)164		})?;165		collection.const_on_chain_schema = const_on_chain;166		save(collection)167	}168169	fn set_limits(170		&self,171		caller: caller,172		collection_address: address,173		limits_json: string,174	) -> Result<void> {175		let (_, mut collection) = collection_from_address(collection_address, &self.0)?;176		check_is_owner(caller, &collection)?;177178		let limits = serde_json::from_str(limits_json.as_ref())179			.map_err(|e| Error::Revert(format!("Parse JSON error: {}", e)))?;180		collection.limits = limits;181		save(collection)182	}183}184185fn error_feild_too_long(feild: &str, bound: u32) -> Error {186	Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))187}188189pub struct CollectionOnMethodCall<T: Config>(PhantomData<*const T>);190impl<T: Config> OnMethodCall<T> for CollectionOnMethodCall<T> {191	fn is_reserved(contract: &sp_core::H160) -> bool {192		contract == &T::ContractAddress::get()193	}194195	fn is_used(contract: &sp_core::H160) -> bool {196		contract == &T::ContractAddress::get()197	}198199	fn call(200		source: &sp_core::H160,201		target: &sp_core::H160,202		gas_left: u64,203		input: &[u8],204		value: sp_core::U256,205	) -> Option<PrecompileResult> {206		// TODO: Extract to another OnMethodCall handler207		if target != &T::ContractAddress::get() {208			return None;209		}210211		let helpers = EvmCollection::<T>(SubstrateRecorder::new(gas_left));212		pallet_evm_coder_substrate::call(*source, helpers, value, input)213	}214215	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {216		(contract == &T::ContractAddress::get())217			.then(|| include_bytes!("./stubs/Collection.raw").to_vec())218	}219}220221generate_stubgen!(collection_impl, CollectionCall<()>, true);222generate_stubgen!(collection_iface, CollectionCall<()>, false);
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: d32d5104
+// Selector: 037b69c8
 contract Collection is Dummy, ERC165 {
 	// Selector: create721Collection(string,string,string) 951c0151
 	function create721Collection(
@@ -87,4 +87,15 @@
 		constOnChain;
 		dummy;
 	}
+
+	// Selector: setLimits(address,string) d05638cc
+	function setLimits(address collectionAddress, string memory limitsJson)
+		public
+		view
+	{
+		require(false, stub_error);
+		collectionAddress;
+		limitsJson;
+		dummy;
+	}
 }
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -506,6 +506,7 @@
 }
 
 #[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
 pub enum MetaUpdatePermission {
 	ItemOwner,
 	Admin,
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: d32d5104
+// Selector: 037b69c8
 interface Collection is Dummy, ERC165 {
 	// Selector: create721Collection(string,string,string) 951c0151
 	function create721Collection(
@@ -45,4 +45,9 @@
 		address collectionAddress,
 		string memory constOnChain
 	) external view;
+
+	// Selector: setLimits(address,string) d05638cc
+	function setLimits(address collectionAddress, string memory limitsJson)
+		external
+		view;
 }
modifiedtests/src/eth/collectionAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/collectionAbi.json
+++ b/tests/src/eth/collectionAbi.json
@@ -44,6 +44,20 @@
         "name": "collectionAddress",
         "type": "address"
       },
+      { "internalType": "string", "name": "limitsJson", "type": "string" }
+    ],
+    "name": "setLimits",
+    "outputs": [],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      {
+        "internalType": "address",
+        "name": "collectionAddress",
+        "type": "address"
+      },
       { "internalType": "string", "name": "shema", "type": "string" }
     ],
     "name": "setOffchainShema",
modifiedtests/src/eth/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createCollection.test.ts
+++ b/tests/src/eth/createCollection.test.ts
@@ -100,4 +100,45 @@
     const collection = (await getDetailedCollectionInfo(api, collectionId))!;
     expect(collection.constOnChainSchema.toHuman()).to.be.eq(constShema);
   });
+
+  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', '4', '4').send();
+    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+    const limits = {
+      accountTokenOwnershipLimit: 1000,
+      sponsoredDataSize: 1024,
+      // sponsoredDataRateLimit: { sponsoringDisabled: null },
+      tokenLimit: 1000000,
+      sponsorTransferTimeout: 6,
+      sponsorApproveTimeout: 6,
+      ownerCanTransfer: false,
+      ownerCanDestroy: false,
+      transfersEnabled: false,
+    };
+    const limitsJson = '{' +
+      '"account_token_ownership_limit": '+ limits.accountTokenOwnershipLimit +',' +
+      '"sponsored_data_size": ' + limits.sponsoredDataSize + ',' +
+      // '"sponsored_data_rate_limit": { sponsoringDisabled: null },' +
+      '"token_limit": ' + limits.tokenLimit + ',' +
+      '"sponsor_transfer_timeout": ' + limits.sponsorTransferTimeout + ',' +
+      '"sponsor_approve_timeout": ' + limits.sponsorApproveTimeout + ',' +
+      '"owner_can_transfer": ' + limits.ownerCanTransfer + ',' +
+      '"owner_can_destroy": ' + limits.ownerCanDestroy + ',' +
+      '"transfers_enabled": ' + limits.transfersEnabled +
+    '}';
+
+    await helper.methods.setLimits(collectionIdAddress, 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.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);
+  });
 });
\ No newline at end of file