1234567891011121314151617import {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 normalizeAccountId,34 getTokenOwner,35 getGenericResult,36 getFreeBalance,37 confirmSponsorshipByKeyExpectSuccess,38 scheduleExpectFailure,39 scheduleAfter,40} from './util/helpers';41import {expect, itSub, Pallets, usingPlaygrounds} from './util/playgrounds';42import {IKeyringPair} from '@polkadot/types/types';4344describe('Scheduling token and balance transfers', () => {45 let alice: IKeyringPair;46 let bob: IKeyringPair;47 let charlie: IKeyringPair;4849 before(async () => {50 await usingPlaygrounds(async (_, privateKeyWrapper) => {51 alice = privateKeyWrapper('//Alice');52 bob = privateKeyWrapper('//Bob');53 charlie = privateKeyWrapper('//Charlie');54 });55 });5657 itSub.ifWithPallets('Can delay a transfer of an owned token', [Pallets.Scheduler], async ({helper}) => {58 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});59 const token = await collection.mintToken(alice);60 const schedulerId = await helper.arrange.makeScheduledId();61 const blocksBeforeExecution = 4;6263 await token.scheduleAfter(schedulerId, blocksBeforeExecution)64 .transfer(alice, {Substrate: bob.address});6566 expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});6768 await helper.wait.newBlocks(blocksBeforeExecution + 1);6970 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});71 });7273 itSub.ifWithPallets('Can transfer funds periodically', [Pallets.Scheduler], async ({helper}) => {74 const scheduledId = await helper.arrange.makeScheduledId();75 const waitForBlocks = 1;7677 const amount = 1n * UNIQUE;78 const periodic = {79 period: 2,80 repetitions: 2,81 };8283 const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);8485 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})86 .balance.transferToSubstrate(alice, bob.address, amount);8788 await helper.wait.newBlocks(waitForBlocks + 1);8990 const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);91 expect(bobsBalanceAfterFirst)92 .to.be.equal(93 bobsBalanceBefore + 1n * amount,94 '#1 Balance of the recipient should be increased by 1 * amount',95 );9697 await helper.wait.newBlocks(periodic.period);9899 const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);100 expect(bobsBalanceAfterSecond)101 .to.be.equal(102 bobsBalanceBefore + 2n * amount,103 '#2 Balance of the recipient should be increased by 2 * amount',104 );105 });106107 itSub.ifWithPallets('Can cancel a scheduled operation which has not yet taken effect', [Pallets.Scheduler], async ({helper}) => {108 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});109 const token = await collection.mintToken(alice);110111 const scheduledId = await helper.arrange.makeScheduledId();112 const waitForBlocks = 4;113114 expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});115116 await token.scheduleAfter(scheduledId, waitForBlocks)117 .transfer(alice, {Substrate: bob.address});118119 await helper.scheduler.cancelScheduled(alice, scheduledId);120121 await waitNewBlocks(waitForBlocks + 1);122123 expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});124 });125126 itSub.ifWithPallets('Can cancel a periodic operation (transfer of funds)', [Pallets.Scheduler], async ({helper}) => {127 const waitForBlocks = 1;128 const periodic = {129 period: 3,130 repetitions: 2,131 };132133 const scheduledId = await helper.arrange.makeScheduledId();134135 const amount = 1n * UNIQUE;136137 const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);138139 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})140 .balance.transferToSubstrate(alice, bob.address, amount);141142 await helper.wait.newBlocks(waitForBlocks + 1);143144 const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);145146 expect(bobsBalanceAfterFirst)147 .to.be.equal(148 bobsBalanceBefore + 1n * amount,149 '#1 Balance of the recipient should be increased by 1 * amount',150 );151152 await helper.scheduler.cancelScheduled(alice, scheduledId);153 await helper.wait.newBlocks(periodic.period);154155 const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);156 expect(bobsBalanceAfterSecond)157 .to.be.equal(158 bobsBalanceAfterFirst,159 '#2 Balance of the recipient should not be changed',160 );161 });162163 itSub.ifWithPallets('Scheduled tasks are transactional', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {164 const scheduledId = await helper.arrange.makeScheduledId();165 const waitForBlocks = 4;166167 const initTestVal = 42;168 const changedTestVal = 111;169170 await helper.executeExtrinsic(171 alice,172 'api.tx.testUtils.setTestValue',173 [initTestVal],174 true,175 );176177 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks)178 .executeExtrinsic(179 alice,180 'api.tx.testUtils.setTestValueAndRollback',181 [changedTestVal],182 true,183 );184185 await helper.wait.newBlocks(waitForBlocks + 1);186187 const testVal = (await helper.api!.query.testUtils.testValue()).toNumber();188 expect(testVal, 'The test value should NOT be commited')189 .to.be.equal(initTestVal);190 });191192 itSub.ifWithPallets('Scheduled tasks should take correct fees', [Pallets.Scheduler, Pallets.TestUtils], async function({helper}) {193 const scheduledId = await helper.arrange.makeScheduledId();194 const waitForBlocks = 8;195 const periodic = {196 period: 2,197 repetitions: 2,198 };199200 const dummyTx = helper.constructApiCall('api.tx.testUtils.justTakeFee', []);201 const scheduledLen = dummyTx.callIndex.length;202203 const expectedScheduledFee = (await helper.getPaymentInfo(alice, dummyTx, scheduledLen))204 .partialFee.toBigInt();205206 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})207 .executeExtrinsic(alice, 'api.tx.testUtils.justTakeFee', [], true);208209 await helper.wait.newBlocks(1);210211 const aliceInitBalance = await helper.balance.getSubstrate(alice.address);212 let diff;213214 await helper.wait.newBlocks(waitForBlocks);215216 const aliceBalanceAfterFirst = await helper.balance.getSubstrate(alice.address);217 expect(218 aliceBalanceAfterFirst < aliceInitBalance,219 '[after execution #1] Scheduled task should take a fee',220 ).to.be.true;221222 diff = aliceInitBalance - aliceBalanceAfterFirst;223 expect(diff).to.be.equal(224 expectedScheduledFee,225 'Scheduled task should take the right amount of fees',226 );227228 await helper.wait.newBlocks(periodic.period);229230 const aliceBalanceAfterSecond = await helper.balance.getSubstrate(alice.address);231 expect(232 aliceBalanceAfterSecond < aliceBalanceAfterFirst,233 '[after execution #2] Scheduled task should take a fee',234 ).to.be.true;235236 diff = aliceBalanceAfterFirst - aliceBalanceAfterSecond;237 expect(diff).to.be.equal(238 expectedScheduledFee,239 'Scheduled task should take the right amount of fees',240 );241 });242243 244 245 itSub.ifWithPallets('Can cancel the periodic sheduled tx when the tx is running', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {246 const currentBlockNumber = await helper.chain.getLatestBlockNumber();247 const blocksBeforeExecution = 10;248 const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;249250 const [251 scheduledId,252 scheduledCancelId,253 ] = await helper.arrange.makeScheduledIds(2);254255 const periodic = {256 period: 5,257 repetitions: 5,258 };259260 const initTestVal = 0;261 const incTestVal = initTestVal + 1;262 const finalTestVal = initTestVal + 2;263264 await helper.executeExtrinsic(265 alice,266 'api.tx.testUtils.setTestValue',267 [initTestVal],268 true,269 );270271 await helper.scheduler.scheduleAt(scheduledId, firstExecutionBlockNumber, {periodic})272 .executeExtrinsic(273 alice,274 'api.tx.testUtils.incTestValue',275 [],276 true,277 );278279 280 281 await helper.scheduler.scheduleAt(282 scheduledCancelId,283 firstExecutionBlockNumber + periodic.period,284 ).scheduler.cancelScheduled(alice, scheduledId);285286 await helper.wait.newBlocks(blocksBeforeExecution);287288 289 expect((await helper.api!.query.testUtils.testValue()).toNumber())290 .to.be.equal(incTestVal);291292 await helper.wait.newBlocks(periodic.period);293294 295 expect((await helper.api!.query.testUtils.testValue()).toNumber())296 .to.be.equal(finalTestVal);297298 for (let i = 1; i < periodic.repetitions; i++) {299 await waitNewBlocks(periodic.period);300 expect((await helper.api!.query.testUtils.testValue()).toNumber())301 .to.be.equal(finalTestVal);302 }303 });304305 itSub.ifWithPallets('A scheduled operation can cancel itself', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {306 const scheduledId = await helper.arrange.makeScheduledId();307 const waitForBlocks = 8;308 const periodic = {309 period: 2,310 repetitions: 5,311 };312313 const initTestVal = 0;314 const maxTestVal = 2;315316 await helper.executeExtrinsic(317 alice,318 'api.tx.testUtils.setTestValue',319 [initTestVal],320 true,321 );322323 await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})324 .executeExtrinsic(325 alice,326 'api.tx.testUtils.selfCancelingInc',327 [scheduledId, maxTestVal],328 true,329 );330331 await helper.wait.newBlocks(waitForBlocks + 1);332333 334 expect((await helper.api!.query.testUtils.testValue()).toNumber())335 .to.be.equal(initTestVal + 1);336337 await helper.wait.newBlocks(periodic.period);338339 340 expect((await helper.api!.query.testUtils.testValue()).toNumber())341 .to.be.equal(initTestVal + 2);342343 await helper.wait.newBlocks(periodic.period);344345 346 expect((await helper.api!.query.testUtils.testValue()).toNumber())347 .to.be.equal(initTestVal + 2);348 });349350 itSub.ifWithPallets('Root can cancel any scheduled operation', [Pallets.Scheduler], async ({helper}) => {351 const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});352 const token = await collection.mintToken(bob);353354 const scheduledId = await helper.arrange.makeScheduledId();355 const waitForBlocks = 4;356357 await token.scheduleAfter(scheduledId, waitForBlocks)358 .transfer(bob, {Substrate: alice.address});359360 await helper.getSudo().scheduler.cancelScheduled(alice, scheduledId);361362 await helper.wait.newBlocks(waitForBlocks + 1);363364 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});365 });366367 itSub.ifWithPallets('Root can set prioritized scheduled operation', [Pallets.Scheduler], async ({helper}) => {368 const scheduledId = await helper.arrange.makeScheduledId();369 const waitForBlocks = 4;370371 const amount = 42n * UNIQUE;372373 const balanceBefore = await helper.balance.getSubstrate(charlie.address);374375 await helper.getSudo()376 .scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42})377 .balance.forceTransferToSubstrate(alice, bob.address, charlie.address, amount);378379 await helper.wait.newBlocks(waitForBlocks + 1);380381 const balanceAfter = await helper.balance.getSubstrate(charlie.address);382383 expect(balanceAfter > balanceBefore).to.be.true;384385 const diff = balanceAfter - balanceBefore;386 expect(diff).to.be.equal(amount);387 });388389 itSub.ifWithPallets("Root can change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {390 const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});391 const token = await collection.mintToken(bob);392393 const scheduledId = await helper.arrange.makeScheduledId();394 const waitForBlocks = 4;395396 await token.scheduleAfter(scheduledId, waitForBlocks)397 .transfer(bob, {Substrate: alice.address});398399 const priority = 112;400 await helper.getSudo().scheduler.changePriority(alice, scheduledId, priority);401402 const priorityChanged = await helper.wait.event(403 waitForBlocks,404 'scheduler',405 'PriorityChanged',406 );407408 expect(priorityChanged !== null).to.be.true;409 expect(priorityChanged!.event.data[2].toString()).to.be.equal(priority.toString());410 });411412 itSub.ifWithPallets('Prioritized operations executes in valid order', [Pallets.Scheduler], async ({helper}) => {413 const [414 scheduledFirstId,415 scheduledSecondId,416 ] = await helper.arrange.makeScheduledIds(2);417418 const currentBlockNumber = await helper.chain.getLatestBlockNumber();419 const blocksBeforeExecution = 4;420 const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;421422 const prioHigh = 0;423 const prioLow = 255;424425 const periodic = {426 period: 8,427 repetitions: 2,428 };429430 const amount = 1n * UNIQUE;431432 433 await helper.getSudo().scheduler.scheduleAt(scheduledFirstId, firstExecutionBlockNumber, {priority: prioLow, periodic})434 .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);435436 await helper.getSudo().scheduler.scheduleAt(scheduledSecondId, firstExecutionBlockNumber, {priority: prioHigh, periodic})437 .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);438439 const capture = await helper.arrange.captureEvents('scheduler', 'Dispatched');440441 await helper.wait.newBlocks(blocksBeforeExecution);442443 444 await helper.getSudo().scheduler.changePriority(alice, scheduledFirstId, prioHigh);445 await helper.getSudo().scheduler.changePriority(alice, scheduledSecondId, prioLow);446447 await helper.wait.newBlocks(periodic.period);448449 const dispatchEvents = capture.extractCapturedEvents();450 expect(dispatchEvents.length).to.be.equal(4);451452 const dispatchedIds = dispatchEvents.map(r => r.event.data[1].toString());453454 const firstExecuctionIds = [dispatchedIds[0], dispatchedIds[1]];455 const secondExecuctionIds = [dispatchedIds[2], dispatchedIds[3]];456457 expect(firstExecuctionIds[0]).to.be.equal(scheduledSecondId);458 expect(firstExecuctionIds[1]).to.be.equal(scheduledFirstId);459460 expect(secondExecuctionIds[0]).to.be.equal(scheduledFirstId);461 expect(secondExecuctionIds[1]).to.be.equal(scheduledSecondId);462 });463});464465describe('Negative Test: Scheduling', () => {466 let alice: IKeyringPair;467 let bob: IKeyringPair;468469 before(async () => {470 await usingPlaygrounds(async (_, privateKeyWrapper) => {471 alice = privateKeyWrapper('//Alice');472 bob = privateKeyWrapper('//Bob');473 });474 });475476 itSub.ifWithPallets("Can't overwrite a scheduled ID", [Pallets.Scheduler], async ({helper}) => {477 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});478 const token = await collection.mintToken(alice);479480 const scheduledId = await helper.arrange.makeScheduledId();481 const waitForBlocks = 4;482483 await token.scheduleAfter(scheduledId, waitForBlocks)484 .transfer(alice, {Substrate: bob.address});485486 const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks);487 await expect(scheduled.balance.transferToSubstrate(alice, bob.address, 1n * UNIQUE))488 .to.be.rejectedWith(/scheduler\.FailedToSchedule/);489490 const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);491492 await helper.wait.newBlocks(waitForBlocks + 1);493494 const bobsBalanceAfter = await helper.balance.getSubstrate(bob.address);495496 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});497 expect(bobsBalanceBefore).to.be.equal(bobsBalanceAfter);498 });499500 itSub.ifWithPallets("Can't cancel an operation which is not scheduled", [Pallets.Scheduler], async ({helper}) => {501 const scheduledId = await helper.arrange.makeScheduledId();502 await expect(helper.scheduler.cancelScheduled(alice, scheduledId))503 .to.be.rejectedWith(/scheduler\.NotFound/);504 });505506 itSub.ifWithPallets("Can't cancel a non-owned scheduled operation", [Pallets.Scheduler], async ({helper}) => {507 const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});508 const token = await collection.mintToken(alice);509510 const scheduledId = await helper.arrange.makeScheduledId();511 const waitForBlocks = 8;512513 await token.scheduleAfter(scheduledId, waitForBlocks)514 .transfer(alice, {Substrate: bob.address});515516 await expect(helper.scheduler.cancelScheduled(bob, scheduledId))517 .to.be.rejectedWith(/badOrigin/);518519 await helper.wait.newBlocks(waitForBlocks + 1);520521 expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});522 });523524 itSub.ifWithPallets("Regular user can't set prioritized scheduled operation", [Pallets.Scheduler], async ({helper}) => {525 const scheduledId = await helper.arrange.makeScheduledId();526 const waitForBlocks = 4;527528 const amount = 42n * UNIQUE;529530 const balanceBefore = await helper.balance.getSubstrate(bob.address);531532 const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42});533 534 await expect(scheduled.balance.transferToSubstrate(alice, bob.address, amount))535 .to.be.rejectedWith(/badOrigin/);536537 await helper.wait.newBlocks(waitForBlocks + 1);538539 const balanceAfter = await helper.balance.getSubstrate(bob.address);540541 expect(balanceAfter).to.be.equal(balanceBefore);542 });543544 itSub.ifWithPallets("Regular user can't change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {545 const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});546 const token = await collection.mintToken(bob);547548 const scheduledId = await helper.arrange.makeScheduledId();549 const waitForBlocks = 4;550551 await token.scheduleAfter(scheduledId, waitForBlocks)552 .transfer(bob, {Substrate: alice.address});553554 const priority = 112;555 await expect(helper.scheduler.changePriority(alice, scheduledId, priority))556 .to.be.rejectedWith(/badOrigin/);557558 const priorityChanged = await helper.wait.event(559 waitForBlocks,560 'scheduler',561 'PriorityChanged',562 );563564 expect(priorityChanged === null).to.be.true;565 });566});567568569describe.skip('Sponsoring scheduling', () => {570 let alice: IKeyringPair;571 let bob: IKeyringPair;572573 before(async() => {574 await usingApi(async (_, privateKeyWrapper) => {575 alice = privateKeyWrapper('//Alice');576 bob = privateKeyWrapper('//Bob');577 });578 });579580 it('Can sponsor scheduling a transaction', async () => {581 582 583 584585 586 587 588589 590 591 592 593 594 595 596 597 598 599 });600601 it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {602 603 604 605606 607608 609 610 611612 613 614 615616 617 618 619620 621 622 623624 625 626 627 628 629 630 631 632633 634 635636 637 638 });639640 it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {641 642643 644 645 646 647648 649 650651 652 653654 655 656657 658 659 660 661662 663 664665 666 667 });668669 it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {670 671 672 673674 675 676677 678 679680 681682 683 684 685686 687 688 689 690691 692693 694 695 });696});