git.delta.rocks / unique-network / refs/commits / bd337d6ea58c

difftreelog

feat make scheduler tests to use playgrounds

Daniel Shiposha2022-09-13parent: #3329598.patch.diff
in: master

1 file changed

modifiedtests/src/.outdated/scheduler.test.tsdiffbeforeafterboth
before · tests/src/.outdated/scheduler.test.ts
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 chai, {expect} from 'chai';18import chaiAsPromised from 'chai-as-promised';19import {20  default as usingApi,21  executeTransaction,22  submitTransactionAsync,23  submitTransactionExpectFailAsync,24} from '../substrate/substrate-api';25import {26  createItemExpectSuccess,27  createCollectionExpectSuccess,28  scheduleTransferExpectSuccess,29  scheduleTransferAndWaitExpectSuccess,30  setCollectionSponsorExpectSuccess,31  confirmSponsorshipExpectSuccess,32  findUnusedAddress,33  UNIQUE,34  enablePublicMintingExpectSuccess,35  addToAllowListExpectSuccess,36  waitNewBlocks,37  makeScheduledId,38  normalizeAccountId,39  getTokenOwner,40  getGenericResult,41  scheduleTransferFundsExpectSuccess,42  getFreeBalance,43  confirmSponsorshipByKeyExpectSuccess,44  scheduleExpectFailure,45  scheduleAfter,46  cancelScheduled,47  requirePallets,48  Pallets,49  getBlockNumber,50  scheduleAt,51} from '../deprecated-helpers/helpers';52import {IKeyringPair, SignatureOptions} from '@polkadot/types/types';53import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';54import {ApiPromise} from '@polkadot/api';55import {objectSpread} from '@polkadot/util';5657chai.use(chaiAsPromised);5859// Check that there are no failing Dispatched events in the block60function checkForFailedSchedulerEvents(api: ApiPromise, events: any[]) {61  return new Promise((res, rej) => {62    let schedulerEventPresent = false;63    64    for (const {event} of events) {65      if (api.events.scheduler.Dispatched.is(event)) {66        schedulerEventPresent = true;67        const result = event.data.result;68        if (result.isErr) {69          const decoded = api.registry.findMetaError(result.asErr.asModule);70          const {method, section} = decoded;71          rej(new Error(`${section}.${method}`));72        }73      }74    }75    res(schedulerEventPresent);76  });77}7879describe('Scheduling token and balance transfers', () => {80  let alice: IKeyringPair;81  let bob: IKeyringPair;8283  before(async function() {84    await requirePallets(this, [Pallets.Scheduler]);8586    await usingApi(async (_, privateKeyWrapper) => {87      alice = privateKeyWrapper('//Alice');88      bob = privateKeyWrapper('//Bob');89    });90  });919293  it('Can delay a transfer of an owned token', async () => {94    await usingApi(async api => {95      const collectionId = await createCollectionExpectSuccess();96      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');97      const scheduledId = await makeScheduledId();9899      await scheduleTransferAndWaitExpectSuccess(api, collectionId, tokenId, alice, bob, 1, 4, scheduledId);100    });101  });102103  it('Can transfer funds periodically', async () => {104    await usingApi(async api => {105      const scheduledId = await makeScheduledId();106      const waitForBlocks = 1;107      const period = 2;108      const repetitions = 2;109110      const amount = 1n * UNIQUE;111112      await scheduleTransferFundsExpectSuccess(api, amount, alice, bob, waitForBlocks, scheduledId, period, repetitions);113      const bobsBalanceBefore = await getFreeBalance(bob);114115      await waitNewBlocks(waitForBlocks + 1);116      const bobsBalanceAfterFirst = await getFreeBalance(bob);117      expect(bobsBalanceAfterFirst)118        .to.be.equal(119          bobsBalanceBefore + 1n * amount,120          '#1 Balance of the recipient should be increased by 1 * amount',121        );122123      await waitNewBlocks(period);124      const bobsBalanceAfterSecond = await getFreeBalance(bob);125      expect(bobsBalanceAfterSecond)126        .to.be.equal(127          bobsBalanceBefore + 2n * amount,128          '#2 Balance of the recipient should be increased by 2 * amount',129        );130    });131  });132133  it('Can cancel a scheduled operation which has not yet taken effect', async () => {134    await usingApi(async api => {135      const collectionId = await createCollectionExpectSuccess();136      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');137      const scheduledId = await makeScheduledId();138      const waitForBlocks = 4;139140      const amount = 1;141142      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, amount, waitForBlocks, scheduledId);143      await expect(cancelScheduled(api, alice, scheduledId)).to.not.be.rejected;144145      await waitNewBlocks(waitForBlocks);146147      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));148    });149  });150151  it('Can cancel a periodic operation (transfer of funds)', async () => {152    await usingApi(async api => {153      const waitForBlocks = 1;154      const period = 3;155      const repetitions = 2;156157      const scheduledId = await makeScheduledId();158      const amount = 1n * UNIQUE;159160      const bobsBalanceBefore = await getFreeBalance(bob);161      await scheduleTransferFundsExpectSuccess(api, amount, alice, bob, waitForBlocks, scheduledId, period, repetitions);162163      await waitNewBlocks(waitForBlocks + 1);164      const bobsBalanceAfterFirst = await getFreeBalance(bob);165      expect(bobsBalanceAfterFirst)166        .to.be.equal(167          bobsBalanceBefore + 1n * amount,168          '#1 Balance of the recipient should be increased by 1 * amount',169        );170171      await expect(cancelScheduled(api, alice, scheduledId)).to.not.be.rejected;172173      await waitNewBlocks(period);174      const bobsBalanceAfterSecond = await getFreeBalance(bob);175      expect(bobsBalanceAfterSecond)176        .to.be.equal(177          bobsBalanceAfterFirst,178          '#2 Balance of the recipient should not be changed',179        );180    });181  });182183  it('Scheduled tasks are transactional', async function() {184    await requirePallets(this, [Pallets.TestUtils]);185186    await usingApi(async api => {187      const scheduledId = await makeScheduledId();188      const waitForBlocks = 4;189190      const initTestVal = 42;191      const changedTestVal = 111;192193      const initTx = api.tx.testUtils.setTestValue(initTestVal);194      await submitTransactionAsync(alice, initTx);195196      const changeErrTx = api.tx.testUtils.setTestValueAndRollback(changedTestVal);197198      await expect(scheduleAfter(199        api,200        changeErrTx,201        alice,202        waitForBlocks,203        scheduledId,204      )).to.not.be.rejected;205206      await waitNewBlocks(waitForBlocks + 1);207208      const testVal = (await api.query.testUtils.testValue()).toNumber();209      expect(testVal, 'The test value should NOT be commited')210        .not.to.be.equal(changedTestVal)211        .and.to.be.equal(initTx);212    });213  });214215  it('Scheduled tasks should take correct fees', async function() {216    await requirePallets(this, [Pallets.TestUtils]);217218    await usingApi(async api => {219      const scheduledId = await makeScheduledId();220      const waitForBlocks = 8;221      const period = 2;222      const repetitions = 2;223224      const dummyTx = api.tx.testUtils.justTakeFee();225  226      const signingInfo = await api.derive.tx.signingInfo(alice.address);227228      // We need to sign the tx because229      // unsigned transactions does not have an inclusion fee230      dummyTx.sign(alice, {231        blockHash: api.genesisHash,232        genesisHash: api.genesisHash,233        runtimeVersion: api.runtimeVersion,234        nonce: signingInfo.nonce,235      });236237      const scheduledLen = dummyTx.callIndex.length;238239      const queryInfo = await api.call.transactionPaymentApi.queryInfo(240        dummyTx.toHex(),241        scheduledLen,242      );243244      const expectedScheduledFee = (await queryInfo as RuntimeDispatchInfo)245        .partialFee.toBigInt();246247      await expect(scheduleAfter(248        api,249        dummyTx,250        alice,251        waitForBlocks,252        scheduledId,253        period,254        repetitions,255      )).to.not.be.rejected;256257      await waitNewBlocks(1);258259      const aliceInitBalance = await getFreeBalance(alice);260      let diff;261262      await waitNewBlocks(waitForBlocks);263264      const aliceBalanceAfterFirst = await getFreeBalance(alice);265      expect(266        aliceBalanceAfterFirst < aliceInitBalance,267        '[after execution #1] Scheduled task should take a fee',268      ).to.be.true;269270      diff = aliceInitBalance - aliceBalanceAfterFirst;271      expect(diff).to.be.equal(272        expectedScheduledFee,273        'Scheduled task should take the right amount of fees',274      );275276      await waitNewBlocks(period);277278      const aliceBalanceAfterSecond = await getFreeBalance(alice);279      expect(280        aliceBalanceAfterSecond < aliceBalanceAfterFirst,281        '[after execution #2] Scheduled task should take a fee',282      ).to.be.true;283284      diff = aliceBalanceAfterFirst - aliceBalanceAfterSecond;285      expect(diff).to.be.equal(286        expectedScheduledFee,287        'Scheduled task should take the right amount of fees',288      );289    });290  });291292  // Check if we can cancel a scheduled periodic operation293  // in the same block in which it is running294  it('Can cancel the periodic sheduled tx when the tx is running', async () => {295    await usingApi(async api => {296      const currentBlockNumber = await getBlockNumber(api);297      const blocksBeforeExecution = 10;298      const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;299      300      const scheduledId = await makeScheduledId();301      const scheduledCancelId = await makeScheduledId();302303      const period = 5;304      const repetitions = 5;305306      const initTestVal = 0;307      const incTestVal = initTestVal + 1;308      const finalTestVal = initTestVal + 2;309      await executeTransaction(310        api,311        alice,312        api.tx.testUtils.setTestValue(initTestVal),313      );314315      const incTx = api.tx.testUtils.incTestValue();316      const cancelTx = api.tx.scheduler.cancelNamed(scheduledId);317318      await expect(scheduleAt(319        api, 320        incTx,321        alice, 322        firstExecutionBlockNumber, 323        scheduledId, 324        period, 325        repetitions,326      )).to.not.be.rejected;327328      // Cancel the inc tx after 2 executions329      // *in the same block* in which the second execution is scheduled330      await expect(scheduleAt(331        api,332        cancelTx,333        alice,334        firstExecutionBlockNumber + period,335        scheduledCancelId,336      )).to.not.be.rejected;337338      await waitNewBlocks(blocksBeforeExecution);339340      // execution #0341      expect((await api.query.testUtils.testValue()).toNumber())342        .to.be.equal(incTestVal);343344      await waitNewBlocks(period);345346      // execution #1347      expect((await api.query.testUtils.testValue()).toNumber())348        .to.be.equal(finalTestVal);349350      for (let i = 1; i < repetitions; i++) {351        await waitNewBlocks(period);352        expect((await api.query.testUtils.testValue()).toNumber())353          .to.be.equal(finalTestVal);354      }355    });356  });357358  it('A scheduled operation can cancel itself', async () => {359    await usingApi(async api => {360      const scheduledId = await makeScheduledId();361      const waitForBlocks = 8;362      const period = 2;363      const repetitions = 5;364365      const initTestVal = 0;366      const maxTestVal = 2;367368      await executeTransaction(369        api,370        alice,371        api.tx.testUtils.setTestValue(initTestVal),372      );373374      const selfCancelingTx = api.tx.testUtils.selfCancelingInc(scheduledId, maxTestVal);375376      await expect(scheduleAfter(377        api,378        selfCancelingTx,379        alice,380        waitForBlocks,381        scheduledId,382        period,383        repetitions,384      )).to.not.be.rejected;385386      await waitNewBlocks(waitForBlocks + 1);387388      // execution #0389      expect((await api.query.testUtils.testValue()).toNumber())390        .to.be.equal(initTestVal + 1);391392      await waitNewBlocks(period);393394      // execution #1395      expect((await api.query.testUtils.testValue()).toNumber())396        .to.be.equal(initTestVal + 2);397398      await waitNewBlocks(period);399400      // <canceled>401      expect((await api.query.testUtils.testValue()).toNumber())402        .to.be.equal(initTestVal + 2);403    });404  });405});406407describe('Negative Test: Scheduling', () => {408  let alice: IKeyringPair;409  let bob: IKeyringPair;410411  before(async function() {412    await requirePallets(this, [Pallets.Scheduler]);413414    await usingApi(async (_, privateKeyWrapper) => {415      alice = privateKeyWrapper('//Alice');416      bob = privateKeyWrapper('//Bob');417    });418  });419420  it("Can't overwrite a scheduled ID", async () => {421    await usingApi(async api => {422      const collectionId = await createCollectionExpectSuccess();423      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');424      const scheduledId = await makeScheduledId();425      const waitForBlocks = 4;426      const amount = 1;427428      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, amount, waitForBlocks, scheduledId);429      await expect(scheduleAfter(430        api, 431        api.tx.balances.transfer(alice.address, 1n * UNIQUE), 432        bob, 433        /* period = */ 2, 434        scheduledId,435      )).to.be.rejectedWith(/scheduler\.FailedToSchedule/);436437      const bobsBalanceBefore = await getFreeBalance(bob);438439      await waitNewBlocks(waitForBlocks + 1);440441      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(bob.address));442      expect(bobsBalanceBefore).to.be.equal(await getFreeBalance(bob));443    });444  });445446  it("Can't cancel an operation which is not scheduled", async () => {447    await usingApi(async api => {448      const scheduledId = await makeScheduledId();449      await expect(cancelScheduled(api, alice, scheduledId)).to.be.rejectedWith(/scheduler\.NotFound/);450    });451  });452453  it("Can't cancel a non-owned scheduled operation", async () => {454    await usingApi(async api => {455      const collectionId = await createCollectionExpectSuccess();456      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');457      const scheduledId = await makeScheduledId();458      const waitForBlocks = 8;459460      const amount = 1;461462      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, amount, waitForBlocks, scheduledId);463      await expect(cancelScheduled(api, bob, scheduledId)).to.be.rejectedWith(/BadOrigin/);464465      await waitNewBlocks(waitForBlocks + 1);466467      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(bob.address));468    });469  });470});471472// Implementation of the functionality tested here was postponed/shelved473describe.skip('Sponsoring scheduling', () => {474  let alice: IKeyringPair;475  let bob: IKeyringPair;476477  before(async() => {478    await usingApi(async (_, privateKeyWrapper) => {479      alice = privateKeyWrapper('//Alice');480      bob = privateKeyWrapper('//Bob');481    });482  });483484  it('Can sponsor scheduling a transaction', async () => {485    const collectionId = await createCollectionExpectSuccess();486    await setCollectionSponsorExpectSuccess(collectionId, bob.address);487    await confirmSponsorshipExpectSuccess(collectionId, '//Bob');488489    await usingApi(async api => {490      const scheduledId = await makeScheduledId();491      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);492493      const bobBalanceBefore = await getFreeBalance(bob);494      const waitForBlocks = 4;495      // no need to wait to check, fees must be deducted on scheduling, immediately496      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, scheduledId);497      const bobBalanceAfter = await getFreeBalance(bob);498      // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;499      expect(bobBalanceAfter < bobBalanceBefore).to.be.true;500      // wait for sequentiality matters501      await waitNewBlocks(waitForBlocks - 1);502    });503  });504505  it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {506    await usingApi(async (api, privateKeyWrapper) => {507      // Find an empty, unused account508      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);509510      const collectionId = await createCollectionExpectSuccess();511512      // Add zeroBalance address to allow list513      await enablePublicMintingExpectSuccess(alice, collectionId);514      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);515516      // Grace zeroBalance with money, enough to cover future transactions517      const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);518      await submitTransactionAsync(alice, balanceTx);519520      // Mint a fresh NFT521      const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');522      const scheduledId = await makeScheduledId();523524      // Schedule transfer of the NFT a few blocks ahead525      const waitForBlocks = 5;526      await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, scheduledId);527528      // Get rid of the account's funds before the scheduled transaction takes place529      const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);530      const events = await submitTransactionAsync(zeroBalance, balanceTx2);531      expect(getGenericResult(events).success).to.be.true;532      /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?533      const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);534      const events = await submitTransactionAsync(alice, sudoTx);535      expect(getGenericResult(events).success).to.be.true;*/536537      // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions538      await waitNewBlocks(waitForBlocks - 3);539540      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));541    });542  });543544  it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {545    const collectionId = await createCollectionExpectSuccess();546547    await usingApi(async (api, privateKeyWrapper) => {548      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);549      const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);550      await submitTransactionAsync(alice, balanceTx);551552      await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);553      await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);554555      const scheduledId = await makeScheduledId();556      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);557558      const waitForBlocks = 5;559      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, scheduledId);560561      const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);562      const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);563      const events = await submitTransactionAsync(alice, sudoTx);564      expect(getGenericResult(events).success).to.be.true;565566      // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions567      await waitNewBlocks(waitForBlocks - 3);568569      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));570    });571  });572573  it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {574    const collectionId = await createCollectionExpectSuccess();575    await setCollectionSponsorExpectSuccess(collectionId, bob.address);576    await confirmSponsorshipExpectSuccess(collectionId, '//Bob');577578    await usingApi(async (api, privateKeyWrapper) => {579      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);580581      await enablePublicMintingExpectSuccess(alice, collectionId);582      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);583584      const bobBalanceBefore = await getFreeBalance(bob);585586      const createData = {nft: {const_data: [], variable_data: []}};587      const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);588      const scheduledId = await makeScheduledId();589590      /*const badTransaction = async function () {591        await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);592      };593      await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/594595      await expect(scheduleAfter(api, creationTx, zeroBalance, 3, scheduledId, 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);596597      expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);598    });599  });600});
after · tests/src/.outdated/scheduler.test.ts
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;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.mintDefaultCollection(alice);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.mintDefaultCollection(alice);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.mintDefaultCollection(alice);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.mintDefaultCollection(alice);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});