git.delta.rocks / unique-network / refs/commits / 1ada10d29826

difftreelog

added tests for `createRTCollection` , refactor `Unique` pallet code

PraetorP2022-10-24parent: #ac8dcbb.patch.diff
in: master

9 files changed

modifiedpallets/unique/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/unique/CHANGELOG.md
+++ b/pallets/unique/CHANGELOG.md
@@ -8,7 +8,7 @@
 
 ### Changes
 
-- Addded **CollectionHelpers** method `destroyCollection`.
+- Added `destroyCollection` and `createFTCollection` methods to **CollectionHelpers**.
 
 ## [v0.2.0] 2022-09-13
 
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -18,7 +18,7 @@
 
 use core::marker::PhantomData;
 use ethereum as _;
-use evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};
+use evm_coder::{execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
 use frame_support::traits::Get;
 
 use crate::Pallet;
@@ -27,23 +27,24 @@
 	CollectionById,
 	dispatch::CollectionDispatch,
 	erc::{
+		static_property::key,
 		CollectionHelpersEvents,
-		static_property::{key},
 	},
 	Pallet as PalletCommon,
+	
 };
+use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
 use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder, WithRecorder};
-use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
 use sp_std::vec;
 use up_data_structs::{
-	CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,
-	CollectionMode, PropertyValue,
+	CollectionDescription, CollectionMode, CollectionName, CollectionTokenPrefix,
+	CreateCollectionData, PropertyValue,
 };
 
-use crate::{Config, SelfWeightOf, weights::WeightInfo};
+use crate::{weights::WeightInfo, Config, SelfWeightOf};
 
-use sp_std::vec::Vec;
 use alloc::format;
+use sp_std::vec::Vec;
 
 /// See [`CollectionHelpersCall`]
 pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);
@@ -104,6 +105,7 @@
 	)
 }
 
+#[inline(always)]
 fn create_collection_internal<T: Config>(
 	caller: caller,
 	value: value,
@@ -212,7 +214,14 @@
 		description: string,
 		token_prefix: string,
 	) -> Result<address> {
-		self.create_nft_collection(caller, value, name, description, token_prefix)
+		create_collection_internal::<T>(
+			caller,
+			value,
+			name,
+			CollectionMode::NFT,
+			description,
+			token_prefix,
+		)
 	}
 
 	#[weight(<SelfWeightOf<T>>::create_collection())]
@@ -225,11 +234,39 @@
 		description: string,
 		token_prefix: string,
 	) -> Result<address> {
-		create_refungible_collection_internal::<T>(caller, value, name, description, token_prefix)
+		create_collection_internal::<T>(
+			caller,
+			value,
+			name,
+			CollectionMode::ReFungible,
+			description,
+			token_prefix,
+		)
+	}
+
+	#[weight(<SelfWeightOf<T>>::create_collection())]
+	#[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]
+	fn create_refungible_collection_with_properties(
+		&mut self,
+		caller: caller,
+		value: value,
+		name: string,
+		description: string,
+		token_prefix: string,
+		base_uri: string,
+	) -> Result<address> {
+		create_collection_internal::<T>(
+			caller,
+			value,
+			name,
+			CollectionMode::ReFungible,
+			description,
+			token_prefix,
+		)
 	}
 
 	#[weight(<SelfWeightOf<T>>::create_collection())]
-	#[solidity(rename_selector = "createRTCollection")]
+	#[solidity(rename_selector = "createFTCollection")]
 	fn create_fungible_collection(
 		&mut self,
 		caller: caller,
modifiedpallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth
--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -24,7 +24,7 @@
 }
 
 /// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0xa2c196ab
+/// @dev the ERC-165 identifier for this interface is 0xd8b36039
 contract CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
 	/// Create an NFT collection
 	/// @param name Name of the collection
@@ -77,9 +77,26 @@
 		return 0x0000000000000000000000000000000000000000;
 	}
 
-	/// @dev EVM selector for this function is: 0xac1e2285,
-	///  or in textual repr: createRTCollection(string,uint8,string,string)
-	function createRTCollection(
+	/// @dev EVM selector for this function is: 0xa5596388,
+	///  or in textual repr: createERC721MetadataCompatibleRFTCollection(string,string,string,string)
+	function createERC721MetadataCompatibleRFTCollection(
+		string memory name,
+		string memory description,
+		string memory tokenPrefix,
+		string memory baseUri
+	) public payable returns (address) {
+		require(false, stub_error);
+		name;
+		description;
+		tokenPrefix;
+		baseUri;
+		dummy = 0;
+		return 0x0000000000000000000000000000000000000000;
+	}
+
+	/// @dev EVM selector for this function is: 0x7335b79f,
+	///  or in textual repr: createFTCollection(string,uint8,string,string)
+	function createFTCollection(
 		string memory name,
 		uint8 decimals,
 		string memory description,
modifiedtests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth
--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -19,7 +19,7 @@
 }
 
 /// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0xa2c196ab
+/// @dev the ERC-165 identifier for this interface is 0xd8b36039
 interface CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
 	/// Create an NFT collection
 	/// @param name Name of the collection
@@ -51,9 +51,18 @@
 		string memory tokenPrefix
 	) external payable returns (address);
 
-	/// @dev EVM selector for this function is: 0xac1e2285,
-	///  or in textual repr: createRTCollection(string,uint8,string,string)
-	function createRTCollection(
+	/// @dev EVM selector for this function is: 0xa5596388,
+	///  or in textual repr: createERC721MetadataCompatibleRFTCollection(string,string,string,string)
+	function createERC721MetadataCompatibleRFTCollection(
+		string memory name,
+		string memory description,
+		string memory tokenPrefix,
+		string memory baseUri
+	) external payable returns (address);
+
+	/// @dev EVM selector for this function is: 0x7335b79f,
+	///  or in textual repr: createFTCollection(string,uint8,string,string)
+	function createFTCollection(
 		string memory name,
 		uint8 decimals,
 		string memory description,
modifiedtests/src/eth/collectionHelpersAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/collectionHelpersAbi.json
+++ b/tests/src/eth/collectionHelpersAbi.json
@@ -42,9 +42,22 @@
     "inputs": [
       { "internalType": "string", "name": "name", "type": "string" },
       { "internalType": "string", "name": "description", "type": "string" },
+      { "internalType": "string", "name": "tokenPrefix", "type": "string" },
+      { "internalType": "string", "name": "baseUri", "type": "string" }
+    ],
+    "name": "createERC721MetadataCompatibleRFTCollection",
+    "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+    "stateMutability": "payable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "string", "name": "name", "type": "string" },
+      { "internalType": "uint8", "name": "decimals", "type": "uint8" },
+      { "internalType": "string", "name": "description", "type": "string" },
       { "internalType": "string", "name": "tokenPrefix", "type": "string" }
     ],
-    "name": "createNFTCollection",
+    "name": "createFTCollection",
     "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
     "stateMutability": "payable",
     "type": "function"
@@ -55,7 +68,7 @@
       { "internalType": "string", "name": "description", "type": "string" },
       { "internalType": "string", "name": "tokenPrefix", "type": "string" }
     ],
-    "name": "createRFTCollection",
+    "name": "createNFTCollection",
     "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
     "stateMutability": "payable",
     "type": "function"
@@ -63,11 +76,10 @@
   {
     "inputs": [
       { "internalType": "string", "name": "name", "type": "string" },
-      { "internalType": "uint8", "name": "decimals", "type": "uint8" },
       { "internalType": "string", "name": "description", "type": "string" },
       { "internalType": "string", "name": "tokenPrefix", "type": "string" }
     ],
-    "name": "createRTCollection",
+    "name": "createRFTCollection",
     "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
     "stateMutability": "payable",
     "type": "function"
modifiedtests/src/eth/createFTCollection.test.tsdiffbeforeafterboth
after · tests/src/eth/createFTCollection.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 {IKeyringPair} from '@polkadot/types/types';18import { evmToAddress } from '@polkadot/util-crypto';19import {Pallets, requirePalletsOrSkip} from '../util';20import {expect, itEth, usingEthPlaygrounds} from './util';2122const DECIMALS = 18;2324describe('Create FT collection from EVM', () => {25  let donor: IKeyringPair;2627  before(async function() {28    await usingEthPlaygrounds(async (helper, privateKey) => {29      requirePalletsOrSkip(this, helper, [Pallets.Fungible]);30      donor = await privateKey('//Alice');31    });32  });3334  itEth('Create collection', async ({helper}) => {35    const owner = await helper.eth.createAccountWithBalance(donor);36    37    const name = 'CollectionEVM';38    const description = 'Some description';39    const prefix = 'token prefix';40  41    // todo:playgrounds this might fail when in async environment.42    const collectionCountBefore = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;4344    const {collectionId} = await helper.eth.createFungibleCollection(owner, name, DECIMALS, description, prefix);45    46    const collectionCountAfter = +(await helper.callRpc('api.rpc.unique.collectionStats')).created;47    const data = (await helper.ft.getData(collectionId))!;4849    expect(collectionCountAfter - collectionCountBefore).to.be.eq(1);50    expect(collectionId).to.be.eq(collectionCountAfter);51    expect(data.name).to.be.eq(name);52    expect(data.description).to.be.eq(description);53    expect(data.raw.tokenPrefix).to.be.eq(prefix);54    expect(data.raw.mode).to.be.deep.eq({Fungible: DECIMALS.toString()});55  });5657  // todo:playgrounds this test will fail when in async environment.58  itEth('Check collection address exist', async ({helper}) => {59    const owner = await helper.eth.createAccountWithBalance(donor);6061    const expectedCollectionId = +(await helper.callRpc('api.rpc.unique.collectionStats')).created + 1;62    const expectedCollectionAddress = helper.ethAddress.fromCollectionId(expectedCollectionId);63    const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);6465    expect(await collectionHelpers.methods66      .isCollectionExist(expectedCollectionAddress)67      .call()).to.be.false;6869    70    await helper.eth.createFungibleCollection(owner, 'A', DECIMALS, 'A', 'A');7172    73    expect(await collectionHelpers.methods74      .isCollectionExist(expectedCollectionAddress)75      .call()).to.be.true;76  });77  78  itEth('Set sponsorship', async ({helper}) => {79    const owner = await helper.eth.createAccountWithBalance(donor);80    const sponsor = await helper.eth.createAccountWithBalance(donor);81    const ss58Format = helper.chain.getChainProperties().ss58Format;82    const {collectionId, collectionAddress} = await helper.eth.createFungibleCollection(owner, 'Sponsor', DECIMALS, 'absolutely anything', 'ENVY');8384    const collection = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);85    await collection.methods.setCollectionSponsor(sponsor).send();8687    let data = (await helper.rft.getData(collectionId))!;88    expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));8990    await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');9192    const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor);93    await sponsorCollection.methods.confirmCollectionSponsorship().send();9495    data = (await helper.rft.getData(collectionId))!;96    expect(data.raw.sponsorship.Confirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));97  });9899  itEth('Set limits', async ({helper}) => {100    const owner = await helper.eth.createAccountWithBalance(donor);101    const {collectionId, collectionAddress} = await helper.eth.createFungibleCollection(owner, 'Limits', DECIMALS, 'absolutely anything', 'INSI');102    const limits = {103      accountTokenOwnershipLimit: 1000,104      sponsoredDataSize: 1024,105      sponsoredDataRateLimit: 30,106      tokenLimit: 1000000,107      sponsorTransferTimeout: 6,108      sponsorApproveTimeout: 6,109      ownerCanTransfer: false,110      ownerCanDestroy: false,111      transfersEnabled: false,112    };113114    const collection = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);115    await collection.methods['setCollectionLimit(string,uint32)']('accountTokenOwnershipLimit', limits.accountTokenOwnershipLimit).send();116    await collection.methods['setCollectionLimit(string,uint32)']('sponsoredDataSize', limits.sponsoredDataSize).send();117    await collection.methods['setCollectionLimit(string,uint32)']('sponsoredDataRateLimit', limits.sponsoredDataRateLimit).send();118    await collection.methods['setCollectionLimit(string,uint32)']('tokenLimit', limits.tokenLimit).send();119    await collection.methods['setCollectionLimit(string,uint32)']('sponsorTransferTimeout', limits.sponsorTransferTimeout).send();120    await collection.methods['setCollectionLimit(string,uint32)']('sponsorApproveTimeout', limits.sponsorApproveTimeout).send();121    await collection.methods['setCollectionLimit(string,bool)']('ownerCanTransfer', limits.ownerCanTransfer).send();122    await collection.methods['setCollectionLimit(string,bool)']('ownerCanDestroy', limits.ownerCanDestroy).send();123    await collection.methods['setCollectionLimit(string,bool)']('transfersEnabled', limits.transfersEnabled).send();124    125    const data = (await helper.rft.getData(collectionId))!;126    expect(data.raw.limits.accountTokenOwnershipLimit).to.be.eq(limits.accountTokenOwnershipLimit);127    expect(data.raw.limits.sponsoredDataSize).to.be.eq(limits.sponsoredDataSize);128    expect(data.raw.limits.sponsoredDataRateLimit.blocks).to.be.eq(limits.sponsoredDataRateLimit);129    expect(data.raw.limits.tokenLimit).to.be.eq(limits.tokenLimit);130    expect(data.raw.limits.sponsorTransferTimeout).to.be.eq(limits.sponsorTransferTimeout);131    expect(data.raw.limits.sponsorApproveTimeout).to.be.eq(limits.sponsorApproveTimeout);132    expect(data.raw.limits.ownerCanTransfer).to.be.eq(limits.ownerCanTransfer);133    expect(data.raw.limits.ownerCanDestroy).to.be.eq(limits.ownerCanDestroy);134    expect(data.raw.limits.transfersEnabled).to.be.eq(limits.transfersEnabled);135  });136137  itEth('Collection address exist', async ({helper}) => {138    const owner = await helper.eth.createAccountWithBalance(donor);139    const collectionAddressForNonexistentCollection = '0x17C4E6453CC49AAAAEACA894E6D9683E00112233';140    expect(await helper.ethNativeContract.collectionHelpers(collectionAddressForNonexistentCollection)141      .methods.isCollectionExist(collectionAddressForNonexistentCollection).call())142      .to.be.false;143    144    const {collectionAddress} = await helper.eth.createFungibleCollection(owner, 'Exister', DECIMALS, 'absolutely anything', 'WIWT');145    expect(await helper.ethNativeContract.collectionHelpers(collectionAddress)146      .methods.isCollectionExist(collectionAddress).call())147      .to.be.true;148  });149  150  itEth('destroyCollection', async ({helper}) => {151    const owner = await helper.eth.createAccountWithBalance(donor);152    const {collectionAddress} = await helper.eth.createFungibleCollection(owner, 'Exister', DECIMALS, 'absolutely anything', 'WIWT');153    const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);154155    const result = await collectionHelper.methods156      .destroyCollection(collectionAddress)157      .send({from: owner});158159    const events = helper.eth.normalizeEvents(result.events);160    161    expect(events).to.be.deep.equal([162      {163        address: collectionHelper.options.address,164        event: 'CollectionDestroyed',165        args: {166          collectionId: collectionAddress,167        },168      },169    ]);170171    expect(await collectionHelper.methods172      .isCollectionExist(collectionAddress)173      .call()).to.be.false;174  });175});176177describe('(!negative tests!) Create FT collection from EVM', () => {178  let donor: IKeyringPair;179  let nominal: bigint;180181  before(async function() {182    await usingEthPlaygrounds(async (helper, privateKey) => {183      requirePalletsOrSkip(this, helper, [Pallets.Fungible]);184      donor = await privateKey('//Alice');185      nominal = helper.balance.getOneTokenNominal();186    });187  });188189  itEth('(!negative test!) Create collection (bad lengths)', async ({helper}) => {190    const owner = await helper.eth.createAccountWithBalance(donor);191    const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);192    {193      const MAX_NAME_LENGTH = 64;194      const collectionName = 'A'.repeat(MAX_NAME_LENGTH + 1);195      const description = 'A';196      const tokenPrefix = 'A';197198      await expect(collectionHelper.methods199        .createFTCollection(collectionName, DECIMALS, description, tokenPrefix)200        .call({value: Number(2n * nominal)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);201    }202    {203      const MAX_DESCRIPTION_LENGTH = 256;204      const collectionName = 'A';205      const description = 'A'.repeat(MAX_DESCRIPTION_LENGTH + 1);206      const tokenPrefix = 'A';207      await expect(collectionHelper.methods208        .createFTCollection(collectionName, DECIMALS, description, tokenPrefix)209        .call({value: Number(2n * nominal)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);210    }211    {212      const MAX_TOKEN_PREFIX_LENGTH = 16;213      const collectionName = 'A';214      const description = 'A';215      const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGTH + 1);216      await expect(collectionHelper.methods217        .createFTCollection(collectionName, DECIMALS, description, tokenPrefix)218        .call({value: Number(2n * nominal)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);219    }220  });221  222  itEth('(!negative test!) Create collection (no funds)', async ({helper}) => {223    const owner = await helper.eth.createAccountWithBalance(donor);224    const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);225    await expect(collectionHelper.methods226      .createFTCollection('Peasantry', DECIMALS, 'absolutely anything', 'TWIW')227      .call({value: Number(1n * nominal)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');228  });229230  itEth('(!negative test!) Check owner', async ({helper}) => {231    const owner = await helper.eth.createAccountWithBalance(donor);232    const peasant = helper.eth.createAccount();233    const {collectionAddress} = await helper.eth.createFungibleCollection(owner, 'Transgressed', DECIMALS, 'absolutely anything', 'YVNE');234    const peasantCollection = helper.ethNativeContract.collection(collectionAddress, 'ft', peasant);235    const EXPECTED_ERROR = 'NoPermission';236    {237      const sponsor = await helper.eth.createAccountWithBalance(donor);238      await expect(peasantCollection.methods239        .setCollectionSponsor(sponsor)240        .call()).to.be.rejectedWith(EXPECTED_ERROR);241      242      const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'ft', sponsor);243      await expect(sponsorCollection.methods244        .confirmCollectionSponsorship()245        .call()).to.be.rejectedWith('caller is not set as sponsor');246    }247    {248      await expect(peasantCollection.methods249        .setCollectionLimit('account_token_ownership_limit', '1000')250        .call()).to.be.rejectedWith(EXPECTED_ERROR);251    }252  });253254  itEth('(!negative test!) Set limits', async ({helper}) => {255    const owner = await helper.eth.createAccountWithBalance(donor);256    const {collectionAddress} = await helper.eth.createFungibleCollection(owner, 'Limits', DECIMALS, 'absolutely anything', 'ISNI');257    const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);258    await expect(collectionEvm.methods259      .setCollectionLimit('badLimit', 'true')260      .call()).to.be.rejectedWith('unknown boolean limit "badLimit"');261  });262});
modifiedtests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -264,7 +264,7 @@
       .call()).to.be.rejectedWith('unknown boolean limit "badLimit"');
   });
   
-  itEth('destroyCollection test', async ({helper}) => {
+  itEth('destroyCollection', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const {collectionAddress} = await helper.eth.createRFTCollection(owner, 'Limits', 'absolutely anything', 'OLF');
     const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -210,8 +210,7 @@
     const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();
     const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
         
-    const result = await collectionHelper.methods.createRTCollection(name, decimals, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
-
+    const result = await collectionHelper.methods.createFTCollection(name, decimals, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
     const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
     const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);