difftreelog
Merge pull request #336 from UniqueNetwork/feature/CORE-325
in: master
Feature/core-325
5 files changed
pallets/nonfungible/src/erc.rsdiffbeforeafterboth14// You should have received a copy of the GNU General Public License14// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.161617extern crate alloc;17use core::{18use core::{18 char::{REPLACEMENT_CHARACTER, decode_utf16},19 char::{REPLACEMENT_CHARACTER, decode_utf16},19 convert::TryInto,20 convert::TryInto,20};21};21use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};22use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};22use frame_support::BoundedVec;23use frame_support::BoundedVec;23use up_data_structs::TokenId;24use up_data_structs::{TokenId, SchemaVersion};24use pallet_evm_coder_substrate::dispatch_to_evm;25use pallet_evm_coder_substrate::dispatch_to_evm;25use sp_core::{H160, U256};26use sp_core::{H160, U256};26use sp_std::{vec::Vec, vec};27use sp_std::{vec::Vec, vec};35 SelfWeightOf, weights::WeightInfo,36 SelfWeightOf, weights::WeightInfo,36};37};3839fn error_unsupported_schema_version() -> Error {40 alloc::format!(41 "Unsupported schema version! Support only {:?}",42 SchemaVersion::ImageURL43 )44 .as_str()45 .into()46}374738#[derive(ToLog)]48#[derive(ToLog)]39pub enum ERC721Events {49pub enum ERC721Events {83 /// Returns token's const_metadata94 /// Returns token's const_metadata84 #[solidity(rename_selector = "tokenURI")]95 #[solidity(rename_selector = "tokenURI")]85 fn token_uri(&self, token_id: uint256) -> Result<string> {96 fn token_uri(&self, token_id: uint256) -> Result<string> {97 if !matches!(self.schema_version, SchemaVersion::ImageURL) {98 return Err(error_unsupported_schema_version());99 }10086 self.consume_store_reads(1)?;101 self.consume_store_reads(1)?;87 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;102 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;270 token_id: uint256,285 token_id: uint256,271 token_uri: string,286 token_uri: string,272 ) -> Result<bool> {287 ) -> Result<bool> {288 if !matches!(self.schema_version, SchemaVersion::ImageURL) {289 return Err(error_unsupported_schema_version());290 }291273 let caller = T::CrossAccountId::from_eth(caller);292 let caller = T::CrossAccountId::from_eth(caller);274 let to = T::CrossAccountId::from_eth(to);293 let to = T::CrossAccountId::from_eth(to);411 to: address,430 to: address,412 tokens: Vec<(uint256, string)>,431 tokens: Vec<(uint256, string)>,413 ) -> Result<bool> {432 ) -> Result<bool> {433 if !matches!(self.schema_version, SchemaVersion::ImageURL) {434 return Err(error_unsupported_schema_version());435 }436414 let caller = T::CrossAccountId::from_eth(caller);437 let caller = T::CrossAccountId::from_eth(caller);415 let to = T::CrossAccountId::from_eth(to);438 let to = T::CrossAccountId::from_eth(to);tests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth1import privateKey from '../substrate/privateKey';1import privateKey from '../substrate/privateKey';2import {addToAllowListExpectSuccess, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, setCollectionSponsorExpectSuccess} from '../util/helpers';2import {addToAllowListExpectSuccess, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, setCollectionSponsorExpectSuccess} from '../util/helpers';3import {itWeb3, transferBalanceToEth, subToEth, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents} from './util/helpers';3import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents} from './util/helpers';4import nonFungibleAbi from './nonFungibleAbi.json';4import nonFungibleAbi from './nonFungibleAbi.json';5import {expect} from 'chai';5import {expect} from 'chai';667describe('evm collection sponsoring', () => {7describe('evm collection sponsoring', () => {8 itWeb3('sponsors mint transactions', async ({api, web3}) => {8 itWeb3('sponsors mint transactions', async ({web3}) => {9 const alice = privateKey('//Alice');9 const alice = privateKey('//Alice');101011 const collection = await createCollectionExpectSuccess();11 const collection = await createCollectionExpectSuccess();12 await setCollectionSponsorExpectSuccess(collection, alice.address);12 await setCollectionSponsorExpectSuccess(collection, alice.address);13 await confirmSponsorshipExpectSuccess(collection);13 await confirmSponsorshipExpectSuccess(collection);1415 // Wouldn't be needed after CORE-30016 await transferBalanceToEth(api, alice, subToEth(alice.address));171418 const minter = createEthAccount(web3);15 const minter = createEthAccount(web3);19 expect(await web3.eth.getBalance(minter)).to.equal('0');16 expect(await web3.eth.getBalance(minter)).to.equal('0');tests/src/eth/metadata.test.tsdiffbeforeafterboth161617import {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';212422describe('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});6970describe('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');8182 const alice = privateKey('//Alice');8384 const caller = await createEthAccountWithBalance(api, web3);85 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: caller});86 await submitTransactionAsync(alice, changeAdminTx);8788 const address = collectionIdToAddress(collectionId);89 const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});9091 expect(await contract.methods.name().call()).to.be.eq('some_name');92 expect(await contract.methods.symbol().call()).to.be.eq('some_prefix');9394 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');102103 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 });112113 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');122123 const alice = privateKey('//Alice');124125 const caller = await createEthAccountWithBalance(api, web3);126 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: caller});127 await submitTransactionAsync(alice, changeAdminTx);128129 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');134135 const receiver = createEthAccount(web3);136 { // mintWithTokenURI137 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 }160161 { // mintBulkWithTokenURI162 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);173174 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 ]);203204 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});210211tests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth323233let alice: IKeyringPair;33let alice: IKeyringPair;34let bob: IKeyringPair;34let bob: IKeyringPair;35let shema: any;35let schema: any;36let largeShema: any;36let largeSchema: any;373738before(async () => {38before(async () => {39 await usingApi(async () => {39 await usingApi(async () => {40 const keyring = new Keyring({type: 'sr25519'});40 const keyring = new Keyring({type: 'sr25519'});41 alice = keyring.addFromUri('//Alice');41 alice = keyring.addFromUri('//Alice');42 bob = keyring.addFromUri('//Bob');42 bob = keyring.addFromUri('//Bob');43 shema = '0x31';43 schema = '0x31';44 largeShema = new Array(1024 * 1024 + 10).fill(0xff);44 largeSchema = new Array(1024 * 1024 + 10).fill(0xff);45 });45 });46});46});47describe('Integration Test ext. setConstOnChainSchema()', () => {47describe('Integration Test ext. setConstOnChainSchema()', () => {51 const collectionId = await createCollectionExpectSuccess();51 const collectionId = await createCollectionExpectSuccess();52 const collection = await queryCollectionExpectSuccess(api, collectionId);52 const collection = await queryCollectionExpectSuccess(api, collectionId);53 expect(collection.owner.toString()).to.be.eq(alice.address);53 expect(collection.owner.toString()).to.be.eq(alice.address);54 const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);54 const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);55 await submitTransactionAsync(alice, setShema);55 await submitTransactionAsync(alice, setSchema);56 });56 });57 });57 });585862 const collection = await queryCollectionExpectSuccess(api, collectionId);62 const collection = await queryCollectionExpectSuccess(api, collectionId);63 expect(collection.owner.toString()).to.be.eq(alice.address);63 expect(collection.owner.toString()).to.be.eq(alice.address);64 await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);64 await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);65 const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);65 const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);66 await submitTransactionAsync(bob, setShema);66 await submitTransactionAsync(bob, setSchema);67 });67 });68 });68 });696970 it('Checking collection data using the ConstOnChainSchema parameter', async () => {70 it('Checking collection data using the ConstOnChainSchema parameter', async () => {71 await usingApi(async (api) => {71 await usingApi(async (api) => {72 const collectionId = await createCollectionExpectSuccess();72 const collectionId = await createCollectionExpectSuccess();73 const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);73 const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);74 await submitTransactionAsync(alice, setShema);74 await submitTransactionAsync(alice, setSchema);75 const collection = await queryCollectionExpectSuccess(api, collectionId);75 const collection = await queryCollectionExpectSuccess(api, collectionId);76 expect(collection.constOnChainSchema.toString()).to.be.eq(shema);76 expect(collection.constOnChainSchema.toString()).to.be.eq(schema);77 });77 });78 });78 });79});79});84 await usingApi(async (api) => {84 await usingApi(async (api) => {85 // tslint:disable-next-line: radix85 // tslint:disable-next-line: radix86 const collectionId = await getCreatedCollectionCount(api) + 1;86 const collectionId = await getCreatedCollectionCount(api) + 1;87 const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);87 const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);88 await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;88 await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;89 });89 });90 });90 });919192 it('Set a previously deleted collection', async () => {92 it('Set a previously deleted collection', async () => {93 await usingApi(async (api) => {93 await usingApi(async (api) => {94 const collectionId = await createCollectionExpectSuccess();94 const collectionId = await createCollectionExpectSuccess();95 await destroyCollectionExpectSuccess(collectionId);95 await destroyCollectionExpectSuccess(collectionId);96 const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);96 const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);97 await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;97 await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;98 });98 });99 });99 });100100101 it('Set invalid data in schema (size too large:> 1MB)', async () => {101 it('Set invalid data in schema (size too large:> 1MB)', async () => {102 await usingApi(async (api) => {102 await usingApi(async (api) => {103 const collectionId = await createCollectionExpectSuccess();103 const collectionId = await createCollectionExpectSuccess();104 const setShema = api.tx.unique.setConstOnChainSchema(collectionId, largeShema);104 const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, largeSchema);105 await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;105 await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;106 });106 });107 });107 });108108111 const collectionId = await createCollectionExpectSuccess();111 const collectionId = await createCollectionExpectSuccess();112 const collection = await queryCollectionExpectSuccess(api, collectionId);112 const collection = await queryCollectionExpectSuccess(api, collectionId);113 expect(collection.owner.toString()).to.be.eq(alice.address);113 expect(collection.owner.toString()).to.be.eq(alice.address);114 const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);114 const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);115 await expect(submitTransactionExpectFailAsync(bob, setShema)).to.be.rejected;115 await expect(submitTransactionExpectFailAsync(bob, setSchema)).to.be.rejected;116 });116 });117 });117 });118118tests/src/util/helpers.tsdiffbeforeafterboth268 name: string,268 name: string,269 description: string,269 description: string,270 tokenPrefix: string,270 tokenPrefix: string,271 schemaVersion: string,271};272};272273273const defaultCreateCollectionParams: CreateCollectionParams = {274const defaultCreateCollectionParams: CreateCollectionParams = {274 description: 'description',275 description: 'description',275 mode: {type: 'NFT'},276 mode: {type: 'NFT'},276 name: 'name',277 name: 'name',277 tokenPrefix: 'prefix',278 tokenPrefix: 'prefix',279 schemaVersion: 'ImageURL',278};280};279281280export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {282export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {281 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};283 const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};282284283 let collectionId = 0;285 let collectionId = 0;284 await usingApi(async (api) => {286 await usingApi(async (api) => {303 name: strToUTF16(name), 304 description: strToUTF16(description), 305 tokenPrefix: strToUTF16(tokenPrefix), 306 mode: modeprm as any,307 schemaVersion: schemaVersion,308 });301 const events = await submitTransactionAsync(alicePrivateKey, tx);309 const events = await submitTransactionAsync(alicePrivateKey, tx);302 const result = getCreateCollectionResult(events);310 const result = getCreateCollectionResult(events);