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
--- a/pallets/evm-collection/src/eth.rs
+++ b/pallets/evm-collection/src/eth.rs
@@ -112,21 +112,74 @@
 	// 	Ok(())
 	// }
 
-	// fn set_offchain_shema(shema: string) -> Result<void> {
-	// 	Ok(())
-	// }
+	fn set_offchain_shema(shema: string) -> Result<void> {
+		let shema = shema
+			.into_bytes()
+			.try_into()
+			.map_err(|_| error_feild_too_long(stringify!(shema), OFFCHAIN_SCHEMA_LIMIT))?;
+		collection.offchain_schema = shema;
+		save(collection)
+	}
 
-	// fn set_const_on_chain_schema(shema: string) -> Result<void> {
-	// 	Ok(())
-	// }
+	fn confirm_sponsorship(&self, caller: caller, collection_address: address) -> Result<void> {
+		let (_, mut collection) = collection_from_address(collection_address, &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()));
+		}
+		save(collection)
+	}
 
 	// fn set_variable_on_chain_schema(shema: string) -> Result<void> {
 	// 	Ok(())
 	// }
 
-	// fn set_limits(limits: string) -> Result<void> {
-	// 	Ok(())
-	// }
+	fn set_variable_on_chain_schema(
+		&self,
+		caller: caller,
+		collection_address: address,
+		variable: string,
+	) -> Result<void> {
+		let (_, mut collection) = collection_from_address(collection_address, &self.0)?;
+		check_is_owner(caller, &collection)?;
+
+		let variable = variable.into_bytes().try_into().map_err(|_| {
+			error_feild_too_long(stringify!(variable), VARIABLE_ON_CHAIN_SCHEMA_LIMIT)
+		})?;
+		collection.variable_on_chain_schema = variable;
+		save(collection)
+	}
+
+	fn set_const_on_chain_schema(
+		&self,
+		caller: caller,
+		collection_address: address,
+		const_on_chain: string,
+	) -> Result<void> {
+		let (_, mut collection) = collection_from_address(collection_address, &self.0)?;
+		check_is_owner(caller, &collection)?;
+
+		let const_on_chain = const_on_chain.into_bytes().try_into().map_err(|_| {
+			error_feild_too_long(stringify!(const_on_chain), CONST_ON_CHAIN_SCHEMA_LIMIT)
+		})?;
+		collection.const_on_chain_schema = const_on_chain;
+		save(collection)
+	}
+
+	fn set_limits(
+		&self,
+		caller: caller,
+		collection_address: address,
+		limits_json: string,
+	) -> Result<void> {
+		let (_, mut collection) = collection_from_address(collection_address, &self.0)?;
+		check_is_owner(caller, &collection)?;
+
+		let limits = serde_json::from_str(limits_json.as_ref())
+			.map_err(|e| Error::Revert(format!("Parse JSON error: {}", e)))?;
+		collection.limits = limits;
+		save(collection)
+	}
 }
 
 fn error_feild_too_long(feild: &str, bound: u32) -> Error {
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
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    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});
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  });103104  itWeb3('Set limits', async ({api, web3}) => {105    const owner = await createEthAccountWithBalance(api, web3);106    const helper = collectionHelper(web3, owner);107    const result = await helper.methods.create721Collection('Const collection', '4', '4').send();108    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);109    const limits = {110      accountTokenOwnershipLimit: 1000,111      sponsoredDataSize: 1024,112      // sponsoredDataRateLimit: { sponsoringDisabled: null },113      tokenLimit: 1000000,114      sponsorTransferTimeout: 6,115      sponsorApproveTimeout: 6,116      ownerCanTransfer: false,117      ownerCanDestroy: false,118      transfersEnabled: false,119    };120    const limitsJson = '{' +121      '"account_token_ownership_limit": '+ limits.accountTokenOwnershipLimit +',' +122      '"sponsored_data_size": ' + limits.sponsoredDataSize + ',' +123      // '"sponsored_data_rate_limit": { sponsoringDisabled: null },' +124      '"token_limit": ' + limits.tokenLimit + ',' +125      '"sponsor_transfer_timeout": ' + limits.sponsorTransferTimeout + ',' +126      '"sponsor_approve_timeout": ' + limits.sponsorApproveTimeout + ',' +127      '"owner_can_transfer": ' + limits.ownerCanTransfer + ',' +128      '"owner_can_destroy": ' + limits.ownerCanDestroy + ',' +129      '"transfers_enabled": ' + limits.transfersEnabled +130    '}';131132    await helper.methods.setLimits(collectionIdAddress, limitsJson).send();133    134    const collection = (await getDetailedCollectionInfo(api, collectionId))!;135    expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.eq(limits.accountTokenOwnershipLimit);136    expect(collection.limits.sponsoredDataSize.unwrap().toNumber()).to.be.eq(limits.sponsoredDataSize);137    expect(collection.limits.tokenLimit.unwrap().toNumber()).to.be.eq(limits.tokenLimit);138    expect(collection.limits.sponsorTransferTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorTransferTimeout);139    expect(collection.limits.sponsorApproveTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorApproveTimeout);140    expect(collection.limits.ownerCanTransfer.toHuman()).to.be.eq(limits.ownerCanTransfer);141    expect(collection.limits.ownerCanDestroy.toHuman()).to.be.eq(limits.ownerCanDestroy);142    expect(collection.limits.transfersEnabled.toHuman()).to.be.eq(limits.transfersEnabled);143  });144});