difftreelog
test(scheduler) root origin tests
in: master
1 file changed
tests/src/.outdated/scheduler.test.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {18 default as usingApi,19 submitTransactionAsync,20 submitTransactionExpectFailAsync,21} from '../substrate/substrate-api';22import {23 createItemExpectSuccess,24 createCollectionExpectSuccess,25 scheduleTransferExpectSuccess,26 setCollectionSponsorExpectSuccess,27 confirmSponsorshipExpectSuccess,28 findUnusedAddress,29 UNIQUE,30 enablePublicMintingExpectSuccess,31 addToAllowListExpectSuccess,32 waitNewBlocks,33 makeScheduledId,34 normalizeAccountId,35 getTokenOwner,36 getGenericResult,37 getFreeBalance,38 confirmSponsorshipByKeyExpectSuccess,39 scheduleExpectFailure,40 scheduleAfter,41} from './util/helpers';42import {expect, itSub, Pallets, usingPlaygrounds} from './util/playgrounds';43import {IKeyringPair} from '@polkadot/types/types';4445describe('Scheduling token and balance transfers', () => {46 let alice: IKeyringPair;47 let bob: IKeyringPair;4849 before(async () => {50 await usingPlaygrounds(async (_, privateKeyWrapper) => {51 alice = privateKeyWrapper('//Alice');52 bob = privateKeyWrapper('//Bob');53 });54 });5556 itSub.ifWithPallets('Can delay a transfer of an owned token', [Pallets.Scheduler], async ({helper}) => {57 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});58 const token = await collection.mintToken(alice);59 const schedulerId = await helper.scheduler.makeScheduledId();60 const blocksBeforeExecution = 4;6162 await token.scheduleAfter(schedulerId, blocksBeforeExecution)63 .transfer(alice, {Substrate: bob.address});6465 expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});6667 await helper.wait.newBlocks(blocksBeforeExecution + 1);6869 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});70 });7172 itSub.ifWithPallets('Can transfer funds periodically', [Pallets.Scheduler], async ({helper}) => {73 const scheduledId = await helper.scheduler.makeScheduledId();74 const waitForBlocks = 1;7576 const amount = 1n * UNIQUE;77 const periodic = {78 period: 2,79 repetitions: 2,80 };8182 const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);8384 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})85 .balance.transferToSubstrate(alice, bob.address, amount);8687 await helper.wait.newBlocks(waitForBlocks + 1);8889 const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);90 expect(bobsBalanceAfterFirst)91 .to.be.equal(92 bobsBalanceBefore + 1n * amount,93 '#1 Balance of the recipient should be increased by 1 * amount',94 );9596 await helper.wait.newBlocks(periodic.period);9798 const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);99 expect(bobsBalanceAfterSecond)100 .to.be.equal(101 bobsBalanceBefore + 2n * amount,102 '#2 Balance of the recipient should be increased by 2 * amount',103 );104 });105106 itSub.ifWithPallets('Can cancel a scheduled operation which has not yet taken effect', [Pallets.Scheduler], async ({helper}) => {107 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});108 const token = await collection.mintToken(alice);109110 const scheduledId = await helper.scheduler.makeScheduledId();111 const waitForBlocks = 4;112113 expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});114115 await token.scheduleAfter(scheduledId, waitForBlocks)116 .transfer(alice, {Substrate: bob.address});117118 await helper.scheduler.cancelScheduled(alice, scheduledId);119120 await waitNewBlocks(waitForBlocks + 1);121122 expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});123 });124125 itSub.ifWithPallets('Can cancel a periodic operation (transfer of funds)', [Pallets.Scheduler], async ({helper}) => {126 const waitForBlocks = 1;127 const periodic = {128 period: 3,129 repetitions: 2,130 };131132 const scheduledId = await helper.scheduler.makeScheduledId();133134 const amount = 1n * UNIQUE;135136 const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);137138 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})139 .balance.transferToSubstrate(alice, bob.address, amount);140141 await helper.wait.newBlocks(waitForBlocks + 1);142143 const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);144145 expect(bobsBalanceAfterFirst)146 .to.be.equal(147 bobsBalanceBefore + 1n * amount,148 '#1 Balance of the recipient should be increased by 1 * amount',149 );150151 await helper.scheduler.cancelScheduled(alice, scheduledId);152 await helper.wait.newBlocks(periodic.period);153154 const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);155 expect(bobsBalanceAfterSecond)156 .to.be.equal(157 bobsBalanceAfterFirst,158 '#2 Balance of the recipient should not be changed',159 );160 });161162 itSub.ifWithPallets('Scheduled tasks are transactional', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {163 const scheduledId = await helper.scheduler.makeScheduledId();164 const waitForBlocks = 4;165166 const initTestVal = 42;167 const changedTestVal = 111;168169 await helper.executeExtrinsic(170 alice,171 'api.tx.testUtils.setTestValue',172 [initTestVal],173 true,174 );175176 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks)177 .executeExtrinsic(178 alice,179 'api.tx.testUtils.setTestValueAndRollback',180 [changedTestVal],181 true,182 );183184 await helper.wait.newBlocks(waitForBlocks + 1);185186 const testVal = (await helper.api!.query.testUtils.testValue()).toNumber();187 expect(testVal, 'The test value should NOT be commited')188 .to.be.equal(initTestVal);189 });190191 itSub.ifWithPallets('Scheduled tasks should take correct fees', [Pallets.Scheduler, Pallets.TestUtils], async function({helper}) {192 const scheduledId = await helper.scheduler.makeScheduledId();193 const waitForBlocks = 8;194 const periodic = {195 period: 2,196 repetitions: 2,197 };198199 const dummyTx = helper.constructApiCall('api.tx.testUtils.justTakeFee', []);200 const scheduledLen = dummyTx.callIndex.length;201202 const expectedScheduledFee = (await helper.getPaymentInfo(alice, dummyTx, scheduledLen))203 .partialFee.toBigInt();204205 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})206 .executeExtrinsic(alice, 'api.tx.testUtils.justTakeFee', [], true);207208 await helper.wait.newBlocks(1);209210 const aliceInitBalance = await helper.balance.getSubstrate(alice.address);211 let diff;212213 await helper.wait.newBlocks(waitForBlocks);214215 const aliceBalanceAfterFirst = await helper.balance.getSubstrate(alice.address);216 expect(217 aliceBalanceAfterFirst < aliceInitBalance,218 '[after execution #1] Scheduled task should take a fee',219 ).to.be.true;220221 diff = aliceInitBalance - aliceBalanceAfterFirst;222 expect(diff).to.be.equal(223 expectedScheduledFee,224 'Scheduled task should take the right amount of fees',225 );226227 await helper.wait.newBlocks(periodic.period);228229 const aliceBalanceAfterSecond = await helper.balance.getSubstrate(alice.address);230 expect(231 aliceBalanceAfterSecond < aliceBalanceAfterFirst,232 '[after execution #2] Scheduled task should take a fee',233 ).to.be.true;234235 diff = aliceBalanceAfterFirst - aliceBalanceAfterSecond;236 expect(diff).to.be.equal(237 expectedScheduledFee,238 'Scheduled task should take the right amount of fees',239 );240 });241242 // Check if we can cancel a scheduled periodic operation243 // in the same block in which it is running244 itSub.ifWithPallets('Can cancel the periodic sheduled tx when the tx is running', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {245 const currentBlockNumber = await helper.chain.getLatestBlockNumber();246 const blocksBeforeExecution = 10;247 const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;248249 const [250 scheduledId,251 scheduledCancelId,252 ] = await helper.scheduler.makeScheduledIds(2);253254 const periodic = {255 period: 5,256 repetitions: 5,257 };258259 const initTestVal = 0;260 const incTestVal = initTestVal + 1;261 const finalTestVal = initTestVal + 2;262263 await helper.executeExtrinsic(264 alice,265 'api.tx.testUtils.setTestValue',266 [initTestVal],267 true,268 );269270 await helper.scheduler.scheduleAt(scheduledId, firstExecutionBlockNumber, {periodic})271 .executeExtrinsic(272 alice,273 'api.tx.testUtils.incTestValue',274 [],275 true,276 );277278 // Cancel the inc tx after 2 executions279 // *in the same block* in which the second execution is scheduled280 await helper.scheduler.scheduleAt(scheduledCancelId, firstExecutionBlockNumber + periodic.period)281 .scheduler.cancelScheduled(alice, scheduledId);282283 await helper.wait.newBlocks(blocksBeforeExecution);284285 // execution #0286 expect((await helper.api!.query.testUtils.testValue()).toNumber())287 .to.be.equal(incTestVal);288289 await helper.wait.newBlocks(periodic.period);290291 // execution #1292 expect((await helper.api!.query.testUtils.testValue()).toNumber())293 .to.be.equal(finalTestVal);294295 for (let i = 1; i < periodic.repetitions; i++) {296 await waitNewBlocks(periodic.period);297 expect((await helper.api!.query.testUtils.testValue()).toNumber())298 .to.be.equal(finalTestVal);299 }300 });301302 itSub.ifWithPallets('A scheduled operation can cancel itself', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {303 const scheduledId = await helper.scheduler.makeScheduledId();304 const waitForBlocks = 8;305 const periodic = {306 period: 2,307 repetitions: 5,308 };309310 const initTestVal = 0;311 const maxTestVal = 2;312313 await helper.executeExtrinsic(314 alice,315 'api.tx.testUtils.setTestValue',316 [initTestVal],317 true,318 );319320 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})321 .executeExtrinsic(322 alice,323 'api.tx.testUtils.selfCancelingInc',324 [scheduledId, maxTestVal],325 true,326 );327328 await helper.wait.newBlocks(waitForBlocks + 1);329330 // execution #0331 expect((await helper.api!.query.testUtils.testValue()).toNumber())332 .to.be.equal(initTestVal + 1);333334 await helper.wait.newBlocks(periodic.period);335336 // execution #1337 expect((await helper.api!.query.testUtils.testValue()).toNumber())338 .to.be.equal(initTestVal + 2);339340 await helper.wait.newBlocks(periodic.period);341342 // <canceled>343 expect((await helper.api!.query.testUtils.testValue()).toNumber())344 .to.be.equal(initTestVal + 2);345 });346});347348describe('Negative Test: Scheduling', () => {349 let alice: IKeyringPair;350 let bob: IKeyringPair;351352 before(async () => {353 await usingPlaygrounds(async (_, privateKeyWrapper) => {354 alice = privateKeyWrapper('//Alice');355 bob = privateKeyWrapper('//Bob');356 });357 });358359 itSub.ifWithPallets("Can't overwrite a scheduled ID", [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {360 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});361 const token = await collection.mintToken(alice);362363 const scheduledId = await helper.scheduler.makeScheduledId();364 const waitForBlocks = 4;365366 await token.scheduleAfter(scheduledId, waitForBlocks)367 .transfer(alice, {Substrate: bob.address});368369 await expect(helper.scheduler.scheduleAfter(scheduledId, waitForBlocks)370 .balance.transferToSubstrate(alice, bob.address, 1n * UNIQUE))371 .to.be.rejectedWith(/scheduler\.FailedToSchedule/);372373 const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);374375 await helper.wait.newBlocks(waitForBlocks + 1);376377 const bobsBalanceAfter = await helper.balance.getSubstrate(bob.address);378379 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});380 expect(bobsBalanceBefore).to.be.equal(bobsBalanceAfter);381 });382383 itSub.ifWithPallets("Can't cancel an operation which is not scheduled", [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {384 const scheduledId = await helper.scheduler.makeScheduledId();385 await expect(helper.scheduler.cancelScheduled(alice, scheduledId))386 .to.be.rejectedWith(/scheduler\.NotFound/);387 });388389 itSub.ifWithPallets("Can't cancel a non-owned scheduled operation", [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {390 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});391 const token = await collection.mintToken(alice);392393 const scheduledId = await helper.scheduler.makeScheduledId();394 const waitForBlocks = 8;395396 await token.scheduleAfter(scheduledId, waitForBlocks)397 .transfer(alice, {Substrate: bob.address});398399 await expect(helper.scheduler.cancelScheduled(bob, scheduledId))400 .to.be.rejectedWith(/badOrigin/);401402 await helper.wait.newBlocks(waitForBlocks + 1);403404 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});405 });406});407408// Implementation of the functionality tested here was postponed/shelved409describe.skip('Sponsoring scheduling', () => {410 let alice: IKeyringPair;411 let bob: IKeyringPair;412413 before(async() => {414 await usingApi(async (_, privateKeyWrapper) => {415 alice = privateKeyWrapper('//Alice');416 bob = privateKeyWrapper('//Bob');417 });418 });419420 it('Can sponsor scheduling a transaction', async () => {421 const collectionId = await createCollectionExpectSuccess();422 await setCollectionSponsorExpectSuccess(collectionId, bob.address);423 await confirmSponsorshipExpectSuccess(collectionId, '//Bob');424425 await usingApi(async api => {426 const scheduledId = await makeScheduledId();427 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);428429 const bobBalanceBefore = await getFreeBalance(bob);430 const waitForBlocks = 4;431 // no need to wait to check, fees must be deducted on scheduling, immediately432 await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, scheduledId);433 const bobBalanceAfter = await getFreeBalance(bob);434 // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;435 expect(bobBalanceAfter < bobBalanceBefore).to.be.true;436 // wait for sequentiality matters437 await waitNewBlocks(waitForBlocks - 1);438 });439 });440441 it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {442 await usingApi(async (api, privateKeyWrapper) => {443 // Find an empty, unused account444 const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);445446 const collectionId = await createCollectionExpectSuccess();447448 // Add zeroBalance address to allow list449 await enablePublicMintingExpectSuccess(alice, collectionId);450 await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);451452 // Grace zeroBalance with money, enough to cover future transactions453 const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);454 await submitTransactionAsync(alice, balanceTx);455456 // Mint a fresh NFT457 const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');458 const scheduledId = await makeScheduledId();459460 // Schedule transfer of the NFT a few blocks ahead461 const waitForBlocks = 5;462 await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, scheduledId);463464 // Get rid of the account's funds before the scheduled transaction takes place465 const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);466 const events = await submitTransactionAsync(zeroBalance, balanceTx2);467 expect(getGenericResult(events).success).to.be.true;468 /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?469 const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);470 const events = await submitTransactionAsync(alice, sudoTx);471 expect(getGenericResult(events).success).to.be.true;*/472473 // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions474 await waitNewBlocks(waitForBlocks - 3);475476 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));477 });478 });479480 it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {481 const collectionId = await createCollectionExpectSuccess();482483 await usingApi(async (api, privateKeyWrapper) => {484 const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);485 const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);486 await submitTransactionAsync(alice, balanceTx);487488 await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);489 await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);490491 const scheduledId = await makeScheduledId();492 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);493494 const waitForBlocks = 5;495 await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, scheduledId);496497 const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);498 const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);499 const events = await submitTransactionAsync(alice, sudoTx);500 expect(getGenericResult(events).success).to.be.true;501502 // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions503 await waitNewBlocks(waitForBlocks - 3);504505 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));506 });507 });508509 it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {510 const collectionId = await createCollectionExpectSuccess();511 await setCollectionSponsorExpectSuccess(collectionId, bob.address);512 await confirmSponsorshipExpectSuccess(collectionId, '//Bob');513514 await usingApi(async (api, privateKeyWrapper) => {515 const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);516517 await enablePublicMintingExpectSuccess(alice, collectionId);518 await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);519520 const bobBalanceBefore = await getFreeBalance(bob);521522 const createData = {nft: {const_data: [], variable_data: []}};523 const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);524 const scheduledId = await makeScheduledId();525526 /*const badTransaction = async function () {527 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);528 };529 await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/530531 await expect(scheduleAfter(api, creationTx, zeroBalance, 3, scheduledId, 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);532533 expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);534 });535 });536});1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import {18 default as usingApi,19 submitTransactionAsync,20 submitTransactionExpectFailAsync,21} from '../substrate/substrate-api';22import {23 createItemExpectSuccess,24 createCollectionExpectSuccess,25 scheduleTransferExpectSuccess,26 setCollectionSponsorExpectSuccess,27 confirmSponsorshipExpectSuccess,28 findUnusedAddress,29 UNIQUE,30 enablePublicMintingExpectSuccess,31 addToAllowListExpectSuccess,32 waitNewBlocks,33 makeScheduledId,34 normalizeAccountId,35 getTokenOwner,36 getGenericResult,37 getFreeBalance,38 confirmSponsorshipByKeyExpectSuccess,39 scheduleExpectFailure,40 scheduleAfter,41} from './util/helpers';42import {expect, itSub, Pallets, usingPlaygrounds} from './util/playgrounds';43import {IKeyringPair} from '@polkadot/types/types';4445describe('Scheduling token and balance transfers', () => {46 let alice: IKeyringPair;47 let bob: IKeyringPair;48 let charlie: IKeyringPair;4950 before(async () => {51 await usingPlaygrounds(async (_, privateKeyWrapper) => {52 alice = privateKeyWrapper('//Alice');53 bob = privateKeyWrapper('//Bob');54 charlie = privateKeyWrapper('//Charlie');55 });56 });5758 itSub.ifWithPallets('Can delay a transfer of an owned token', [Pallets.Scheduler], async ({helper}) => {59 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});60 const token = await collection.mintToken(alice);61 const schedulerId = await helper.arrange.makeScheduledId();62 const blocksBeforeExecution = 4;6364 await token.scheduleAfter(schedulerId, blocksBeforeExecution)65 .transfer(alice, {Substrate: bob.address});6667 expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});6869 await helper.wait.newBlocks(blocksBeforeExecution + 1);7071 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});72 });7374 itSub.ifWithPallets('Can transfer funds periodically', [Pallets.Scheduler], async ({helper}) => {75 const scheduledId = await helper.arrange.makeScheduledId();76 const waitForBlocks = 1;7778 const amount = 1n * UNIQUE;79 const periodic = {80 period: 2,81 repetitions: 2,82 };8384 const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);8586 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})87 .balance.transferToSubstrate(alice, bob.address, amount);8889 await helper.wait.newBlocks(waitForBlocks + 1);9091 const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);92 expect(bobsBalanceAfterFirst)93 .to.be.equal(94 bobsBalanceBefore + 1n * amount,95 '#1 Balance of the recipient should be increased by 1 * amount',96 );9798 await helper.wait.newBlocks(periodic.period);99100 const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);101 expect(bobsBalanceAfterSecond)102 .to.be.equal(103 bobsBalanceBefore + 2n * amount,104 '#2 Balance of the recipient should be increased by 2 * amount',105 );106 });107108 itSub.ifWithPallets('Can cancel a scheduled operation which has not yet taken effect', [Pallets.Scheduler], async ({helper}) => {109 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});110 const token = await collection.mintToken(alice);111112 const scheduledId = await helper.arrange.makeScheduledId();113 const waitForBlocks = 4;114115 expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});116117 await token.scheduleAfter(scheduledId, waitForBlocks)118 .transfer(alice, {Substrate: bob.address});119120 await helper.scheduler.cancelScheduled(alice, scheduledId);121122 await waitNewBlocks(waitForBlocks + 1);123124 expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});125 });126127 itSub.ifWithPallets('Can cancel a periodic operation (transfer of funds)', [Pallets.Scheduler], async ({helper}) => {128 const waitForBlocks = 1;129 const periodic = {130 period: 3,131 repetitions: 2,132 };133134 const scheduledId = await helper.arrange.makeScheduledId();135136 const amount = 1n * UNIQUE;137138 const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);139140 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})141 .balance.transferToSubstrate(alice, bob.address, amount);142143 await helper.wait.newBlocks(waitForBlocks + 1);144145 const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);146147 expect(bobsBalanceAfterFirst)148 .to.be.equal(149 bobsBalanceBefore + 1n * amount,150 '#1 Balance of the recipient should be increased by 1 * amount',151 );152153 await helper.scheduler.cancelScheduled(alice, scheduledId);154 await helper.wait.newBlocks(periodic.period);155156 const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);157 expect(bobsBalanceAfterSecond)158 .to.be.equal(159 bobsBalanceAfterFirst,160 '#2 Balance of the recipient should not be changed',161 );162 });163164 itSub.ifWithPallets('Scheduled tasks are transactional', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {165 const scheduledId = await helper.arrange.makeScheduledId();166 const waitForBlocks = 4;167168 const initTestVal = 42;169 const changedTestVal = 111;170171 await helper.executeExtrinsic(172 alice,173 'api.tx.testUtils.setTestValue',174 [initTestVal],175 true,176 );177178 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks)179 .executeExtrinsic(180 alice,181 'api.tx.testUtils.setTestValueAndRollback',182 [changedTestVal],183 true,184 );185186 await helper.wait.newBlocks(waitForBlocks + 1);187188 const testVal = (await helper.api!.query.testUtils.testValue()).toNumber();189 expect(testVal, 'The test value should NOT be commited')190 .to.be.equal(initTestVal);191 });192193 itSub.ifWithPallets('Scheduled tasks should take correct fees', [Pallets.Scheduler, Pallets.TestUtils], async function({helper}) {194 const scheduledId = await helper.arrange.makeScheduledId();195 const waitForBlocks = 8;196 const periodic = {197 period: 2,198 repetitions: 2,199 };200201 const dummyTx = helper.constructApiCall('api.tx.testUtils.justTakeFee', []);202 const scheduledLen = dummyTx.callIndex.length;203204 const expectedScheduledFee = (await helper.getPaymentInfo(alice, dummyTx, scheduledLen))205 .partialFee.toBigInt();206207 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})208 .executeExtrinsic(alice, 'api.tx.testUtils.justTakeFee', [], true);209210 await helper.wait.newBlocks(1);211212 const aliceInitBalance = await helper.balance.getSubstrate(alice.address);213 let diff;214215 await helper.wait.newBlocks(waitForBlocks);216217 const aliceBalanceAfterFirst = await helper.balance.getSubstrate(alice.address);218 expect(219 aliceBalanceAfterFirst < aliceInitBalance,220 '[after execution #1] Scheduled task should take a fee',221 ).to.be.true;222223 diff = aliceInitBalance - aliceBalanceAfterFirst;224 expect(diff).to.be.equal(225 expectedScheduledFee,226 'Scheduled task should take the right amount of fees',227 );228229 await helper.wait.newBlocks(periodic.period);230231 const aliceBalanceAfterSecond = await helper.balance.getSubstrate(alice.address);232 expect(233 aliceBalanceAfterSecond < aliceBalanceAfterFirst,234 '[after execution #2] Scheduled task should take a fee',235 ).to.be.true;236237 diff = aliceBalanceAfterFirst - aliceBalanceAfterSecond;238 expect(diff).to.be.equal(239 expectedScheduledFee,240 'Scheduled task should take the right amount of fees',241 );242 });243244 // Check if we can cancel a scheduled periodic operation245 // in the same block in which it is running246 itSub.ifWithPallets('Can cancel the periodic sheduled tx when the tx is running', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {247 const currentBlockNumber = await helper.chain.getLatestBlockNumber();248 const blocksBeforeExecution = 10;249 const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;250251 const [252 scheduledId,253 scheduledCancelId,254 ] = await helper.arrange.makeScheduledIds(2);255256 const periodic = {257 period: 5,258 repetitions: 5,259 };260261 const initTestVal = 0;262 const incTestVal = initTestVal + 1;263 const finalTestVal = initTestVal + 2;264265 await helper.executeExtrinsic(266 alice,267 'api.tx.testUtils.setTestValue',268 [initTestVal],269 true,270 );271272 await helper.scheduler.scheduleAt(scheduledId, firstExecutionBlockNumber, {periodic})273 .executeExtrinsic(274 alice,275 'api.tx.testUtils.incTestValue',276 [],277 true,278 );279280 // Cancel the inc tx after 2 executions281 // *in the same block* in which the second execution is scheduled282 await helper.scheduler.scheduleAt(283 scheduledCancelId,284 firstExecutionBlockNumber + periodic.period,285 ).scheduler.cancelScheduled(alice, scheduledId);286287 await helper.wait.newBlocks(blocksBeforeExecution);288289 // execution #0290 expect((await helper.api!.query.testUtils.testValue()).toNumber())291 .to.be.equal(incTestVal);292293 await helper.wait.newBlocks(periodic.period);294295 // execution #1296 expect((await helper.api!.query.testUtils.testValue()).toNumber())297 .to.be.equal(finalTestVal);298299 for (let i = 1; i < periodic.repetitions; i++) {300 await waitNewBlocks(periodic.period);301 expect((await helper.api!.query.testUtils.testValue()).toNumber())302 .to.be.equal(finalTestVal);303 }304 });305306 itSub.ifWithPallets('A scheduled operation can cancel itself', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {307 const scheduledId = await helper.arrange.makeScheduledId();308 const waitForBlocks = 8;309 const periodic = {310 period: 2,311 repetitions: 5,312 };313314 const initTestVal = 0;315 const maxTestVal = 2;316317 await helper.executeExtrinsic(318 alice,319 'api.tx.testUtils.setTestValue',320 [initTestVal],321 true,322 );323324 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})325 .executeExtrinsic(326 alice,327 'api.tx.testUtils.selfCancelingInc',328 [scheduledId, maxTestVal],329 true,330 );331332 await helper.wait.newBlocks(waitForBlocks + 1);333334 // execution #0335 expect((await helper.api!.query.testUtils.testValue()).toNumber())336 .to.be.equal(initTestVal + 1);337338 await helper.wait.newBlocks(periodic.period);339340 // execution #1341 expect((await helper.api!.query.testUtils.testValue()).toNumber())342 .to.be.equal(initTestVal + 2);343344 await helper.wait.newBlocks(periodic.period);345346 // <canceled>347 expect((await helper.api!.query.testUtils.testValue()).toNumber())348 .to.be.equal(initTestVal + 2);349 });350351 itSub.ifWithPallets('Root can cancel any scheduled operation', [Pallets.Scheduler], async ({helper}) => {352 const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});353 const token = await collection.mintToken(bob);354355 const scheduledId = await helper.arrange.makeScheduledId();356 const waitForBlocks = 4;357358 await token.scheduleAfter(scheduledId, waitForBlocks)359 .transfer(bob, {Substrate: alice.address});360361 await helper.getSudo().scheduler.cancelScheduled(alice, scheduledId);362363 await helper.wait.newBlocks(waitForBlocks + 1);364365 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});366 });367368 itSub.ifWithPallets('Root can set prioritized scheduled operation', [Pallets.Scheduler], async ({helper}) => {369 const scheduledId = await helper.arrange.makeScheduledId();370 const waitForBlocks = 4;371372 const amount = 42n * UNIQUE;373374 const balanceBefore = await helper.balance.getSubstrate(charlie.address);375376 await helper.getSudo()377 .scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42})378 .balance.forceTransferToSubstrate(alice, bob.address, charlie.address, amount);379380 await helper.wait.newBlocks(waitForBlocks + 1);381382 const balanceAfter = await helper.balance.getSubstrate(charlie.address);383384 expect(balanceAfter > balanceBefore).to.be.true;385386 const diff = balanceAfter - balanceBefore;387 expect(diff).to.be.equal(amount);388 });389390 itSub.ifWithPallets("Root can change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {391 const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});392 const token = await collection.mintToken(bob);393394 const scheduledId = await helper.arrange.makeScheduledId();395 const waitForBlocks = 4;396397 await token.scheduleAfter(scheduledId, waitForBlocks)398 .transfer(bob, {Substrate: alice.address});399400 const priority = 112;401 await helper.getSudo().scheduler.changePriority(alice, scheduledId, priority);402403 const priorityChanged = await helper.wait.event(404 waitForBlocks,405 'scheduler',406 'PriorityChanged',407 );408409 expect(priorityChanged !== null).to.be.true;410 expect(priorityChanged!.event.data[2].toString()).to.be.equal(priority.toString());411 });412413 itSub.ifWithPallets.only('Prioritized operations executes in valid order', [Pallets.Scheduler], async ({helper}) => {414 const [415 scheduledFirstId,416 scheduledSecondId,417 ] = await helper.arrange.makeScheduledIds(2);418419 const currentBlockNumber = await helper.chain.getLatestBlockNumber();420 const blocksBeforeExecution = 4;421 const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;422423 const prioHigh = 0;424 const prioLow = 255;425426 const periodic = {427 period: 8,428 repetitions: 2,429 };430431 const amount = 1n * UNIQUE;432433 // Scheduler a task with a lower priority first, then with a higher priority434 await helper.getSudo().scheduler.scheduleAt(scheduledFirstId, firstExecutionBlockNumber, {priority: prioLow, periodic})435 .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);436437 await helper.getSudo().scheduler.scheduleAt(scheduledSecondId, firstExecutionBlockNumber, {priority: prioHigh, periodic})438 .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);439440 const capture = await helper.arrange.captureEvents('scheduler', 'Dispatched');441442 await helper.wait.newBlocks(blocksBeforeExecution);443444 // Flip priorities445 await helper.getSudo().scheduler.changePriority(alice, scheduledFirstId, prioHigh);446 await helper.getSudo().scheduler.changePriority(alice, scheduledSecondId, prioLow);447448 await helper.wait.newBlocks(periodic.period);449450 const dispatchEvents = capture.extractCapturedEvents();451 expect(dispatchEvents.length).to.be.equal(4);452453 const dispatchedIds = dispatchEvents.map(r => r.event.data[1].toString());454455 const firstExecuctionIds = [dispatchedIds[0], dispatchedIds[1]];456 const secondExecuctionIds = [dispatchedIds[2], dispatchedIds[3]];457458 expect(firstExecuctionIds[0]).to.be.equal(scheduledSecondId);459 expect(firstExecuctionIds[1]).to.be.equal(scheduledFirstId);460461 expect(secondExecuctionIds[0]).to.be.equal(scheduledFirstId);462 expect(secondExecuctionIds[1]).to.be.equal(scheduledSecondId);463 });464});465466describe('Negative Test: Scheduling', () => {467 let alice: IKeyringPair;468 let bob: IKeyringPair;469470 before(async () => {471 await usingPlaygrounds(async (_, privateKeyWrapper) => {472 alice = privateKeyWrapper('//Alice');473 bob = privateKeyWrapper('//Bob');474 });475 });476477 itSub.ifWithPallets("Can't overwrite a scheduled ID", [Pallets.Scheduler], async ({helper}) => {478 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});479 const token = await collection.mintToken(alice);480481 const scheduledId = await helper.arrange.makeScheduledId();482 const waitForBlocks = 4;483484 await token.scheduleAfter(scheduledId, waitForBlocks)485 .transfer(alice, {Substrate: bob.address});486487 const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks);488 await expect(scheduled.balance.transferToSubstrate(alice, bob.address, 1n * UNIQUE))489 .to.be.rejectedWith(/scheduler\.FailedToSchedule/);490491 const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);492493 await helper.wait.newBlocks(waitForBlocks + 1);494495 const bobsBalanceAfter = await helper.balance.getSubstrate(bob.address);496497 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});498 expect(bobsBalanceBefore).to.be.equal(bobsBalanceAfter);499 });500501 itSub.ifWithPallets("Can't cancel an operation which is not scheduled", [Pallets.Scheduler], async ({helper}) => {502 const scheduledId = await helper.arrange.makeScheduledId();503 await expect(helper.scheduler.cancelScheduled(alice, scheduledId))504 .to.be.rejectedWith(/scheduler\.NotFound/);505 });506507 itSub.ifWithPallets("Can't cancel a non-owned scheduled operation", [Pallets.Scheduler], async ({helper}) => {508 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});509 const token = await collection.mintToken(alice);510511 const scheduledId = await helper.arrange.makeScheduledId();512 const waitForBlocks = 8;513514 await token.scheduleAfter(scheduledId, waitForBlocks)515 .transfer(alice, {Substrate: bob.address});516517 await expect(helper.scheduler.cancelScheduled(bob, scheduledId))518 .to.be.rejectedWith(/badOrigin/);519520 await helper.wait.newBlocks(waitForBlocks + 1);521522 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});523 });524525 itSub.ifWithPallets("Regular user can't set prioritized scheduled operation", [Pallets.Scheduler], async ({helper}) => {526 const scheduledId = await helper.arrange.makeScheduledId();527 const waitForBlocks = 4;528529 const amount = 42n * UNIQUE;530531 const balanceBefore = await helper.balance.getSubstrate(bob.address);532533 const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42});534 535 await expect(scheduled.balance.transferToSubstrate(alice, bob.address, amount))536 .to.be.rejectedWith(/badOrigin/);537538 await helper.wait.newBlocks(waitForBlocks + 1);539540 const balanceAfter = await helper.balance.getSubstrate(bob.address);541542 expect(balanceAfter).to.be.equal(balanceBefore);543 });544545 itSub.ifWithPallets("Regular user can't change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {546 const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});547 const token = await collection.mintToken(bob);548549 const scheduledId = await helper.arrange.makeScheduledId();550 const waitForBlocks = 4;551552 await token.scheduleAfter(scheduledId, waitForBlocks)553 .transfer(bob, {Substrate: alice.address});554555 const priority = 112;556 await expect(helper.scheduler.changePriority(alice, scheduledId, priority))557 .to.be.rejectedWith(/badOrigin/);558559 const priorityChanged = await helper.wait.event(560 waitForBlocks,561 'scheduler',562 'PriorityChanged',563 );564565 expect(priorityChanged === null).to.be.true;566 });567});568569// Implementation of the functionality tested here was postponed/shelved570describe.skip('Sponsoring scheduling', () => {571 let alice: IKeyringPair;572 let bob: IKeyringPair;573574 before(async() => {575 await usingApi(async (_, privateKeyWrapper) => {576 alice = privateKeyWrapper('//Alice');577 bob = privateKeyWrapper('//Bob');578 });579 });580581 it('Can sponsor scheduling a transaction', async () => {582 const collectionId = await createCollectionExpectSuccess();583 await setCollectionSponsorExpectSuccess(collectionId, bob.address);584 await confirmSponsorshipExpectSuccess(collectionId, '//Bob');585586 await usingApi(async api => {587 const scheduledId = await makeScheduledId();588 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);589590 const bobBalanceBefore = await getFreeBalance(bob);591 const waitForBlocks = 4;592 // no need to wait to check, fees must be deducted on scheduling, immediately593 await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, scheduledId);594 const bobBalanceAfter = await getFreeBalance(bob);595 // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;596 expect(bobBalanceAfter < bobBalanceBefore).to.be.true;597 // wait for sequentiality matters598 await waitNewBlocks(waitForBlocks - 1);599 });600 });601602 it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {603 await usingApi(async (api, privateKeyWrapper) => {604 // Find an empty, unused account605 const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);606607 const collectionId = await createCollectionExpectSuccess();608609 // Add zeroBalance address to allow list610 await enablePublicMintingExpectSuccess(alice, collectionId);611 await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);612613 // Grace zeroBalance with money, enough to cover future transactions614 const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);615 await submitTransactionAsync(alice, balanceTx);616617 // Mint a fresh NFT618 const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');619 const scheduledId = await makeScheduledId();620621 // Schedule transfer of the NFT a few blocks ahead622 const waitForBlocks = 5;623 await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, scheduledId);624625 // Get rid of the account's funds before the scheduled transaction takes place626 const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);627 const events = await submitTransactionAsync(zeroBalance, balanceTx2);628 expect(getGenericResult(events).success).to.be.true;629 /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?630 const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);631 const events = await submitTransactionAsync(alice, sudoTx);632 expect(getGenericResult(events).success).to.be.true;*/633634 // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions635 await waitNewBlocks(waitForBlocks - 3);636637 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));638 });639 });640641 it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {642 const collectionId = await createCollectionExpectSuccess();643644 await usingApi(async (api, privateKeyWrapper) => {645 const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);646 const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);647 await submitTransactionAsync(alice, balanceTx);648649 await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);650 await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);651652 const scheduledId = await makeScheduledId();653 const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);654655 const waitForBlocks = 5;656 await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, scheduledId);657658 const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);659 const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);660 const events = await submitTransactionAsync(alice, sudoTx);661 expect(getGenericResult(events).success).to.be.true;662663 // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions664 await waitNewBlocks(waitForBlocks - 3);665666 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));667 });668 });669670 it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {671 const collectionId = await createCollectionExpectSuccess();672 await setCollectionSponsorExpectSuccess(collectionId, bob.address);673 await confirmSponsorshipExpectSuccess(collectionId, '//Bob');674675 await usingApi(async (api, privateKeyWrapper) => {676 const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);677678 await enablePublicMintingExpectSuccess(alice, collectionId);679 await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);680681 const bobBalanceBefore = await getFreeBalance(bob);682683 const createData = {nft: {const_data: [], variable_data: []}};684 const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);685 const scheduledId = await makeScheduledId();686687 /*const badTransaction = async function () {688 await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);689 };690 await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/691692 await expect(scheduleAfter(api, creationTx, zeroBalance, 3, scheduledId, 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);693694 expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);695 });696 });697});