git.delta.rocks / unique-network / refs/commits / 02783a223963

difftreelog

Merge pull request #336 from UniqueNetwork/feature/CORE-325

kozyrevdev2022-04-21parents: #23e7e86 #447d08b.patch.diff
in: master
Feature/core-325

5 files changed

modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -14,13 +14,14 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
+extern crate alloc;
 use core::{
 	char::{REPLACEMENT_CHARACTER, decode_utf16},
 	convert::TryInto,
 };
 use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
 use frame_support::BoundedVec;
-use up_data_structs::TokenId;
+use up_data_structs::{TokenId, SchemaVersion};
 use pallet_evm_coder_substrate::dispatch_to_evm;
 use sp_core::{H160, U256};
 use sp_std::{vec::Vec, vec};
@@ -35,6 +36,15 @@
 	SelfWeightOf, weights::WeightInfo,
 };
 
+fn error_unsupported_schema_version() -> Error {
+	alloc::format!(
+		"Unsupported schema version! Support only {:?}",
+		SchemaVersion::ImageURL
+	)
+	.as_str()
+	.into()
+}
+
 #[derive(ToLog)]
 pub enum ERC721Events {
 	Transfer {
@@ -76,6 +86,7 @@
 			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
 			.collect::<string>())
 	}
+
 	fn symbol(&self) -> Result<string> {
 		Ok(string::from_utf8_lossy(&self.token_prefix).into())
 	}
@@ -83,6 +94,10 @@
 	/// Returns token's const_metadata
 	#[solidity(rename_selector = "tokenURI")]
 	fn token_uri(&self, token_id: uint256) -> Result<string> {
+		if !matches!(self.schema_version, SchemaVersion::ImageURL) {
+			return Err(error_unsupported_schema_version());
+		}
+
 		self.consume_store_reads(1)?;
 		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
 		Ok(string::from_utf8_lossy(
@@ -270,6 +285,10 @@
 		token_id: uint256,
 		token_uri: string,
 	) -> Result<bool> {
+		if !matches!(self.schema_version, SchemaVersion::ImageURL) {
+			return Err(error_unsupported_schema_version());
+		}
+
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
 		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;
@@ -411,6 +430,10 @@
 		to: address,
 		tokens: Vec<(uint256, string)>,
 	) -> Result<bool> {
+		if !matches!(self.schema_version, SchemaVersion::ImageURL) {
+			return Err(error_unsupported_schema_version());
+		}
+
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
 		let mut expected_index = <TokensMinted<T>>::get(self.id)
modifiedtests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -1,19 +1,16 @@
 import privateKey from '../substrate/privateKey';
 import {addToAllowListExpectSuccess, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, setCollectionSponsorExpectSuccess} from '../util/helpers';
-import {itWeb3, transferBalanceToEth, subToEth, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents} from './util/helpers';
+import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents} from './util/helpers';
 import nonFungibleAbi from './nonFungibleAbi.json';
 import {expect} from 'chai';
 
 describe('evm collection sponsoring', () => {
-  itWeb3('sponsors mint transactions', async ({api, web3}) => {
+  itWeb3('sponsors mint transactions', async ({web3}) => {
     const alice = privateKey('//Alice');
 
     const collection = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collection, alice.address);
     await confirmSponsorshipExpectSuccess(collection);
-
-    // Wouldn't be needed after CORE-300
-    await transferBalanceToEth(api, alice, subToEth(alice.address));
 
     const minter = createEthAccount(web3);
     expect(await web3.eth.getBalance(minter)).to.equal('0');
modifiedtests/src/eth/metadata.test.tsdiffbeforeafterboth
--- a/tests/src/eth/metadata.test.ts
+++ b/tests/src/eth/metadata.test.ts
@@ -16,8 +16,11 @@
 
 import {expect} from 'chai';
 import {createCollectionExpectSuccess} from '../util/helpers';
-import {collectionIdToAddress, createEthAccountWithBalance, GAS_ARGS, itWeb3} from './util/helpers';
+import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents} from './util/helpers';
 import fungibleMetadataAbi from './fungibleMetadataAbi.json';
+import privateKey from '../substrate/privateKey';
+import {submitTransactionAsync} from '../substrate/substrate-api';
+import nonFungibleAbi from './nonFungibleAbi.json';
 
 describe('Common metadata', () => {
   itWeb3('Returns collection name', async ({api, web3}) => {
@@ -62,4 +65,146 @@
 
     expect(+decimals).to.equal(6);
   });
-});
\ No newline at end of file
+});
+
+describe('Support ERC721Metadata', () => {
+  itWeb3('Check unsupport ERC721Metadata SchemaVersion::Unique', async ({web3, api}) => {
+    const collectionId = await createCollectionExpectSuccess({
+      mode: {type: 'NFT'},
+      schemaVersion: 'Unique',
+      name: 'some_name',
+      tokenPrefix: 'some_prefix',
+    });
+    const collection = await api.rpc.unique.collectionById(collectionId);
+    expect(collection.isSome).to.be.true;
+    expect(collection.unwrap().schemaVersion.toHuman()).to.be.eq('Unique');
+
+    const alice = privateKey('//Alice');
+
+    const caller = await createEthAccountWithBalance(api, web3);
+    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: caller});
+    await submitTransactionAsync(alice, changeAdminTx);
+
+    const address = collectionIdToAddress(collectionId);
+    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+
+    expect(await contract.methods.name().call()).to.be.eq('some_name');
+    expect(await contract.methods.symbol().call()).to.be.eq('some_prefix');
+
+    const receiver = createEthAccount(web3);
+    const nextTokenId = await contract.methods.nextTokenId().call();
+    expect(nextTokenId).to.be.equal('1');
+    await expect(contract.methods.mintWithTokenURI(
+      receiver,
+      nextTokenId,
+      'Test URI',
+    ).call({from: caller})).to.be.rejectedWith('Unsupported schema version! Support only ImageURL');
+
+    await expect(contract.methods.mintBulkWithTokenURI(
+      receiver,
+      [
+        [nextTokenId, 'Test URI 0'],
+        [+nextTokenId + 1, 'Test URI 1'],
+        [+nextTokenId + 2, 'Test URI 2'],
+      ],
+    ).call({from: caller})).to.be.rejectedWith('Unsupported schema version! Support only ImageURL');
+  });
+
+  itWeb3('Check support ERC721Metadata for SchemaVersion::ImageURL', async ({web3, api}) => {
+    const collectionId = await createCollectionExpectSuccess({
+      mode: {type: 'NFT'},
+      name: 'some_name',
+      tokenPrefix: 'some_prefix',
+    });
+    const collection = await api.rpc.unique.collectionById(collectionId);
+    expect(collection.isSome).to.be.true;
+    expect(collection.unwrap().schemaVersion.toHuman()).to.be.eq('ImageURL');
+
+    const alice = privateKey('//Alice');
+
+    const caller = await createEthAccountWithBalance(api, web3);
+    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: caller});
+    await submitTransactionAsync(alice, changeAdminTx);
+
+    const address = collectionIdToAddress(collectionId);
+    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+    
+    expect(await contract.methods.name().call()).to.be.eq('some_name');
+    expect(await contract.methods.symbol().call()).to.be.eq('some_prefix');
+
+    const receiver = createEthAccount(web3);
+    { // mintWithTokenURI
+      const nextTokenId = await contract.methods.nextTokenId().call();
+      expect(nextTokenId).to.be.equal('1');
+      const result = await contract.methods.mintWithTokenURI(
+        receiver,
+        nextTokenId,
+        'Test URI',
+      ).send({from: caller});
+      const events = normalizeEvents(result.events);
+  
+      expect(events).to.be.deep.equal([
+        {
+          address,
+          event: 'Transfer',
+          args: {
+            from: '0x0000000000000000000000000000000000000000',
+            to: receiver,
+            tokenId: nextTokenId,
+          },
+        },
+      ]);
+  
+      expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+    }
+
+    { // mintBulkWithTokenURI
+      const nextTokenId = await contract.methods.nextTokenId().call();
+      expect(nextTokenId).to.be.equal('2');
+      const result = await contract.methods.mintBulkWithTokenURI(
+        receiver,
+        [
+          [nextTokenId, 'Test URI 0'],
+          [+nextTokenId + 1, 'Test URI 1'],
+          [+nextTokenId + 2, 'Test URI 2'],
+        ],
+      ).send({from: caller});
+      const events = normalizeEvents(result.events);
+
+      expect(events).to.be.deep.equal([
+        {
+          address,
+          event: 'Transfer',
+          args: {
+            from: '0x0000000000000000000000000000000000000000',
+            to: receiver,
+            tokenId: nextTokenId,
+          },
+        },
+        {
+          address,
+          event: 'Transfer',
+          args: {
+            from: '0x0000000000000000000000000000000000000000',
+            to: receiver,
+            tokenId: String(+nextTokenId + 1),
+          },
+        },
+        {
+          address,
+          event: 'Transfer',
+          args: {
+            from: '0x0000000000000000000000000000000000000000',
+            to: receiver,
+            tokenId: String(+nextTokenId + 2),
+          },
+        },
+      ]);
+
+      expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI 0');
+      expect(await contract.methods.tokenURI(+nextTokenId + 1).call()).to.be.equal('Test URI 1');
+      expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');
+    }
+  });
+});
+
modifiedtests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth
before · tests/src/setConstOnChainSchema.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.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/>.1617import {Keyring} from '@polkadot/api';18import {IKeyringPair} from '@polkadot/types/types';19import chai from 'chai';20import chaiAsPromised from 'chai-as-promised';21import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';22import {23  createCollectionExpectSuccess,24  destroyCollectionExpectSuccess,25  addCollectionAdminExpectSuccess,26  queryCollectionExpectSuccess,27  getCreatedCollectionCount,28} from './util/helpers';2930chai.use(chaiAsPromised);31const expect = chai.expect;3233let alice: IKeyringPair;34let bob: IKeyringPair;35let shema: any;36let largeShema: any;3738before(async () => {39  await usingApi(async () => {40    const keyring = new Keyring({type: 'sr25519'});41    alice = keyring.addFromUri('//Alice');42    bob = keyring.addFromUri('//Bob');43    shema = '0x31';44    largeShema = new Array(1024 * 1024 + 10).fill(0xff);45  });46});47describe('Integration Test ext. setConstOnChainSchema()', () => {4849  it('Run extrinsic with parameters of the collection id, set the scheme', async () => {50    await usingApi(async (api) => {51      const collectionId = await createCollectionExpectSuccess();52      const collection = await queryCollectionExpectSuccess(api, collectionId);53      expect(collection.owner.toString()).to.be.eq(alice.address);54      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);55      await submitTransactionAsync(alice, setShema);56    });57  });5859  it('Collection admin can set the scheme', async () => {60    await usingApi(async (api) => {61      const collectionId = await createCollectionExpectSuccess();62      const collection = await queryCollectionExpectSuccess(api, collectionId);63      expect(collection.owner.toString()).to.be.eq(alice.address);64      await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);65      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);66      await submitTransactionAsync(bob, setShema);67    });68  });6970  it('Checking collection data using the ConstOnChainSchema parameter', async () => {71    await usingApi(async (api) => {72      const collectionId = await createCollectionExpectSuccess();73      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);74      await submitTransactionAsync(alice, setShema);75      const collection = await queryCollectionExpectSuccess(api, collectionId);76      expect(collection.constOnChainSchema.toString()).to.be.eq(shema);77    });78  });79});8081describe('Negative Integration Test ext. setConstOnChainSchema()', () => {8283  it('Set a non-existent collection', async () => {84    await usingApi(async (api) => {85      // tslint:disable-next-line: radix86      const collectionId = await getCreatedCollectionCount(api) + 1;87      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);88      await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;89    });90  });9192  it('Set a previously deleted collection', async () => {93    await usingApi(async (api) => {94      const collectionId = await createCollectionExpectSuccess();95      await destroyCollectionExpectSuccess(collectionId);96      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);97      await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;98    });99  });100101  it('Set invalid data in schema (size too large:> 1MB)', async () => {102    await usingApi(async (api) => {103      const collectionId = await createCollectionExpectSuccess();104      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, largeShema);105      await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;106    });107  });108109  it('Execute method not on behalf of the collection owner', async () => {110    await usingApi(async (api) => {111      const collectionId = await createCollectionExpectSuccess();112      const collection = await queryCollectionExpectSuccess(api, collectionId);113      expect(collection.owner.toString()).to.be.eq(alice.address);114      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);115      await expect(submitTransactionExpectFailAsync(bob, setShema)).to.be.rejected;116    });117  });118119});
after · tests/src/setConstOnChainSchema.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.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/>.1617import {Keyring} from '@polkadot/api';18import {IKeyringPair} from '@polkadot/types/types';19import chai from 'chai';20import chaiAsPromised from 'chai-as-promised';21import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';22import {23  createCollectionExpectSuccess,24  destroyCollectionExpectSuccess,25  addCollectionAdminExpectSuccess,26  queryCollectionExpectSuccess,27  getCreatedCollectionCount,28} from './util/helpers';2930chai.use(chaiAsPromised);31const expect = chai.expect;3233let alice: IKeyringPair;34let bob: IKeyringPair;35let schema: any;36let largeSchema: any;3738before(async () => {39  await usingApi(async () => {40    const keyring = new Keyring({type: 'sr25519'});41    alice = keyring.addFromUri('//Alice');42    bob = keyring.addFromUri('//Bob');43    schema = '0x31';44    largeSchema = new Array(1024 * 1024 + 10).fill(0xff);45  });46});47describe('Integration Test ext. setConstOnChainSchema()', () => {4849  it('Run extrinsic with parameters of the collection id, set the scheme', async () => {50    await usingApi(async (api) => {51      const collectionId = await createCollectionExpectSuccess();52      const collection = await queryCollectionExpectSuccess(api, collectionId);53      expect(collection.owner.toString()).to.be.eq(alice.address);54      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);55      await submitTransactionAsync(alice, setSchema);56    });57  });5859  it('Collection admin can set the scheme', async () => {60    await usingApi(async (api) => {61      const collectionId = await createCollectionExpectSuccess();62      const collection = await queryCollectionExpectSuccess(api, collectionId);63      expect(collection.owner.toString()).to.be.eq(alice.address);64      await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);65      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);66      await submitTransactionAsync(bob, setSchema);67    });68  });6970  it('Checking collection data using the ConstOnChainSchema parameter', async () => {71    await usingApi(async (api) => {72      const collectionId = await createCollectionExpectSuccess();73      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);74      await submitTransactionAsync(alice, setSchema);75      const collection = await queryCollectionExpectSuccess(api, collectionId);76      expect(collection.constOnChainSchema.toString()).to.be.eq(schema);77    });78  });79});8081describe('Negative Integration Test ext. setConstOnChainSchema()', () => {8283  it('Set a non-existent collection', async () => {84    await usingApi(async (api) => {85      // tslint:disable-next-line: radix86      const collectionId = await getCreatedCollectionCount(api) + 1;87      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);88      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;89    });90  });9192  it('Set a previously deleted collection', async () => {93    await usingApi(async (api) => {94      const collectionId = await createCollectionExpectSuccess();95      await destroyCollectionExpectSuccess(collectionId);96      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);97      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;98    });99  });100101  it('Set invalid data in schema (size too large:> 1MB)', async () => {102    await usingApi(async (api) => {103      const collectionId = await createCollectionExpectSuccess();104      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, largeSchema);105      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;106    });107  });108109  it('Execute method not on behalf of the collection owner', async () => {110    await usingApi(async (api) => {111      const collectionId = await createCollectionExpectSuccess();112      const collection = await queryCollectionExpectSuccess(api, collectionId);113      expect(collection.owner.toString()).to.be.eq(alice.address);114      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);115      await expect(submitTransactionExpectFailAsync(bob, setSchema)).to.be.rejected;116    });117  });118119});
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -268,6 +268,7 @@
   name: string,
   description: string,
   tokenPrefix: string,
+  schemaVersion: string,
 };
 
 const defaultCreateCollectionParams: CreateCollectionParams = {
@@ -275,10 +276,11 @@
   mode: {type: 'NFT'},
   name: 'name',
   tokenPrefix: 'prefix',
+  schemaVersion: 'ImageURL',
 };
 
 export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {
-  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};
+  const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};
 
   let collectionId = 0;
   await usingApi(async (api) => {
@@ -297,7 +299,13 @@
       modeprm = {refungible: null};
     }
 
-    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});
+    const tx = api.tx.unique.createCollectionEx({
+      name: strToUTF16(name), 
+      description: strToUTF16(description), 
+      tokenPrefix: strToUTF16(tokenPrefix), 
+      mode: modeprm as any,
+      schemaVersion: schemaVersion,
+    });
     const events = await submitTransactionAsync(alicePrivateKey, tx);
     const result = getCreateCollectionResult(events);