1234567891011121314151617import {IKeyringPair} from '@polkadot/types/types';18import {ApiPromise} from '@polkadot/api';19import {expect, itSched, itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from './util';20import {itEth} from './eth/util';21import {UniqueHelper} from './util/playgrounds/unique';22import {main as correctState} from './migrations/correctStateAfterMaintenance';2324async function maintenanceEnabled(api: ApiPromise): Promise<boolean> {25 return (await api.query.maintenance.enabled()).toJSON() as boolean;26}2728describe('Integration Test: Maintenance Functionality', () => {29 let superuser: IKeyringPair;30 let donor: IKeyringPair;31 let bob: IKeyringPair;3233 before(async function() {34 await usingPlaygrounds(async (helper, privateKey) => {35 requirePalletsOrSkip(this, helper, [Pallets.Maintenance]);36 superuser = await privateKey('//Alice');37 donor = await privateKey({url: import.meta.url});38 [bob] = await helper.arrange.createAccounts([10000n], donor);3940 });41 });4243 describe('Maintenance Mode', () => {44 before(async function() {45 await usingPlaygrounds(async (helper) => {46 if(await maintenanceEnabled(helper.getApi())) {47 console.warn('\tMaintenance mode was left enabled BEFORE the test suite! Disabling it now.');48 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', [])).to.be.fulfilled;49 }50 });51 });5253 itSub('Allows superuser to enable and disable maintenance mode - and disallows anyone else', async ({helper}) => {54 55 await expect(helper.executeExtrinsic(superuser, 'api.tx.maintenance.enable', []), 'on commoner enabling MM')56 .to.be.rejectedWith(/BadOrigin/);5758 59 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);60 expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;6162 63 await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.disable', []), 'on commoner disabling MM')64 .to.be.rejectedWith(/BadOrigin/);6566 67 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);68 expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;69 });7071 itSub('MM blocks unique pallet calls', async ({helper}) => {72 73 const nftCollection = await helper.nft.mintCollection(bob, {74 tokenPropertyPermissions: [{75 key: 'test', permission: {76 collectionAdmin: true,77 tokenOwner: true,78 mutable: true,79 },80 }],81 });8283 84 const nft = await nftCollection.mintToken(bob);8586 87 const ftCollection = await helper.ft.mintCollection(superuser);8889 90 await expect(ftCollection.mint(superuser)).to.be.fulfilled;9192 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);93 expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;9495 96 await expect(helper.nft.mintCollection(superuser), 'cudo forbidden stuff')97 .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);9899 100 await expect(nft.setProperties(101 bob,102 [{key: 'test', value: 'test-val'}],103 )).to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);104105 106 await expect(nftCollection.mintToken(superuser))107 .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);108109 110 await expect(ftCollection.mint(superuser))111 .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);112113 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);114 expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;115116 117 await expect(helper.nft.mintCollection(bob), 'MM is disabled, the collection should be created').to.be.fulfilled;118119 120 await nft.setProperties(bob, [{key: 'test', value: 'test-val'}]);121122 123 await nftCollection.mintToken(bob);124125 126 await ftCollection.mint(superuser);127 });128129 itSub.ifWithPallets('MM blocks unique pallet calls (Re-Fungible)', [Pallets.ReFungible], async ({helper}) => {130 131 const rftCollection = await helper.rft.mintCollection(superuser);132133 134 await expect(rftCollection.mintToken(superuser)).to.be.fulfilled;135136 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);137 expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;138139 140 await expect(rftCollection.mintToken(superuser))141 .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);142143 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);144 expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;145146 147 await rftCollection.mintToken(superuser);148 });149150 itSub('MM allows native token transfers and RPC calls', async ({helper}) => {151 152 const totalCount = await helper.collection.getTotalCount();153154 155 await expect(helper.balance.transferToSubstrate(superuser, bob.address, 2n)).to.be.fulfilled;156157 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);158 expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;159160 161 expect(await helper.collection.getTotalCount()).to.be.deep.equal(totalCount);162163 164 await expect(helper.balance.transferToSubstrate(bob, superuser.address, 1n)).to.be.fulfilled;165166 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);167 expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;168169 170 expect(await helper.collection.getTotalCount()).to.be.deep.equal(totalCount);171172 173 await expect(helper.balance.transferToSubstrate(bob, superuser.address, 1n)).to.be.fulfilled;174 });175176 itSched.ifWithPallets('MM blocks scheduled calls and the scheduler itself', [Pallets.UniqueScheduler], async (scheduleKind, {helper}) => {177 const collection = await helper.nft.mintCollection(bob);178179 const nftBeforeMM = await collection.mintToken(bob);180 const nftDuringMM = await collection.mintToken(bob);181 const nftAfterMM = await collection.mintToken(bob);182183 const [184 scheduledIdBeforeMM,185 scheduledIdDuringMM,186 scheduledIdBunkerThroughMM,187 scheduledIdAttemptDuringMM,188 scheduledIdAfterMM,189 ] = scheduleKind == 'named'190 ? helper.arrange.makeScheduledIds(5)191 : new Array(5);192193 const blocksToWait = 6;194195 196 await nftBeforeMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdBeforeMM})197 .transfer(bob, {Substrate: superuser.address});198199 await helper.wait.newBlocks(blocksToWait + 1);200 expect(await nftBeforeMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});201202 203 await nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdDuringMM})204 .transfer(bob, {Substrate: superuser.address});205206 207 await nftDuringMM.scheduleAfter(blocksToWait * 2, {scheduledId: scheduledIdBunkerThroughMM})208 .transfer(bob, {Substrate: superuser.address});209210 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);211 expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;212213 await helper.wait.newBlocks(blocksToWait + 1);214 215 expect(await nftDuringMM.getOwner()).to.be.deep.equal({Substrate: bob.address});216217 218 await expect(nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAttemptDuringMM})219 .transfer(bob, {Substrate: superuser.address}))220 .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);221222 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);223 expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;224225 226 await nftAfterMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAfterMM})227 .transfer(bob, {Substrate: superuser.address});228229 await helper.wait.newBlocks(blocksToWait + 1);230231 expect(await nftAfterMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});232 233 expect(await nftDuringMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});234 });235236 itEth('Disallows Ethereum transactions to execute while in maintenance', async ({helper}) => {237 const owner = await helper.eth.createAccountWithBalance(donor);238 const receiver = helper.eth.createAccount();239240 const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'A', 'B', 'C', '');241242 243 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);244 expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;245246 const contract = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);247 const tokenId = await contract.methods.nextTokenId().call();248 expect(tokenId).to.be.equal('1');249250 await expect(contract.methods.mintWithTokenURI(receiver, 'Test URI').send())251 .to.be.rejectedWith(/Returned error: unknown error/);252253 await expect(contract.methods.ownerOf(tokenId).call()).rejectedWith(/token not found/);254255 256 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);257 expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;258 });259260 itSub('Allows to enable and disable MM repeatedly', async ({helper}) => {261 262 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);263 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);264 expect(await maintenanceEnabled(helper.getApi()), 'MM is OFF when it should be ON').to.be.true;265266 267 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);268 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);269 expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;270 });271272 afterEach(async () => {273 await usingPlaygrounds(async helper => {274 if(helper.fetchMissingPalletNames([Pallets.Maintenance]).length != 0) return;275 if(await maintenanceEnabled(helper.getApi())) {276 console.warn('\tMaintenance mode was left enabled AFTER a test has finished! Be careful. Disabling it now.');277 await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', []);278 }279 expect(await maintenanceEnabled(helper.getApi()), 'Disastrous! Exited the test suite with maintenance mode on.').to.be.false;280 });281 });282 });283284 describe('Preimage Execution', () => {285 const preimageHashes: string[] = [];286287 before(async function() {288 await usingPlaygrounds(async (helper) => {289 requirePalletsOrSkip(this, helper, [Pallets.Preimage, Pallets.Maintenance]);290291 292 const randomAccounts = await helper.arrange.createCrowd(10, 0n, superuser);293 const randomIdentities = randomAccounts.map((acc, i) => [294 acc.address, {295 deposit: 0n,296 judgements: [],297 info: {298 display: {299 raw: `Random Account #${i}`,300 },301 },302 },303 ]);304 const preimage = helper.constructApiCall('api.tx.identity.forceInsertIdentities', [randomIdentities]).method.toHex();305 preimageHashes.push(await helper.preimage.notePreimage(bob, preimage, true));306 });307 });308309 itSub('Successfully executes call in a preimage', async ({helper}) => {310 const result = await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [311 preimageHashes[0], {refTime: 10000000000, proofSize: 10000},312 ])).to.be.fulfilled;313314 315 const events = result.result.events.filter((x: any) => x.event.method === 'IdentitiesInserted' && x.event.section === 'identity');316 expect(events.length).to.be.equal(1);317318 319 expect(await helper.preimage.getPreimageInfo(preimageHashes[0])).to.have.property('unrequested');320 });321322 itSub('Does not allow execution of a preimage that would fail', async ({helper}) => {323 const [zeroAccount] = await helper.arrange.createAccounts([0n], superuser);324325 const preimage = helper.constructApiCall('api.tx.balances.forceTransfer', [326 {Id: zeroAccount.address}, {Id: superuser.address}, 1000n,327 ]).method.toHex();328 const preimageHash = await helper.preimage.notePreimage(bob, preimage, true);329 preimageHashes.push(preimageHash);330331 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [332 preimageHash, {refTime: 10000000000, proofSize: 10000},333 ])).to.be.rejectedWith(/^Token: FundsUnavailable$/);334 });335336 itSub('Does not allow preimage execution with non-root', async ({helper}) => {337 await expect(helper.executeExtrinsic(bob, 'api.tx.maintenance.executePreimage', [338 preimageHashes[0], {refTime: 10000000000, proofSize: 10000},339 ])).to.be.rejectedWith(/^Misc: BadOrigin$/);340 });341342 itSub('Does not allow execution of non-existent preimages', async ({helper}) => {343 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [344 '0x1010101010101010101010101010101010101010101010101010101010101010', {refTime: 10000000000, proofSize: 10000},345 ])).to.be.rejectedWith(/^Misc: Unavailable$/);346 });347348 itSub('Does not allow preimage execution with less than minimum weights', async ({helper}) => {349 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.executePreimage', [350 preimageHashes[0], {refTime: 1000, proofSize: 100},351 ])).to.be.rejectedWith(/^Misc: Exhausted$/);352 });353354 after(async function() {355 await usingPlaygrounds(async (helper) => {356 if(helper.fetchMissingPalletNames([Pallets.Preimage, Pallets.Maintenance]).length != 0) return;357358 for(const hash of preimageHashes) {359 await helper.preimage.unnotePreimage(bob, hash);360 }361 });362 });363 });364365 describe('Integration Test: Maintenance mode & App Promo', () => {366 let superuser: IKeyringPair;367368 before(async function() {369 await usingPlaygrounds(async (helper, privateKey) => {370 requirePalletsOrSkip(this, helper, [Pallets.Maintenance]);371 superuser = await privateKey('//Alice');372 });373 });374375 describe('Test AppPromo script for check state after Maintenance mode', () => {376 before(async function () {377 await usingPlaygrounds(async (helper) => {378 if(await maintenanceEnabled(helper.getApi())) {379 console.warn('\tMaintenance mode was left enabled BEFORE the test suite! Disabling it now.');380 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', [])).to.be.fulfilled;381 }382 });383 });384 itSub('Can find and fix inconsistent state', async ({helper}) => {385 const api = helper.getApi();386387 await helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [api.tx.system.setStorage([388 389 ['0x42b67acb8bd223c60d0c8f621ffefc0ae280fa2db99bd3827aac976de75af95f5153cb1f00942ff401000000',390 '0x04d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d000010632d5ec76b0500000000000000'],391 392 ['0x42b67acb8bd223c60d0c8f621ffefc0ae280fa2db99bd3827aac976de75af95f9eb2dcce60f37a2702000000',393 '0x04d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d000010632d5ec76b0500000000000000'],394 395 ['0xc2261276cc9d1f8598ea4b6a74b15c2fb1c0eb12e038e5c7f91e120ed4b7ebf1de1e86a9a8c739864cf3cc5ec2bea59fd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d',396 '0x046170707374616b656170707374616b65000020c65abc8ed70a00000000000000'],397 ])]);398399 expect((await api.query.appPromotion.pendingUnstake(1)).toJSON()).to.be.deep.equal([[superuser.address, '0x00000000000000056bc75e2d63100000']]);400 expect((await api.query.appPromotion.pendingUnstake(2)).toJSON()).to.be.deep.equal([[superuser.address, '0x00000000000000056bc75e2d63100000']]);401 expect((await api.query.balances.freezes(superuser.address))402 .map(lock => ({id: lock.id.toUtf8(), amount: lock.amount.toBigInt()})))403 .to.be.deep.equal([{id: 'appstakeappstake', amount: 200000000000000000000n}]);404 await correctState();405406 expect((await api.query.appPromotion.pendingUnstake(1)).toJSON()).to.be.deep.equal([]);407 expect((await api.query.appPromotion.pendingUnstake(2)).toJSON()).to.be.deep.equal([]);408 expect((await api.query.balances.freezes(superuser.address)).toJSON()).to.be.deep.equal([]);409410 });411412 itSub('(!negative test!) Only works when Maintenance mode is disabled', async({helper}) => {413 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', [])).to.be.fulfilled;414 await expect(correctState()).to.be.rejectedWith('The network is still in maintenance mode');415 await expect(helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.disable', [])).to.be.fulfilled;416 });417 });418 });419});