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
1616
17import {expect} from 'chai';17import {expect} from 'chai';
18import {createCollectionExpectSuccess} from '../util/helpers';18import {createCollectionExpectSuccess} from '../util/helpers';
19import {collectionIdToAddress, createEthAccountWithBalance, GAS_ARGS, itWeb3} from './util/helpers';19import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents} from './util/helpers';
20import fungibleMetadataAbi from './fungibleMetadataAbi.json';20import fungibleMetadataAbi from './fungibleMetadataAbi.json';
21import privateKey from '../substrate/privateKey';
22import {submitTransactionAsync} from '../substrate/substrate-api';
23import nonFungibleAbi from './nonFungibleAbi.json';
2124
22describe('Common metadata', () => {25describe('Common metadata', () => {
23 itWeb3('Returns collection name', async ({api, web3}) => {26 itWeb3('Returns collection name', async ({api, web3}) => {
64 });67 });
65});68});
69
70describe('Support ERC721Metadata', () => {
71 itWeb3('Check unsupport ERC721Metadata SchemaVersion::Unique', async ({web3, api}) => {
72 const collectionId = await createCollectionExpectSuccess({
73 mode: {type: 'NFT'},
74 schemaVersion: 'Unique',
75 name: 'some_name',
76 tokenPrefix: 'some_prefix',
77 });
78 const collection = await api.rpc.unique.collectionById(collectionId);
79 expect(collection.isSome).to.be.true;
80 expect(collection.unwrap().schemaVersion.toHuman()).to.be.eq('Unique');
81
82 const alice = privateKey('//Alice');
83
84 const caller = await createEthAccountWithBalance(api, web3);
85 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: caller});
86 await submitTransactionAsync(alice, changeAdminTx);
87
88 const address = collectionIdToAddress(collectionId);
89 const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
90
91 expect(await contract.methods.name().call()).to.be.eq('some_name');
92 expect(await contract.methods.symbol().call()).to.be.eq('some_prefix');
93
94 const receiver = createEthAccount(web3);
95 const nextTokenId = await contract.methods.nextTokenId().call();
96 expect(nextTokenId).to.be.equal('1');
97 await expect(contract.methods.mintWithTokenURI(
98 receiver,
99 nextTokenId,
100 'Test URI',
101 ).call({from: caller})).to.be.rejectedWith('Unsupported schema version! Support only ImageURL');
102
103 await expect(contract.methods.mintBulkWithTokenURI(
104 receiver,
105 [
106 [nextTokenId, 'Test URI 0'],
107 [+nextTokenId + 1, 'Test URI 1'],
108 [+nextTokenId + 2, 'Test URI 2'],
109 ],
110 ).call({from: caller})).to.be.rejectedWith('Unsupported schema version! Support only ImageURL');
111 });
112
113 itWeb3('Check support ERC721Metadata for SchemaVersion::ImageURL', async ({web3, api}) => {
114 const collectionId = await createCollectionExpectSuccess({
115 mode: {type: 'NFT'},
116 name: 'some_name',
117 tokenPrefix: 'some_prefix',
118 });
119 const collection = await api.rpc.unique.collectionById(collectionId);
120 expect(collection.isSome).to.be.true;
121 expect(collection.unwrap().schemaVersion.toHuman()).to.be.eq('ImageURL');
122
123 const alice = privateKey('//Alice');
124
125 const caller = await createEthAccountWithBalance(api, web3);
126 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: caller});
127 await submitTransactionAsync(alice, changeAdminTx);
128
129 const address = collectionIdToAddress(collectionId);
130 const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
131
132 expect(await contract.methods.name().call()).to.be.eq('some_name');
133 expect(await contract.methods.symbol().call()).to.be.eq('some_prefix');
134
135 const receiver = createEthAccount(web3);
136 { // mintWithTokenURI
137 const nextTokenId = await contract.methods.nextTokenId().call();
138 expect(nextTokenId).to.be.equal('1');
139 const result = await contract.methods.mintWithTokenURI(
140 receiver,
141 nextTokenId,
142 'Test URI',
143 ).send({from: caller});
144 const events = normalizeEvents(result.events);
145
146 expect(events).to.be.deep.equal([
147 {
148 address,
149 event: 'Transfer',
150 args: {
151 from: '0x0000000000000000000000000000000000000000',
152 to: receiver,
153 tokenId: nextTokenId,
154 },
155 },
156 ]);
157
158 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
159 }
160
161 { // mintBulkWithTokenURI
162 const nextTokenId = await contract.methods.nextTokenId().call();
163 expect(nextTokenId).to.be.equal('2');
164 const result = await contract.methods.mintBulkWithTokenURI(
165 receiver,
166 [
167 [nextTokenId, 'Test URI 0'],
168 [+nextTokenId + 1, 'Test URI 1'],
169 [+nextTokenId + 2, 'Test URI 2'],
170 ],
171 ).send({from: caller});
172 const events = normalizeEvents(result.events);
173
174 expect(events).to.be.deep.equal([
175 {
176 address,
177 event: 'Transfer',
178 args: {
179 from: '0x0000000000000000000000000000000000000000',
180 to: receiver,
181 tokenId: nextTokenId,
182 },
183 },
184 {
185 address,
186 event: 'Transfer',
187 args: {
188 from: '0x0000000000000000000000000000000000000000',
189 to: receiver,
190 tokenId: String(+nextTokenId + 1),
191 },
192 },
193 {
194 address,
195 event: 'Transfer',
196 args: {
197 from: '0x0000000000000000000000000000000000000000',
198 to: receiver,
199 tokenId: String(+nextTokenId + 2),
200 },
201 },
202 ]);
203
204 expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI 0');
205 expect(await contract.methods.tokenURI(+nextTokenId + 1).call()).to.be.equal('Test URI 1');
206 expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');
207 }
208 });
209});
210
211
modifiedtests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth
--- a/tests/src/setConstOnChainSchema.test.ts
+++ b/tests/src/setConstOnChainSchema.test.ts
@@ -32,16 +32,16 @@
 
 let alice: IKeyringPair;
 let bob: IKeyringPair;
-let shema: any;
-let largeShema: any;
+let schema: any;
+let largeSchema: any;
 
 before(async () => {
   await usingApi(async () => {
     const keyring = new Keyring({type: 'sr25519'});
     alice = keyring.addFromUri('//Alice');
     bob = keyring.addFromUri('//Bob');
-    shema = '0x31';
-    largeShema = new Array(1024 * 1024 + 10).fill(0xff);
+    schema = '0x31';
+    largeSchema = new Array(1024 * 1024 + 10).fill(0xff);
   });
 });
 describe('Integration Test ext. setConstOnChainSchema()', () => {
@@ -51,8 +51,8 @@
       const collectionId = await createCollectionExpectSuccess();
       const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.eq(alice.address);
-      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);
-      await submitTransactionAsync(alice, setShema);
+      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
+      await submitTransactionAsync(alice, setSchema);
     });
   });
 
@@ -62,18 +62,18 @@
       const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.eq(alice.address);
       await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
-      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);
-      await submitTransactionAsync(bob, setShema);
+      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
+      await submitTransactionAsync(bob, setSchema);
     });
   });
 
   it('Checking collection data using the ConstOnChainSchema parameter', async () => {
     await usingApi(async (api) => {
       const collectionId = await createCollectionExpectSuccess();
-      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);
-      await submitTransactionAsync(alice, setShema);
+      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
+      await submitTransactionAsync(alice, setSchema);
       const collection = await queryCollectionExpectSuccess(api, collectionId);
-      expect(collection.constOnChainSchema.toString()).to.be.eq(shema);
+      expect(collection.constOnChainSchema.toString()).to.be.eq(schema);
     });
   });
 });
@@ -84,8 +84,8 @@
     await usingApi(async (api) => {
       // tslint:disable-next-line: radix
       const collectionId = await getCreatedCollectionCount(api) + 1;
-      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);
-      await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;
+      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
+      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
     });
   });
 
@@ -93,16 +93,16 @@
     await usingApi(async (api) => {
       const collectionId = await createCollectionExpectSuccess();
       await destroyCollectionExpectSuccess(collectionId);
-      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);
-      await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;
+      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
+      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
     });
   });
 
   it('Set invalid data in schema (size too large:> 1MB)', async () => {
     await usingApi(async (api) => {
       const collectionId = await createCollectionExpectSuccess();
-      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, largeShema);
-      await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;
+      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, largeSchema);
+      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
     });
   });
 
@@ -111,8 +111,8 @@
       const collectionId = await createCollectionExpectSuccess();
       const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.eq(alice.address);
-      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);
-      await expect(submitTransactionExpectFailAsync(bob, setShema)).to.be.rejected;
+      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
+      await expect(submitTransactionExpectFailAsync(bob, setSchema)).to.be.rejected;
     });
   });
 
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);