git.delta.rocks / unique-network / refs/commits / fc6e54132883

difftreelog

Merge pull request #565 from UniqueNetwork/tests/eth-playgrounds

ut-akuznetsov2022-09-05parents: #46ff423 #d561a49.patch.diff
in: master

15 files changed

modifiedtests/package.jsondiffbeforeafterboth
30 "testEth": "mocha --timeout 9999999 -r ts-node/register './**/eth/**/*.test.ts'",30 "testEth": "mocha --timeout 9999999 -r ts-node/register './**/eth/**/*.test.ts'",
31 "testEthMarketplace": "mocha --timeout 9999999 -r ts-node/register './**/eth/marketplace/**/*.test.ts'",31 "testEthMarketplace": "mocha --timeout 9999999 -r ts-node/register './**/eth/marketplace/**/*.test.ts'",
32 "testEthNesting": "mocha --timeout 9999999 -r ts-node/register './**/eth/nesting/**/*.test.ts'",32 "testEthNesting": "mocha --timeout 9999999 -r ts-node/register './**/eth/nesting/**/*.test.ts'",
33 "testEthPayable": "mocha --timeout 9999999 -r ts-node/register './**/eth/payable.test.ts'",
33 "load": "mocha --timeout 9999999 -r ts-node/register './**/*.load.ts'",34 "load": "mocha --timeout 9999999 -r ts-node/register './**/*.load.ts'",
34 "loadTransfer": "ts-node src/transfer.nload.ts",35 "loadTransfer": "ts-node src/transfer.nload.ts",
35 "testCollision": "mocha --timeout 9999999 -r ts-node/register ./src/collision-tests/*.test.ts",36 "testCollision": "mocha --timeout 9999999 -r ts-node/register ./src/collision-tests/*.test.ts",
79 "testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",80 "testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
80 "testEnableDisableTransfers": "mocha --timeout 9999999 -r ts-node/register ./**/enableDisableTransfer.test.ts",81 "testEnableDisableTransfers": "mocha --timeout 9999999 -r ts-node/register ./**/enableDisableTransfer.test.ts",
81 "testLimits": "mocha --timeout 9999999 -r ts-node/register ./**/limits.test.ts",82 "testLimits": "mocha --timeout 9999999 -r ts-node/register ./**/limits.test.ts",
83 "testEthCreateNFTCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createNFTCollection.test.ts",
82 "testEthCreateCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createCollection.test.ts",84 "testEthCreateRFTCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createRFTCollection.test.ts",
83 "testRFT": "mocha --timeout 9999999 -r ts-node/register ./**/refungible.test.ts",85 "testRFT": "mocha --timeout 9999999 -r ts-node/register ./**/refungible.test.ts",
84 "testFT": "mocha --timeout 9999999 -r ts-node/register ./**/fungible.test.ts",86 "testFT": "mocha --timeout 9999999 -r ts-node/register ./**/fungible.test.ts",
85 "testRPC": "mocha --timeout 9999999 -r ts-node/register ./**/rpc.test.ts",87 "testRPC": "mocha --timeout 9999999 -r ts-node/register ./**/rpc.test.ts",
modifiedtests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth
24 getCollectionAddressFromResult, 24 getCollectionAddressFromResult,
25 itWeb3,25 itWeb3,
26 recordEthFee,26 recordEthFee,
27 subToEth,
28} from './util/helpers';27} from './util/helpers';
2928
30describe('Add collection admins', () => {29describe('Add collection admins', () => {
37 .send();36 .send();
38 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);37 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
3938
40 const newAdmin = await createEthAccount(web3);39 const newAdmin = createEthAccount(web3);
41 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);40 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
42 await collectionEvm.methods.addCollectionAdmin(newAdmin).send();41 await collectionEvm.methods.addCollectionAdmin(newAdmin).send();
43 const adminList = await api.rpc.unique.adminlist(collectionId);42 const adminList = await api.rpc.unique.adminlist(collectionId);
92 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);91 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
93 await collectionEvm.methods.addCollectionAdmin(admin).send();92 await collectionEvm.methods.addCollectionAdmin(admin).send();
94 93
95 const user = await createEthAccount(web3);94 const user = createEthAccount(web3);
96 await expect(collectionEvm.methods.addCollectionAdmin(user).call({from: admin}))95 await expect(collectionEvm.methods.addCollectionAdmin(user).call({from: admin}))
97 .to.be.rejectedWith('NoPermission');96 .to.be.rejectedWith('NoPermission');
9897
114 const notAdmin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);113 const notAdmin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
115 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);114 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
116 115
117 const user = await createEthAccount(web3);116 const user = createEthAccount(web3);
118 await expect(collectionEvm.methods.addCollectionAdmin(user).call({from: notAdmin}))117 await expect(collectionEvm.methods.addCollectionAdmin(user).call({from: notAdmin}))
119 .to.be.rejectedWith('NoPermission');118 .to.be.rejectedWith('NoPermission');
120119
175 .send();174 .send();
176 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);175 const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
177176
178 const newAdmin = await createEthAccount(web3);177 const newAdmin = createEthAccount(web3);
179 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);178 const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
180 await collectionEvm.methods.addCollectionAdmin(newAdmin).send();179 await collectionEvm.methods.addCollectionAdmin(newAdmin).send();
181 {180 {
226225
227 const admin0 = await createEthAccountWithBalance(api, web3, privateKeyWrapper);226 const admin0 = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
228 await collectionEvm.methods.addCollectionAdmin(admin0).send();227 await collectionEvm.methods.addCollectionAdmin(admin0).send();
229 const admin1 = await createEthAccount(web3);228 const admin1 = createEthAccount(web3);
230 await collectionEvm.methods.addCollectionAdmin(admin1).send();229 await collectionEvm.methods.addCollectionAdmin(admin1).send();
231230
232 await expect(collectionEvm.methods.removeCollectionAdmin(admin1).call({from: admin0}))231 await expect(collectionEvm.methods.removeCollectionAdmin(admin1).call({from: admin0}))
253252
254 const admin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);253 const admin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
255 await collectionEvm.methods.addCollectionAdmin(admin).send();254 await collectionEvm.methods.addCollectionAdmin(admin).send();
256 const notAdmin = await createEthAccount(web3);255 const notAdmin = createEthAccount(web3);
257256
258 await expect(collectionEvm.methods.removeCollectionAdmin(admin).call({from: notAdmin}))257 await expect(collectionEvm.methods.removeCollectionAdmin(admin).call({from: notAdmin}))
259 .to.be.rejectedWith('NoPermission');258 .to.be.rejectedWith('NoPermission');
modifiedtests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth
1import {addToAllowListExpectSuccess, bigIntToSub, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, getDetailedCollectionInfo, setCollectionSponsorExpectSuccess} from '../util/helpers';1import {addToAllowListExpectSuccess, bigIntToSub, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, getDetailedCollectionInfo, setCollectionSponsorExpectSuccess} from '../util/helpers';
2import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents, createEthAccountWithBalance, evmCollectionHelpers, getCollectionAddressFromResult, evmCollection, ethBalanceViaSub, subToEth} from './util/helpers';2import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents, createEthAccountWithBalance, evmCollectionHelpers, getCollectionAddressFromResult, evmCollection, ethBalanceViaSub} from './util/helpers';
3import nonFungibleAbi from './nonFungibleAbi.json';3import nonFungibleAbi from './nonFungibleAbi.json';
4import {expect} from 'chai';4import {expect} from 'chai';
5import {evmToAddress} from '@polkadot/util-crypto';5import {evmToAddress} from '@polkadot/util-crypto';
modifiedtests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth
181 });181 });
182 182
183 itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {183 itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {
184 const owner = await createEthAccount(web3);184 const owner = createEthAccount(web3);
185 const helper = evmCollectionHelpers(web3, owner);185 const helper = evmCollectionHelpers(web3, owner);
186 const collectionName = 'A';186 const collectionName = 'A';
187 const description = 'A';187 const description = 'A';
194194
195 itWeb3('(!negative test!) Check owner', async ({api, web3, privateKeyWrapper}) => {195 itWeb3('(!negative test!) Check owner', async ({api, web3, privateKeyWrapper}) => {
196 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);196 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
197 const notOwner = await createEthAccount(web3);197 const notOwner = createEthAccount(web3);
198 const collectionHelpers = evmCollectionHelpers(web3, owner);198 const collectionHelpers = evmCollectionHelpers(web3, owner);
199 const result = await collectionHelpers.methods.createNonfungibleCollection('A', 'A', 'A').send();199 const result = await collectionHelpers.methods.createNonfungibleCollection('A', 'A', 'A').send();
200 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);200 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
modifiedtests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth
189 });189 });
190 190
191 itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {191 itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {
192 const owner = await createEthAccount(web3);192 const owner = createEthAccount(web3);
193 const helper = evmCollectionHelpers(web3, owner);193 const helper = evmCollectionHelpers(web3, owner);
194 const collectionName = 'A';194 const collectionName = 'A';
195 const description = 'A';195 const description = 'A';
202202
203 itWeb3('(!negative test!) Check owner', async ({api, web3, privateKeyWrapper}) => {203 itWeb3('(!negative test!) Check owner', async ({api, web3, privateKeyWrapper}) => {
204 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);204 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
205 const notOwner = await createEthAccount(web3);205 const notOwner = createEthAccount(web3);
206 const collectionHelpers = evmCollectionHelpers(web3, owner);206 const collectionHelpers = evmCollectionHelpers(web3, owner);
207 const result = await collectionHelpers.methods.createRefungibleCollection('A', 'A', 'A').send();207 const result = await collectionHelpers.methods.createRefungibleCollection('A', 'A', 'A').send();
208 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);208 const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
modifiedtests/src/eth/nesting/nest.test.tsdiffbeforeafterboth
1import {ApiPromise} from '@polkadot/api';1import {IKeyringPair} from '@polkadot/types/types';
2import {Contract} from 'web3-eth-contract';2import {Contract} from 'web3-eth-contract';
3import {expect} from 'chai';3
4import Web3 from 'web3';
5import {createEthAccountWithBalance, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, tokenIdToAddress} from '../../eth/util/helpers';4import {itEth, EthUniqueHelper, usingEthPlaygrounds, expect} from '../util/playgrounds';
6import nonFungibleAbi from '../nonFungibleAbi.json';
75
8const createNestingCollection = async (6const createNestingCollection = async (
9 api: ApiPromise,7 helper: EthUniqueHelper,
10 web3: Web3,
11 owner: string,8 owner: string,
12): Promise<{ collectionId: number, collectionAddress: string, contract: Contract }> => {9): Promise<{ collectionId: number, collectionAddress: string, contract: Contract }> => {
13 const collectionHelper = evmCollectionHelpers(web3, owner);
14
15 const result = await collectionHelper.methods10 const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
16 .createNonfungibleCollection('A', 'B', 'C')
17 .send();
18 const {collectionIdAddress: collectionAddress, collectionId} = await getCollectionAddressFromResult(api, result);
1911
20 const contract = new web3.eth.Contract(nonFungibleAbi as any, collectionAddress, {from: owner, ...GAS_ARGS});12 const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
21 await contract.methods.setCollectionNesting(true).send({from: owner});13 await contract.methods.setCollectionNesting(true).send({from: owner});
2214
23 return {collectionId, collectionAddress, contract};15 return {collectionId, collectionAddress, contract};
24};16};
2517
26describe('Integration Test: EVM Nesting', () => {
27 itWeb3('NFT: allows an Owner to nest/unnest their token', async ({api, web3, privateKeyWrapper}) => {
28 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
29 const {collectionId, contract} = await createNestingCollection(api, web3, owner);
30
31 // Create a token to be nested
32 const targetNFTTokenId = await contract.methods.nextTokenId().call();
33 await contract.methods.mint(
34 owner,
35 targetNFTTokenId,
36 ).send({from: owner});
37
38 const targetNftTokenAddress = tokenIdToAddress(collectionId, targetNFTTokenId);
39
40 // Create a nested token
41 const firstTokenId = await contract.methods.nextTokenId().call();
42 await contract.methods.mint(
43 targetNftTokenAddress,
44 firstTokenId,
45 ).send({from: owner});
46
47 expect(await contract.methods.ownerOf(firstTokenId).call()).to.be.equal(targetNftTokenAddress);
48
49 // Create a token to be nested and nest
50 const secondTokenId = await contract.methods.nextTokenId().call();
51 await contract.methods.mint(
52 owner,
53 secondTokenId,
54 ).send({from: owner});
55
56 await contract.methods.transfer(targetNftTokenAddress, secondTokenId).send({from: owner});
57
58 expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(targetNftTokenAddress);
59
60 // Unnest token back
61 await contract.methods.transferFrom(targetNftTokenAddress, owner, secondTokenId).send({from: owner});
62 expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(owner);
63 });
64
65 itWeb3('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({api, web3, privateKeyWrapper}) => {
66 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
67
68 const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(api, web3, owner);
69 const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(api, web3, owner);
70 await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
71
72 // Create a token to nest into
73 const targetNftTokenId = await contractA.methods.nextTokenId().call();
74 await contractA.methods.mint(
75 owner,
76 targetNftTokenId,
77 ).send({from: owner});
78 const nftTokenAddressA1 = tokenIdToAddress(collectionIdA, targetNftTokenId);
79
80 // Create a token for nesting in the same collection as the target
81 const nftTokenIdA = await contractA.methods.nextTokenId().call();
82 await contractA.methods.mint(
83 owner,
84 nftTokenIdA,
85 ).send({from: owner});
86
87 // Create a token for nesting in a different collection
88 const nftTokenIdB = await contractB.methods.nextTokenId().call();
89 await contractB.methods.mint(
90 owner,
91 nftTokenIdB,
92 ).send({from: owner});
93
94 // Nest
95 await contractA.methods.transfer(nftTokenAddressA1, nftTokenIdA).send({from: owner});
96 expect(await contractA.methods.ownerOf(nftTokenIdA).call()).to.be.equal(nftTokenAddressA1);
97
98 await contractB.methods.transfer(nftTokenAddressA1, nftTokenIdB).send({from: owner});
99 expect(await contractB.methods.ownerOf(nftTokenIdB).call()).to.be.equal(nftTokenAddressA1);
100 });
101});
10218
103describe('Negative Test: EVM Nesting', async() => {19describe('EVM nesting tests group', () => {
20 let donor: IKeyringPair;
21
22 before(async function() {
23 await usingEthPlaygrounds(async (helper, privateKey) => {
24 donor = privateKey('//Alice');
25 });
26 });
27
28 describe('Integration Test: EVM Nesting', () => {
29 itEth('NFT: allows an Owner to nest/unnest their token', async ({helper}) => {
30 const owner = await helper.eth.createAccountWithBalance(donor);
31 const {collectionId, contract} = await createNestingCollection(helper, owner);
32
33 // Create a token to be nested
34 const targetNFTTokenId = await contract.methods.nextTokenId().call();
35 await contract.methods.mint(
36 owner,
37 targetNFTTokenId,
38 ).send({from: owner});
39
40 const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetNFTTokenId);
41
42 // Create a nested token
43 const firstTokenId = await contract.methods.nextTokenId().call();
44 await contract.methods.mint(
45 targetNftTokenAddress,
46 firstTokenId,
47 ).send({from: owner});
48
49 expect(await contract.methods.ownerOf(firstTokenId).call()).to.be.equal(targetNftTokenAddress);
50
51 // Create a token to be nested and nest
52 const secondTokenId = await contract.methods.nextTokenId().call();
53 await contract.methods.mint(
54 owner,
55 secondTokenId,
56 ).send({from: owner});
57
58 await contract.methods.transfer(targetNftTokenAddress, secondTokenId).send({from: owner});
59
60 expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(targetNftTokenAddress);
61
62 // Unnest token back
63 await contract.methods.transferFrom(targetNftTokenAddress, owner, secondTokenId).send({from: owner});
64 expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(owner);
65 });
66
67 itEth('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {
68 const owner = await helper.eth.createAccountWithBalance(donor);
69
70 const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
71 const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
72 await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
73
74 // Create a token to nest into
75 const targetNftTokenId = await contractA.methods.nextTokenId().call();
76 await contractA.methods.mint(
77 owner,
78 targetNftTokenId,
79 ).send({from: owner});
80 const nftTokenAddressA1 = helper.ethAddress.fromTokenId(collectionIdA, targetNftTokenId);
81
82 // Create a token for nesting in the same collection as the target
83 const nftTokenIdA = await contractA.methods.nextTokenId().call();
84 await contractA.methods.mint(
85 owner,
86 nftTokenIdA,
87 ).send({from: owner});
88
89 // Create a token for nesting in a different collection
90 const nftTokenIdB = await contractB.methods.nextTokenId().call();
91 await contractB.methods.mint(
92 owner,
93 nftTokenIdB,
94 ).send({from: owner});
95
96 // Nest
97 await contractA.methods.transfer(nftTokenAddressA1, nftTokenIdA).send({from: owner});
98 expect(await contractA.methods.ownerOf(nftTokenIdA).call()).to.be.equal(nftTokenAddressA1);
99
100 await contractB.methods.transfer(nftTokenAddressA1, nftTokenIdB).send({from: owner});
101 expect(await contractB.methods.ownerOf(nftTokenIdB).call()).to.be.equal(nftTokenAddressA1);
102 });
103 });
104
105 describe('Negative Test: EVM Nesting', async() => {
104 itWeb3('NFT: disallows to nest token if nesting is disabled', async ({api, web3, privateKeyWrapper}) => {106 itEth('NFT: disallows to nest token if nesting is disabled', async ({helper}) => {
105 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);107 const owner = await helper.eth.createAccountWithBalance(donor);
106108
107 const {collectionId, contract} = await createNestingCollection(api, web3, owner);109 const {collectionId, contract} = await createNestingCollection(helper, owner);
108 await contract.methods.setCollectionNesting(false).send({from: owner});110 await contract.methods.setCollectionNesting(false).send({from: owner});
109111
110 // Create a token to nest into112 // Create a token to nest into
114 targetNftTokenId,116 targetNftTokenId,
115 ).send({from: owner});117 ).send({from: owner});
116118
117 const targetNftTokenAddress = tokenIdToAddress(collectionId, targetNftTokenId);119 const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetNftTokenId);
118120
119 // Create a token to nest121 // Create a token to nest
120 const nftTokenId = await contract.methods.nextTokenId().call();122 const nftTokenId = await contract.methods.nextTokenId().call();
129 .call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');131 .call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
130 });132 });
131133
132 itWeb3('NFT: disallows a non-Owner to nest someone else\'s token', async ({api, web3, privateKeyWrapper}) => {134 itEth('NFT: disallows a non-Owner to nest someone else\'s token', async ({helper}) => {
133 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);135 const owner = await helper.eth.createAccountWithBalance(donor);
134 const malignant = await createEthAccountWithBalance(api, web3, privateKeyWrapper);136 const malignant = await helper.eth.createAccountWithBalance(donor);
135137
136 const {collectionId, contract} = await createNestingCollection(api, web3, owner);138 const {collectionId, contract} = await createNestingCollection(helper, owner);
137139
138 // Mint a token140 // Mint a token
139 const targetTokenId = await contract.methods.nextTokenId().call();141 const targetTokenId = await contract.methods.nextTokenId().call();
140 await contract.methods.mint(142 await contract.methods.mint(
141 owner,143 owner,
142 targetTokenId,144 targetTokenId,
143 ).send({from: owner});145 ).send({from: owner});
144 const targetTokenAddress = tokenIdToAddress(collectionId, targetTokenId);146 const targetTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetTokenId);
145147
146 // Mint a token belonging to a different account148 // Mint a token belonging to a different account
147 const tokenId = await contract.methods.nextTokenId().call();149 const tokenId = await contract.methods.nextTokenId().call();
156 .call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');158 .call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');
157 });159 });
158160
159 itWeb3('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async ({api, web3, privateKeyWrapper}) => {161 itEth('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async ({helper}) => {
160 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);162 const owner = await helper.eth.createAccountWithBalance(donor);
161 const malignant = await createEthAccountWithBalance(api, web3, privateKeyWrapper);163 const malignant = await helper.eth.createAccountWithBalance(donor);
162164
163 const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(api, web3, owner);165 const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
164 const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(api, web3, owner);166 const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
165167
166 await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});168 await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
167169
171 owner,173 owner,
172 nftTokenIdA,174 nftTokenIdA,
173 ).send({from: owner});175 ).send({from: owner});
174 const nftTokenAddressA = tokenIdToAddress(collectionIdA, nftTokenIdA);176 const nftTokenAddressA = helper.ethAddress.fromTokenId(collectionIdA, nftTokenIdA);
175177
176 // Create a token in another collection belonging to someone else178 // Create a token in another collection belonging to someone else
177 const nftTokenIdB = await contractB.methods.nextTokenId().call();179 const nftTokenIdB = await contractB.methods.nextTokenId().call();
186 .call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');188 .call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');
187 });189 });
188190
189 itWeb3('NFT: disallows to nest token in an unlisted collection', async ({api, web3, privateKeyWrapper}) => {191 itEth('NFT: disallows to nest token in an unlisted collection', async ({helper}) => {
190 const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);192 const owner = await helper.eth.createAccountWithBalance(donor);
191193
192 const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(api, web3, owner);194 const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
193 const {contract: contractB} = await createNestingCollection(api, web3, owner);195 const {contract: contractB} = await createNestingCollection(helper, owner);
194196
195 await contractA.methods.setCollectionNesting(true, [collectionAddressA]).send({from: owner});197 await contractA.methods.setCollectionNesting(true, [collectionAddressA]).send({from: owner});
196198
200 owner,202 owner,
201 nftTokenIdA,203 nftTokenIdA,
202 ).send({from: owner});204 ).send({from: owner});
203 const nftTokenAddressA = tokenIdToAddress(collectionIdA, nftTokenIdA);205 const nftTokenAddressA = helper.ethAddress.fromTokenId(collectionIdA, nftTokenIdA);
204206
205 // Create a token in another collection207 // Create a token in another collection
206 const nftTokenIdB = await contractB.methods.nextTokenId().call();208 const nftTokenIdB = await contractB.methods.nextTokenId().call();
214 .transfer(nftTokenAddressA, nftTokenIdB)216 .transfer(nftTokenAddressA, nftTokenIdB)
215 .call()).to.be.rejectedWith('SourceCollectionIsNotAllowedToNest');217 .call()).to.be.rejectedWith('SourceCollectionIsNotAllowedToNest');
216 });218 });
217});219 });
220});
218221
modifiedtests/src/eth/payable.test.tsdiffbeforeafterboth
14// You should have received a copy of the GNU General Public License14// You should have received a copy of the GNU General Public License
15// 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/>.
1616
17import {expect} from 'chai';
18import {submitTransactionAsync} from '../substrate/substrate-api';17import {IKeyringPair} from '@polkadot/types/types';
18
19import {createEthAccountWithBalance, deployCollector, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from './util/helpers';19import {itEth, expect, usingEthPlaygrounds} from './util/playgrounds';
20import {evmToAddress} from '@polkadot/util-crypto';
21import {getGenericResult, UNIQUE} from '../util/helpers';
22import {getBalanceSingle, transferBalanceExpectSuccess} from '../substrate/get-balance';
2320
24describe('EVM payable contracts', () => {21describe('EVM payable contracts', () => {
22 let donor: IKeyringPair;
23
24 before(async function() {
25 await usingEthPlaygrounds(async (helper, privateKey) => {
26 donor = privateKey('//Alice');
27 });
28 });
29
25 itWeb3('Evm contract can receive wei from eth account', async ({api, web3, privateKeyWrapper}) => {30 itEth('Evm contract can receive wei from eth account', async ({helper}) => {
26 const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);31 const deployer = await helper.eth.createAccountWithBalance(donor);
27 const contract = await deployCollector(web3, deployer);32 const contract = await helper.eth.deployCollectorContract(deployer);
33
34 const web3 = helper.getWeb3();
2835
29 await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: '10000', ...GAS_ARGS});36 await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: '10000', gas: helper.eth.DEFAULT_GAS});
3037
31 expect(await contract.methods.getCollected().call()).to.be.equal('10000');38 expect(await contract.methods.getCollected().call()).to.be.equal('10000');
32 });39 });
3340
34 itWeb3('Evm contract can receive wei from substrate account', async ({api, web3, privateKeyWrapper}) => {41 itEth('Evm contract can receive wei from substrate account', async ({helper}) => {
35 const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);42 const deployer = await helper.eth.createAccountWithBalance(donor);
36 const contract = await deployCollector(web3, deployer);43 const contract = await helper.eth.deployCollectorContract(deployer);
37 const alice = privateKeyWrapper('//Alice');44 const [alice] = await helper.arrange.createAccounts([10n], donor);
45
46 const weiCount = '10000';
3847
39 // Transaction fee/value will be payed from subToEth(sender) evm balance,48 // Transaction fee/value will be payed from subToEth(sender) evm balance,
40 // which is backed by evmToAddress(subToEth(sender)) substrate balance49 // which is backed by evmToAddress(subToEth(sender)) substrate balance
41 await transferBalanceToEth(api, alice, subToEth(alice.address));50 await helper.eth.transferBalanceFromSubstrate(alice, helper.address.substrateToEth(alice.address), 5n);
4251
43 {52
44 const tx = api.tx.evm.call(53 await helper.eth.callEVM(alice, contract.options.address, contract.methods.giveMoney().encodeABI(), weiCount);
45 subToEth(alice.address),
46 contract.options.address,
47 contract.methods.giveMoney().encodeABI(),
52 null,
53 [],
54 );
55 const events = await submitTransactionAsync(alice, tx);
56 const result = getGenericResult(events);
57 expect(result.success).to.be.true;
58 }
5954
60 expect(await contract.methods.getCollected().call()).to.be.equal('10000');55 expect(await contract.methods.getCollected().call()).to.be.equal(weiCount);
61 });56 });
6257
63 // We can't handle sending balance to backing storage of evm balance, because evmToAddress operation is irreversible58 // We can't handle sending balance to backing storage of evm balance, because evmToAddress operation is irreversible
64 itWeb3('Wei sent directly to backing storage of evm contract balance is unaccounted', async({api, web3, privateKeyWrapper}) => {59 itEth('Wei sent directly to backing storage of evm contract balance is unaccounted', async({helper}) => {
65 const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);60 const deployer = await helper.eth.createAccountWithBalance(donor);
66 const contract = await deployCollector(web3, deployer);61 const contract = await helper.eth.deployCollectorContract(deployer);
67 const alice = privateKeyWrapper('//Alice');62 const [alice] = await helper.arrange.createAccounts([10n], donor);
63
64 const weiCount = 10_000n;
6865
69 await transferBalanceExpectSuccess(api, alice, evmToAddress(contract.options.address), '10000');66 await helper.eth.transferBalanceFromSubstrate(alice, contract.options.address, weiCount, false);
7067
71 expect(await contract.methods.getUnaccounted().call()).to.be.equal('10000');68 expect(await contract.methods.getUnaccounted().call()).to.be.equal(weiCount.toString());
72 });69 });
7370
74 itWeb3('Balance can be retrieved from evm contract', async({api, web3, privateKeyWrapper}) => {71 itEth('Balance can be retrieved from evm contract', async({helper, privateKey}) => {
75 const FEE_BALANCE = 1000n * UNIQUE;72 const FEE_BALANCE = 10n * helper.balance.getOneTokenNominal();
76 const CONTRACT_BALANCE = 1n * UNIQUE;73 const CONTRACT_BALANCE = 1n * helper.balance.getOneTokenNominal();
7774
78 const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);75 const deployer = await helper.eth.createAccountWithBalance(donor);
79 const contract = await deployCollector(web3, deployer);76 const contract = await helper.eth.deployCollectorContract(deployer);
80 const alice = privateKeyWrapper('//Alice');77 const [alice] = await helper.arrange.createAccounts([20n], donor);
78
79 const web3 = helper.getWeb3();
8180
82 await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: CONTRACT_BALANCE.toString(), ...GAS_ARGS});81 await web3.eth.sendTransaction({from: deployer, to: contract.options.address, value: CONTRACT_BALANCE.toString(), gas: helper.eth.DEFAULT_GAS});
8382
84 const receiver = privateKeyWrapper(`//Receiver${Date.now()}`);83 const receiver = privateKey(`//Receiver${Date.now()}`);
8584
86 // First receive balance on eth balance of bob85 // First receive balance on eth balance of bob
87 {86 {
88 const ethReceiver = subToEth(receiver.address);87 const ethReceiver = helper.address.substrateToEth(receiver.address);
89 expect(await web3.eth.getBalance(ethReceiver)).to.be.equal('0');88 expect(await web3.eth.getBalance(ethReceiver)).to.be.equal('0');
90 await contract.methods.withdraw(ethReceiver).send({from: deployer});89 await contract.methods.withdraw(ethReceiver).send({from: deployer});
91 expect(await web3.eth.getBalance(ethReceiver)).to.be.equal(CONTRACT_BALANCE.toString());90 expect(await web3.eth.getBalance(ethReceiver)).to.be.equal(CONTRACT_BALANCE.toString());
92 }91 }
9392
94 // Some balance is required to pay fee for evm.withdraw call93 // Some balance is required to pay fee for evm.withdraw call
95 await transferBalanceExpectSuccess(api, alice, receiver.address, FEE_BALANCE.toString());94 await helper.balance.transferToSubstrate(alice, receiver.address, FEE_BALANCE);
95 // await transferBalanceExpectSuccess(api, alice, receiver.address, FEE_BALANCE.toString());
9696
97 // Withdraw balance from eth to substrate97 // Withdraw balance from eth to substrate
98 {98 {
99 const initialReceiverBalance = await getBalanceSingle(api, receiver.address);99 const initialReceiverBalance = await helper.balance.getSubstrate(receiver.address);
100 const tx = api.tx.evm.withdraw(100 await helper.executeExtrinsic(receiver, 'api.tx.evm.withdraw', [helper.address.substrateToEth(receiver.address), CONTRACT_BALANCE.toString()], true);
101 subToEth(receiver.address),
102 CONTRACT_BALANCE.toString(),
103 );
104 const events = await submitTransactionAsync(receiver, tx);
105 const result = getGenericResult(events);
106 expect(result.success).to.be.true;
107 const finalReceiverBalance = await getBalanceSingle(api, receiver.address);101 const finalReceiverBalance = await helper.balance.getSubstrate(receiver.address);
108102
109 expect(finalReceiverBalance > initialReceiverBalance).to.be.true;103 expect(finalReceiverBalance > initialReceiverBalance).to.be.true;
110 }104 }
modifiedtests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth
15// 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/>.
1616
17import {approve, createCollection, createRefungibleToken, transfer, transferFrom, UNIQUE, requirePallets, Pallets} from '../util/helpers';17import {approve, createCollection, createRefungibleToken, transfer, transferFrom, UNIQUE, requirePallets, Pallets} from '../util/helpers';
18import {collectionIdFromAddress, collectionIdToAddress, createEthAccount, createEthAccountWithBalance, createNonfungibleCollection, createRefungibleCollection, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth, uniqueNFT, uniqueRefungible, uniqueRefungibleToken} from './util/helpers';18import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, createRefungibleCollection, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth, uniqueRefungible, uniqueRefungibleToken} from './util/helpers';
1919
20import chai from 'chai';20import chai from 'chai';
21import chaiAsPromised from 'chai-as-promised';21import chaiAsPromised from 'chai-as-promised';
addedtests/src/eth/util/playgrounds/index.tsdiffbeforeafterboth

no changes

addedtests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth

no changes

addedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth

no changes

modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
25import privateKey from './privateKey';25import privateKey from './privateKey';
26import promisifySubstrate from './promisify-substrate';26import promisifySubstrate from './promisify-substrate';
27
28import {SilentConsole} from '../util/playgrounds/unique.dev';
2729
2830
2931
75 const api: ApiPromise = new ApiPromise(settings);77 const api: ApiPromise = new ApiPromise(settings);
76 let result: T = null as unknown as T;78 let result: T = null as unknown as T;
77
78 // TODO: Remove, this is temporary: Filter unneeded API output
79 // (Jaco promised it will be removed in the next version)
80 const consoleErr = console.error;
81 const consoleLog = console.log;
82 const consoleWarn = console.warn;
8379
84 const outFn = (printer: any) => (...args: any[]) => {80 const silentConsole = new SilentConsole();
85 for (const arg of args) {
86 if (typeof arg !== 'string')
87 continue;
88 if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')
89 return;
90 }
91 printer(...args);
92 };
93
94 console.error = outFn(consoleErr.bind(console));81 silentConsole.enable();
95 console.log = outFn(consoleLog.bind(console));
96 console.warn = outFn(consoleWarn.bind(console));
9782
98 try {83 try {
99 await promisifySubstrate(api, async () => {84 await promisifySubstrate(api, async () => {
106 })();91 })();
107 } finally {92 } finally {
108 await api.disconnect();93 await api.disconnect();
109 console.error = consoleErr;94 silentConsole.disable();
110 console.log = consoleLog;
111 console.warn = consoleWarn;
112 }95 }
113 return result as T;96 return result as T;
114}97}
modifiedtests/src/util/playgrounds/index.tsdiffbeforeafterboth
4import {IKeyringPair} from '@polkadot/types/types';4import {IKeyringPair} from '@polkadot/types/types';
5import config from '../../config';5import config from '../../config';
6import '../../interfaces/augment-api-events';6import '../../interfaces/augment-api-events';
7import {DevUniqueHelper} from './unique.dev';7import {DevUniqueHelper, SilentLogger, SilentConsole} from './unique.dev';
88
9class SilentLogger {
10 log(msg: any, level: any): void { }
11 level = {
12 ERROR: 'ERROR' as const,
13 WARNING: 'WARNING' as const,
14 INFO: 'INFO' as const,
15 };
16}
179
18export const usingPlaygrounds = async (code: (helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {10export const usingPlaygrounds = async (code: (helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>) => {
19 // TODO: Remove, this is temporary: Filter unneeded API output
20 // (Jaco promised it will be removed in the next version)
21 const consoleErr = console.error;
22 const consoleLog = console.log;
23 const consoleWarn = console.warn;
24
25 const outFn = (printer: any) => (...args: any[]) => {11 const silentConsole = new SilentConsole();
26 for (const arg of args) {
27 if (typeof arg !== 'string')
28 continue;
29 if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')
30 return;
31 }
32 printer(...args);
33 };
34
35 console.error = outFn(consoleErr.bind(console));12 silentConsole.enable();
36 console.log = outFn(consoleLog.bind(console));13
37 console.warn = outFn(consoleWarn.bind(console));
38 const helper = new DevUniqueHelper(new SilentLogger());14 const helper = new DevUniqueHelper(new SilentLogger());
3915
40 try {16 try {
45 }21 }
46 finally {22 finally {
47 await helper.disconnect();23 await helper.disconnect();
48 console.error = consoleErr;24 silentConsole.disable();
49 console.log = consoleLog;
50 console.warn = consoleWarn;
51 }25 }
52};26};
5327
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
5import {UniqueHelper} from './unique';5import {UniqueHelper} from './unique';
6import {ApiPromise, WsProvider} from '@polkadot/api';6import {ApiPromise, WsProvider} from '@polkadot/api';
7import * as defs from '../../interfaces/definitions';7import * as defs from '../../interfaces/definitions';
8import {TSigner} from './types';
9import {IKeyringPair} from '@polkadot/types/types';8import {IKeyringPair} from '@polkadot/types/types';
9
10
11export class SilentLogger {
12 log(_msg: any, _level: any): void { }
13 level = {
14 ERROR: 'ERROR' as const,
15 WARNING: 'WARNING' as const,
16 INFO: 'INFO' as const,
17 };
18}
19
20
21export class SilentConsole {
22 // TODO: Remove, this is temporary: Filter unneeded API output
23 // (Jaco promised it will be removed in the next version)
24 consoleErr: any;
25 consoleLog: any;
26 consoleWarn: any;
27
28 constructor() {
29 this.consoleErr = console.error;
30 this.consoleLog = console.log;
31 this.consoleWarn = console.warn;
32 }
33
34 enable() {
35 const outFn = (printer: any) => (...args: any[]) => {
36 for (const arg of args) {
37 if (typeof arg !== 'string')
38 continue;
39 if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis: UniqueApi/2, RmrkApi/1') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')
40 return;
41 }
42 printer(...args);
43 };
44
45 console.error = outFn(this.consoleErr.bind(console));
46 console.log = outFn(this.consoleLog.bind(console));
47 console.warn = outFn(this.consoleWarn.bind(console));
48 }
49
50 disable() {
51 console.error = this.consoleErr;
52 console.log = this.consoleLog;
53 console.warn = this.consoleWarn;
54 }
55}
1056
1157
12export class DevUniqueHelper extends UniqueHelper {58export class DevUniqueHelper extends UniqueHelper {
20 this.arrange = new ArrangeGroup(this);66 this.arrange = new ArrangeGroup(this);
21 }67 }
2268
23 async connect(wsEndpoint: string, listeners?: any): Promise<void> {69 async connect(wsEndpoint: string, _listeners?: any): Promise<void> {
24 const wsProvider = new WsProvider(wsEndpoint);70 const wsProvider = new WsProvider(wsEndpoint);
25 this.api = new ApiPromise({71 this.api = new ApiPromise({
26 provider: wsProvider,72 provider: wsProvider,
85 }131 }
86 }132 }
87133
88 await Promise.all(transactions).catch(e => {});134 await Promise.all(transactions).catch(_e => {});
89 135
90 //#region TODO remove this region, when nonce problem will be solved136 //#region TODO remove this region, when nonce problem will be solved
91 const checkBalances = async () => {137 const checkBalances = async () => {
120 * @returns 166 * @returns
121 */167 */
122 async waitNewBlocks(blocksCount = 1): Promise<void> {168 async waitNewBlocks(blocksCount = 1): Promise<void> {
169 // eslint-disable-next-line no-async-promise-executor
123 const promise = new Promise<void>(async (resolve) => {170 const promise = new Promise<void>(async (resolve) => {
124 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {171 const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {
125 if (blocksCount > 0) {172 if (blocksCount > 0) {
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
317 if(options !== null) return transaction.signAndSend(sender, options, callback);317 if(options !== null) return transaction.signAndSend(sender, options, callback);
318 return transaction.signAndSend(sender, callback);318 return transaction.signAndSend(sender, callback);
319 };319 };
320 // eslint-disable-next-line no-async-promise-executor
320 return new Promise(async (resolve, reject) => {321 return new Promise(async (resolve, reject) => {
321 try {322 try {
322 const unsub = await sign((result: any) => {323 const unsub = await sign((result: any) => {
388 type: this.chainLogType.EXTRINSIC,389 type: this.chainLogType.EXTRINSIC,
389 status: result.status,390 status: result.status,
390 call: extrinsic,391 call: extrinsic,
392 signer: this.getSignerAddress(sender),
391 params,393 params,
392 } as IUniqueHelperLog;394 } as IUniqueHelperLog;
393395
1087 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1089 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));
1088 }1090 }
10891091
1090 getCollectionObject(collectionId: number): any {1092 getCollectionObject(_collectionId: number): any {
1091 return null;1093 return null;
1092 }1094 }
10931095
1094 getTokenObject(collectionId: number, tokenId: number): any {1096 getTokenObject(_collectionId: number, _tokenId: number): any {
1095 return null;1097 return null;
1096 }1098 }
1097}1099}