difftreelog
fix(scheduler) minimize wait time in test, comment sponsorship, remove unused imports
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 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 // Check if we can cancel a scheduled periodic operation244 // in the same block in which it is running245 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 // Cancel the inc tx after 2 executions280 // *in the same block* in which the second execution is scheduled281 await helper.scheduler.scheduleAt(282 scheduledCancelId,283 firstExecutionBlockNumber + periodic.period,284 ).scheduler.cancelScheduled(alice, scheduledId);285286 await helper.wait.newBlocks(blocksBeforeExecution);287288 // execution #0289 expect((await helper.api!.query.testUtils.testValue()).toNumber())290 .to.be.equal(incTestVal);291292 await helper.wait.newBlocks(periodic.period);293294 // execution #1295 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 // execution #0334 expect((await helper.api!.query.testUtils.testValue()).toNumber())335 .to.be.equal(initTestVal + 1);336337 await helper.wait.newBlocks(periodic.period);338339 // execution #1340 expect((await helper.api!.query.testUtils.testValue()).toNumber())341 .to.be.equal(initTestVal + 2);342343 await helper.wait.newBlocks(periodic.period);344345 // <canceled>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 // Scheduler a task with a lower priority first, then with a higher priority433 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 // Flip priorities444 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});567568// Implementation of the functionality tested here was postponed/shelved569describe.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 // const collectionId = await createCollectionExpectSuccess();582 // await setCollectionSponsorExpectSuccess(collectionId, bob.address);583 // await confirmSponsorshipExpectSuccess(collectionId, '//Bob');584585 // await usingApi(async api => {586 // const scheduledId = await makeScheduledId();587 // const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);588589 // const bobBalanceBefore = await getFreeBalance(bob);590 // const waitForBlocks = 4;591 // // no need to wait to check, fees must be deducted on scheduling, immediately592 // await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, scheduledId);593 // const bobBalanceAfter = await getFreeBalance(bob);594 // // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;595 // expect(bobBalanceAfter < bobBalanceBefore).to.be.true;596 // // wait for sequentiality matters597 // await waitNewBlocks(waitForBlocks - 1);598 // });599 });600601 it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {602 // await usingApi(async (api, privateKeyWrapper) => {603 // // Find an empty, unused account604 // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);605606 // const collectionId = await createCollectionExpectSuccess();607608 // // Add zeroBalance address to allow list609 // await enablePublicMintingExpectSuccess(alice, collectionId);610 // await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);611612 // // Grace zeroBalance with money, enough to cover future transactions613 // const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);614 // await submitTransactionAsync(alice, balanceTx);615616 // // Mint a fresh NFT617 // const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');618 // const scheduledId = await makeScheduledId();619620 // // Schedule transfer of the NFT a few blocks ahead621 // const waitForBlocks = 5;622 // await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, scheduledId);623624 // // Get rid of the account's funds before the scheduled transaction takes place625 // const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);626 // const events = await submitTransactionAsync(zeroBalance, balanceTx2);627 // expect(getGenericResult(events).success).to.be.true;628 // /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?629 // const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);630 // const events = await submitTransactionAsync(alice, sudoTx);631 // expect(getGenericResult(events).success).to.be.true;*/632633 // // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions634 // await waitNewBlocks(waitForBlocks - 3);635636 // expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));637 // });638 });639640 it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {641 // const collectionId = await createCollectionExpectSuccess();642643 // await usingApi(async (api, privateKeyWrapper) => {644 // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);645 // const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);646 // await submitTransactionAsync(alice, balanceTx);647648 // await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);649 // await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);650651 // const scheduledId = await makeScheduledId();652 // const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);653654 // const waitForBlocks = 5;655 // await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, scheduledId);656657 // const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);658 // const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);659 // const events = await submitTransactionAsync(alice, sudoTx);660 // expect(getGenericResult(events).success).to.be.true;661662 // // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions663 // await waitNewBlocks(waitForBlocks - 3);664665 // expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));666 // });667 });668669 it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {670 // const collectionId = await createCollectionExpectSuccess();671 // await setCollectionSponsorExpectSuccess(collectionId, bob.address);672 // await confirmSponsorshipExpectSuccess(collectionId, '//Bob');673674 // await usingApi(async (api, privateKeyWrapper) => {675 // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);676677 // await enablePublicMintingExpectSuccess(alice, collectionId);678 // await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);679680 // const bobBalanceBefore = await getFreeBalance(bob);681682 // const createData = {nft: {const_data: [], variable_data: []}};683 // const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);684 // const scheduledId = await makeScheduledId();685686 // /*const badTransaction = async function () {687 // await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);688 // };689 // await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/690691 // await expect(scheduleAfter(api, creationTx, zeroBalance, 3, scheduledId, 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);692693 // expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);694 // });695 });696});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 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 // Check if we can cancel a scheduled periodic operation229 // in the same block in which it is running230 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 // Cancel the inc tx after 2 executions265 // *in the same block* in which the second execution is scheduled266 await helper.scheduler.scheduleAt(267 scheduledCancelId,268 firstExecutionBlockNumber + periodic.period,269 ).scheduler.cancelScheduled(alice, scheduledId);270271 await helper.wait.newBlocks(blocksBeforeExecution);272273 // execution #0274 expect((await helper.api!.query.testUtils.testValue()).toNumber())275 .to.be.equal(incTestVal);276277 await helper.wait.newBlocks(periodic.period);278279 // execution #1280 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 // execution #0319 expect((await helper.api!.query.testUtils.testValue()).toNumber())320 .to.be.equal(initTestVal + 1);321322 await helper.wait.newBlocks(periodic.period);323324 // execution #1325 expect((await helper.api!.query.testUtils.testValue()).toNumber())326 .to.be.equal(initTestVal + 2);327328 await helper.wait.newBlocks(periodic.period);329330 // <canceled>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 // Scheduler a task with a lower priority first, then with a higher priority418 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 // Flip priorities429 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});552553// Implementation of the functionality tested here was postponed/shelved554describe.skip('Sponsoring scheduling', () => {555 // let alice: IKeyringPair;556 // let bob: IKeyringPair;557558 // before(async() => {559 // await usingApi(async (_, privateKeyWrapper) => {560 // alice = privateKeyWrapper('//Alice');561 // bob = privateKeyWrapper('//Bob');562 // });563 // });564565 it('Can sponsor scheduling a transaction', async () => {566 // const collectionId = await createCollectionExpectSuccess();567 // await setCollectionSponsorExpectSuccess(collectionId, bob.address);568 // await confirmSponsorshipExpectSuccess(collectionId, '//Bob');569570 // await usingApi(async api => {571 // const scheduledId = await makeScheduledId();572 // const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);573574 // const bobBalanceBefore = await getFreeBalance(bob);575 // const waitForBlocks = 4;576 // // no need to wait to check, fees must be deducted on scheduling, immediately577 // await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, scheduledId);578 // const bobBalanceAfter = await getFreeBalance(bob);579 // // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;580 // expect(bobBalanceAfter < bobBalanceBefore).to.be.true;581 // // wait for sequentiality matters582 // await waitNewBlocks(waitForBlocks - 1);583 // });584 });585586 it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {587 // await usingApi(async (api, privateKeyWrapper) => {588 // // Find an empty, unused account589 // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);590591 // const collectionId = await createCollectionExpectSuccess();592593 // // Add zeroBalance address to allow list594 // await enablePublicMintingExpectSuccess(alice, collectionId);595 // await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);596597 // // Grace zeroBalance with money, enough to cover future transactions598 // const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);599 // await submitTransactionAsync(alice, balanceTx);600601 // // Mint a fresh NFT602 // const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');603 // const scheduledId = await makeScheduledId();604605 // // Schedule transfer of the NFT a few blocks ahead606 // const waitForBlocks = 5;607 // await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, scheduledId);608609 // // Get rid of the account's funds before the scheduled transaction takes place610 // const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);611 // const events = await submitTransactionAsync(zeroBalance, balanceTx2);612 // expect(getGenericResult(events).success).to.be.true;613 // /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?614 // const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);615 // const events = await submitTransactionAsync(alice, sudoTx);616 // expect(getGenericResult(events).success).to.be.true;*/617618 // // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions619 // await waitNewBlocks(waitForBlocks - 3);620621 // expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));622 // });623 });624625 it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {626 // const collectionId = await createCollectionExpectSuccess();627628 // await usingApi(async (api, privateKeyWrapper) => {629 // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);630 // const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);631 // await submitTransactionAsync(alice, balanceTx);632633 // await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);634 // await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);635636 // const scheduledId = await makeScheduledId();637 // const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);638639 // const waitForBlocks = 5;640 // await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, scheduledId);641642 // const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);643 // const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);644 // const events = await submitTransactionAsync(alice, sudoTx);645 // expect(getGenericResult(events).success).to.be.true;646647 // // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions648 // await waitNewBlocks(waitForBlocks - 3);649650 // expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));651 // });652 });653654 it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {655 // const collectionId = await createCollectionExpectSuccess();656 // await setCollectionSponsorExpectSuccess(collectionId, bob.address);657 // await confirmSponsorshipExpectSuccess(collectionId, '//Bob');658659 // await usingApi(async (api, privateKeyWrapper) => {660 // const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);661662 // await enablePublicMintingExpectSuccess(alice, collectionId);663 // await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);664665 // const bobBalanceBefore = await getFreeBalance(bob);666667 // const createData = {nft: {const_data: [], variable_data: []}};668 // const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);669 // const scheduledId = await makeScheduledId();670671 // /*const badTransaction = async function () {672 // await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);673 // };674 // await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/675676 // await expect(scheduleAfter(api, creationTx, zeroBalance, 3, scheduledId, 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);677678 // expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);679 // });680 });681});