1234567891011121314151617import {18 default as usingApi,19 submitTransactionAsync,20 submitTransactionExpectFailAsync,21} from '../substrate/substrate-api';22import {23 UNIQUE,24 waitNewBlocks,25} from './util/helpers';26import {expect, itSub, Pallets, usingPlaygrounds} from './util/playgrounds';27import {IKeyringPair} from '@polkadot/types/types';2829describe('Scheduling token and balance transfers', () => {30 let alice: IKeyringPair;31 let bob: IKeyringPair;32 let charlie: IKeyringPair;3334 before(async () => {35 await usingPlaygrounds(async (_, privateKeyWrapper) => {36 alice = privateKeyWrapper('//Alice');37 bob = privateKeyWrapper('//Bob');38 charlie = privateKeyWrapper('//Charlie');39 });40 });4142 itSub.ifWithPallets('Can delay a transfer of an owned token', [Pallets.Scheduler], async ({helper}) => {43 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});44 const token = await collection.mintToken(alice);45 const schedulerId = await helper.arrange.makeScheduledId();46 const blocksBeforeExecution = 4;4748 await token.scheduleAfter(schedulerId, blocksBeforeExecution)49 .transfer(alice, {Substrate: bob.address});5051 expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});5253 await helper.wait.newBlocks(blocksBeforeExecution + 1);5455 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});56 });5758 itSub.ifWithPallets('Can transfer funds periodically', [Pallets.Scheduler], async ({helper}) => {59 const scheduledId = await helper.arrange.makeScheduledId();60 const waitForBlocks = 1;6162 const amount = 1n * UNIQUE;63 const periodic = {64 period: 2,65 repetitions: 2,66 };6768 const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);6970 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})71 .balance.transferToSubstrate(alice, bob.address, amount);7273 await helper.wait.newBlocks(waitForBlocks + 1);7475 const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);76 expect(bobsBalanceAfterFirst)77 .to.be.equal(78 bobsBalanceBefore + 1n * amount,79 '#1 Balance of the recipient should be increased by 1 * amount',80 );8182 await helper.wait.newBlocks(periodic.period);8384 const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);85 expect(bobsBalanceAfterSecond)86 .to.be.equal(87 bobsBalanceBefore + 2n * amount,88 '#2 Balance of the recipient should be increased by 2 * amount',89 );90 });9192 itSub.ifWithPallets('Can cancel a scheduled operation which has not yet taken effect', [Pallets.Scheduler], async ({helper}) => {93 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});94 const token = await collection.mintToken(alice);9596 const scheduledId = await helper.arrange.makeScheduledId();97 const waitForBlocks = 4;9899 expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});100101 await token.scheduleAfter(scheduledId, waitForBlocks)102 .transfer(alice, {Substrate: bob.address});103104 await helper.scheduler.cancelScheduled(alice, scheduledId);105106 await waitNewBlocks(waitForBlocks + 1);107108 expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});109 });110111 itSub.ifWithPallets('Can cancel a periodic operation (transfer of funds)', [Pallets.Scheduler], async ({helper}) => {112 const waitForBlocks = 1;113 const periodic = {114 period: 3,115 repetitions: 2,116 };117118 const scheduledId = await helper.arrange.makeScheduledId();119120 const amount = 1n * UNIQUE;121122 const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);123124 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})125 .balance.transferToSubstrate(alice, bob.address, amount);126127 await helper.wait.newBlocks(waitForBlocks + 1);128129 const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);130131 expect(bobsBalanceAfterFirst)132 .to.be.equal(133 bobsBalanceBefore + 1n * amount,134 '#1 Balance of the recipient should be increased by 1 * amount',135 );136137 await helper.scheduler.cancelScheduled(alice, scheduledId);138 await helper.wait.newBlocks(periodic.period);139140 const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);141 expect(bobsBalanceAfterSecond)142 .to.be.equal(143 bobsBalanceAfterFirst,144 '#2 Balance of the recipient should not be changed',145 );146 });147148 itSub.ifWithPallets('Scheduled tasks are transactional', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {149 const scheduledId = await helper.arrange.makeScheduledId();150 const waitForBlocks = 4;151152 const initTestVal = 42;153 const changedTestVal = 111;154155 await helper.executeExtrinsic(156 alice,157 'api.tx.testUtils.setTestValue',158 [initTestVal],159 true,160 );161162 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks)163 .executeExtrinsic(164 alice,165 'api.tx.testUtils.setTestValueAndRollback',166 [changedTestVal],167 true,168 );169170 await helper.wait.newBlocks(waitForBlocks + 1);171172 const testVal = (await helper.api!.query.testUtils.testValue()).toNumber();173 expect(testVal, 'The test value should NOT be commited')174 .to.be.equal(initTestVal);175 });176177 itSub.ifWithPallets('Scheduled tasks should take correct fees', [Pallets.Scheduler, Pallets.TestUtils], async function({helper}) {178 const scheduledId = await helper.arrange.makeScheduledId();179 const waitForBlocks = 4;180 const periodic = {181 period: 2,182 repetitions: 2,183 };184185 const dummyTx = helper.constructApiCall('api.tx.testUtils.justTakeFee', []);186 const scheduledLen = dummyTx.callIndex.length;187188 const expectedScheduledFee = (await helper.getPaymentInfo(alice, dummyTx, scheduledLen))189 .partialFee.toBigInt();190191 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})192 .executeExtrinsic(alice, 'api.tx.testUtils.justTakeFee', [], true);193194 await helper.wait.newBlocks(1);195196 const aliceInitBalance = await helper.balance.getSubstrate(alice.address);197 let diff;198199 await helper.wait.newBlocks(waitForBlocks);200201 const aliceBalanceAfterFirst = await helper.balance.getSubstrate(alice.address);202 expect(203 aliceBalanceAfterFirst < aliceInitBalance,204 '[after execution #1] Scheduled task should take a fee',205 ).to.be.true;206207 diff = aliceInitBalance - aliceBalanceAfterFirst;208 expect(diff).to.be.equal(209 expectedScheduledFee,210 'Scheduled task should take the right amount of fees',211 );212213 await helper.wait.newBlocks(periodic.period);214215 const aliceBalanceAfterSecond = await helper.balance.getSubstrate(alice.address);216 expect(217 aliceBalanceAfterSecond < aliceBalanceAfterFirst,218 '[after execution #2] Scheduled task should take a fee',219 ).to.be.true;220221 diff = aliceBalanceAfterFirst - aliceBalanceAfterSecond;222 expect(diff).to.be.equal(223 expectedScheduledFee,224 'Scheduled task should take the right amount of fees',225 );226 });227228 229 230 itSub.ifWithPallets('Can cancel the periodic sheduled tx when the tx is running', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {231 const currentBlockNumber = await helper.chain.getLatestBlockNumber();232 const blocksBeforeExecution = 10;233 const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;234235 const [236 scheduledId,237 scheduledCancelId,238 ] = await helper.arrange.makeScheduledIds(2);239240 const periodic = {241 period: 5,242 repetitions: 5,243 };244245 const initTestVal = 0;246 const incTestVal = initTestVal + 1;247 const finalTestVal = initTestVal + 2;248249 await helper.executeExtrinsic(250 alice,251 'api.tx.testUtils.setTestValue',252 [initTestVal],253 true,254 );255256 await helper.scheduler.scheduleAt(scheduledId, firstExecutionBlockNumber, {periodic})257 .executeExtrinsic(258 alice,259 'api.tx.testUtils.incTestValue',260 [],261 true,262 );263264 265 266 await helper.scheduler.scheduleAt(267 scheduledCancelId,268 firstExecutionBlockNumber + periodic.period,269 ).scheduler.cancelScheduled(alice, scheduledId);270271 await helper.wait.newBlocks(blocksBeforeExecution);272273 274 expect((await helper.api!.query.testUtils.testValue()).toNumber())275 .to.be.equal(incTestVal);276277 await helper.wait.newBlocks(periodic.period);278279 280 expect((await helper.api!.query.testUtils.testValue()).toNumber())281 .to.be.equal(finalTestVal);282283 for (let i = 1; i < periodic.repetitions; i++) {284 await waitNewBlocks(periodic.period);285 expect((await helper.api!.query.testUtils.testValue()).toNumber())286 .to.be.equal(finalTestVal);287 }288 });289290 itSub.ifWithPallets('A scheduled operation can cancel itself', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {291 const scheduledId = await helper.arrange.makeScheduledId();292 const waitForBlocks = 4;293 const periodic = {294 period: 2,295 repetitions: 5,296 };297298 const initTestVal = 0;299 const maxTestVal = 2;300301 await helper.executeExtrinsic(302 alice,303 'api.tx.testUtils.setTestValue',304 [initTestVal],305 true,306 );307308 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})309 .executeExtrinsic(310 alice,311 'api.tx.testUtils.selfCancelingInc',312 [scheduledId, maxTestVal],313 true,314 );315316 await helper.wait.newBlocks(waitForBlocks + 1);317318 319 expect((await helper.api!.query.testUtils.testValue()).toNumber())320 .to.be.equal(initTestVal + 1);321322 await helper.wait.newBlocks(periodic.period);323324 325 expect((await helper.api!.query.testUtils.testValue()).toNumber())326 .to.be.equal(initTestVal + 2);327328 await helper.wait.newBlocks(periodic.period);329330 331 expect((await helper.api!.query.testUtils.testValue()).toNumber())332 .to.be.equal(initTestVal + 2);333 });334335 itSub.ifWithPallets('Root can cancel any scheduled operation', [Pallets.Scheduler], async ({helper}) => {336 const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});337 const token = await collection.mintToken(bob);338339 const scheduledId = await helper.arrange.makeScheduledId();340 const waitForBlocks = 4;341342 await token.scheduleAfter(scheduledId, waitForBlocks)343 .transfer(bob, {Substrate: alice.address});344345 await helper.getSudo().scheduler.cancelScheduled(alice, scheduledId);346347 await helper.wait.newBlocks(waitForBlocks + 1);348349 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});350 });351352 itSub.ifWithPallets('Root can set prioritized scheduled operation', [Pallets.Scheduler], async ({helper}) => {353 const scheduledId = await helper.arrange.makeScheduledId();354 const waitForBlocks = 4;355356 const amount = 42n * UNIQUE;357358 const balanceBefore = await helper.balance.getSubstrate(charlie.address);359360 await helper.getSudo()361 .scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42})362 .balance.forceTransferToSubstrate(alice, bob.address, charlie.address, amount);363364 await helper.wait.newBlocks(waitForBlocks + 1);365366 const balanceAfter = await helper.balance.getSubstrate(charlie.address);367368 expect(balanceAfter > balanceBefore).to.be.true;369370 const diff = balanceAfter - balanceBefore;371 expect(diff).to.be.equal(amount);372 });373374 itSub.ifWithPallets("Root can change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {375 const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});376 const token = await collection.mintToken(bob);377378 const scheduledId = await helper.arrange.makeScheduledId();379 const waitForBlocks = 6;380381 await token.scheduleAfter(scheduledId, waitForBlocks)382 .transfer(bob, {Substrate: alice.address});383384 const priority = 112;385 await helper.getSudo().scheduler.changePriority(alice, scheduledId, priority);386387 const priorityChanged = await helper.wait.event(388 waitForBlocks,389 'scheduler',390 'PriorityChanged',391 );392393 expect(priorityChanged !== null).to.be.true;394 expect(priorityChanged!.event.data[2].toString()).to.be.equal(priority.toString());395 });396397 itSub.ifWithPallets('Prioritized operations executes in valid order', [Pallets.Scheduler], async ({helper}) => {398 const [399 scheduledFirstId,400 scheduledSecondId,401 ] = await helper.arrange.makeScheduledIds(2);402403 const currentBlockNumber = await helper.chain.getLatestBlockNumber();404 const blocksBeforeExecution = 4;405 const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;406407 const prioHigh = 0;408 const prioLow = 255;409410 const periodic = {411 period: 6,412 repetitions: 2,413 };414415 const amount = 1n * UNIQUE;416417 418 await helper.getSudo().scheduler.scheduleAt(scheduledFirstId, firstExecutionBlockNumber, {priority: prioLow, periodic})419 .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);420421 await helper.getSudo().scheduler.scheduleAt(scheduledSecondId, firstExecutionBlockNumber, {priority: prioHigh, periodic})422 .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);423424 const capture = await helper.arrange.captureEvents('scheduler', 'Dispatched');425426 await helper.wait.newBlocks(blocksBeforeExecution);427428 429 await helper.getSudo().scheduler.changePriority(alice, scheduledFirstId, prioHigh);430 await helper.getSudo().scheduler.changePriority(alice, scheduledSecondId, prioLow);431432 await helper.wait.newBlocks(periodic.period);433434 const dispatchEvents = capture.extractCapturedEvents();435 expect(dispatchEvents.length).to.be.equal(4);436437 const dispatchedIds = dispatchEvents.map(r => r.event.data[1].toString());438439 const firstExecuctionIds = [dispatchedIds[0], dispatchedIds[1]];440 const secondExecuctionIds = [dispatchedIds[2], dispatchedIds[3]];441442 expect(firstExecuctionIds[0]).to.be.equal(scheduledSecondId);443 expect(firstExecuctionIds[1]).to.be.equal(scheduledFirstId);444445 expect(secondExecuctionIds[0]).to.be.equal(scheduledFirstId);446 expect(secondExecuctionIds[1]).to.be.equal(scheduledSecondId);447 });448});449450describe('Negative Test: Scheduling', () => {451 let alice: IKeyringPair;452 let bob: IKeyringPair;453454 before(async () => {455 await usingPlaygrounds(async (_, privateKeyWrapper) => {456 alice = privateKeyWrapper('//Alice');457 bob = privateKeyWrapper('//Bob');458 });459 });460461 itSub.ifWithPallets("Can't overwrite a scheduled ID", [Pallets.Scheduler], async ({helper}) => {462 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});463 const token = await collection.mintToken(alice);464465 const scheduledId = await helper.arrange.makeScheduledId();466 const waitForBlocks = 4;467468 await token.scheduleAfter(scheduledId, waitForBlocks)469 .transfer(alice, {Substrate: bob.address});470471 const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks);472 await expect(scheduled.balance.transferToSubstrate(alice, bob.address, 1n * UNIQUE))473 .to.be.rejectedWith(/scheduler\.FailedToSchedule/);474475 const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);476477 await helper.wait.newBlocks(waitForBlocks + 1);478479 const bobsBalanceAfter = await helper.balance.getSubstrate(bob.address);480481 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});482 expect(bobsBalanceBefore).to.be.equal(bobsBalanceAfter);483 });484485 itSub.ifWithPallets("Can't cancel an operation which is not scheduled", [Pallets.Scheduler], async ({helper}) => {486 const scheduledId = await helper.arrange.makeScheduledId();487 await expect(helper.scheduler.cancelScheduled(alice, scheduledId))488 .to.be.rejectedWith(/scheduler\.NotFound/);489 });490491 itSub.ifWithPallets("Can't cancel a non-owned scheduled operation", [Pallets.Scheduler], async ({helper}) => {492 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});493 const token = await collection.mintToken(alice);494495 const scheduledId = await helper.arrange.makeScheduledId();496 const waitForBlocks = 4;497498 await token.scheduleAfter(scheduledId, waitForBlocks)499 .transfer(alice, {Substrate: bob.address});500501 await expect(helper.scheduler.cancelScheduled(bob, scheduledId))502 .to.be.rejectedWith(/badOrigin/);503504 await helper.wait.newBlocks(waitForBlocks + 1);505506 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});507 });508509 itSub.ifWithPallets("Regular user can't set prioritized scheduled operation", [Pallets.Scheduler], async ({helper}) => {510 const scheduledId = await helper.arrange.makeScheduledId();511 const waitForBlocks = 4;512513 const amount = 42n * UNIQUE;514515 const balanceBefore = await helper.balance.getSubstrate(bob.address);516517 const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42});518 519 await expect(scheduled.balance.transferToSubstrate(alice, bob.address, amount))520 .to.be.rejectedWith(/badOrigin/);521522 await helper.wait.newBlocks(waitForBlocks + 1);523524 const balanceAfter = await helper.balance.getSubstrate(bob.address);525526 expect(balanceAfter).to.be.equal(balanceBefore);527 });528529 itSub.ifWithPallets("Regular user can't change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {530 const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});531 const token = await collection.mintToken(bob);532533 const scheduledId = await helper.arrange.makeScheduledId();534 const waitForBlocks = 4;535536 await token.scheduleAfter(scheduledId, waitForBlocks)537 .transfer(bob, {Substrate: alice.address});538539 const priority = 112;540 await expect(helper.scheduler.changePriority(alice, scheduledId, priority))541 .to.be.rejectedWith(/badOrigin/);542543 const priorityChanged = await helper.wait.event(544 waitForBlocks,545 'scheduler',546 'PriorityChanged',547 );548549 expect(priorityChanged === null).to.be.true;550 });551});552553554describe.skip('Sponsoring scheduling', () => {555 556 557558 559 560 561 562 563 564565 it('Can sponsor scheduling a transaction', async () => {566 567 568 569570 571 572 573574 575 576 577 578 579 580 581 582 583 584 });585586 it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {587 588 589 590591 592593 594 595 596597 598 599 600601 602 603 604605 606 607 608609 610 611 612 613 614 615 616 617618 619 620621 622 623 });624625 it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {626 627628 629 630 631 632633 634 635636 637 638639 640 641642 643 644 645 646647 648 649650 651 652 });653654 it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {655 656 657 658659 660 661662 663 664665 666667 668 669 670671 672 673 674 675676 677678 679 680 });681});