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

difftreelog

refactor make scheduler test more explicit

Daniel Shiposha2022-08-17parent: #e5b072a.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  submitTransactionAsync,22} from '../substrate/substrate-api';23import {24  createItemExpectSuccess,25  createCollectionExpectSuccess,26  scheduleTransferExpectSuccess,27  scheduleTransferAndWaitExpectSuccess,28  setCollectionSponsorExpectSuccess,29  confirmSponsorshipExpectSuccess,30  findUnusedAddress,31  UNIQUE,32  enablePublicMintingExpectSuccess,33  addToAllowListExpectSuccess,34  waitNewBlocks,35  normalizeAccountId,36  getTokenOwner,37  getGenericResult,38  scheduleTransferFundsExpectSuccess,39  getFreeBalance,40  confirmSponsorshipByKeyExpectSuccess,41  scheduleExpectFailure,42  scheduleAfter,43  cancelScheduled,44} from '../deprecated-helpers/helpers';45import {IKeyringPair} from '@polkadot/types/types';46import {ApiPromise} from '@polkadot/api';4748chai.use(chaiAsPromised);4950const scheduledIdBase: string = '0x' + '0'.repeat(31);51let scheduledIdSlider = 0;5253// Loop scheduledId around 10. Unless there are concurrent tasks with long periods/repetitions, tests' tasks' ids shouldn't ovelap.54function makeScheduledId(): string {55  return scheduledIdBase + ((scheduledIdSlider++) % 10);56}5758// Check that there are no failing Dispatched events in the block59function checkForFailedSchedulerEvents(api: ApiPromise, events: any[]) {60  return new Promise((res, rej) => {61    let schedulerEventPresent = false;62    63    for (const {event} of events) {64      if (api.events.scheduler.Dispatched.is(event)) {65        schedulerEventPresent = true;66        const result = event.data.result;67        if (result.isErr) {68          const decoded = api.registry.findMetaError(result.asErr.asModule);69          const {method, section} = decoded;70          rej(new Error(`${section}.${method}`));71        }72      }73    }74    res(schedulerEventPresent);75  });76}7778describe('Scheduling token and balance transfers', () => {79  let alice: IKeyringPair;80  let bob: IKeyringPair;8182  before(async() => {83    await usingApi(async (_, privateKeyWrapper) => {84      alice = privateKeyWrapper('//Alice');85      bob = privateKeyWrapper('//Bob');86    });87  });888990  it('Can delay a transfer of an owned token', async () => {91    await usingApi(async api => {92      const collectionId = await createCollectionExpectSuccess();93      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');9495      await scheduleTransferAndWaitExpectSuccess(api, collectionId, tokenId, alice, bob, 1, 4, makeScheduledId());96    });97  });9899  it('Can transfer funds periodically', async () => {100    await usingApi(async api => {101      const waitForBlocks = 1;102      const period = 2;103      const repetitions = 2;104105      await scheduleTransferFundsExpectSuccess(api, 1n * UNIQUE, alice, bob, waitForBlocks, makeScheduledId(), period, repetitions);106      const bobsBalanceBefore = await getFreeBalance(bob);107108      await waitNewBlocks(waitForBlocks + 1);109      const bobsBalanceAfterFirst = await getFreeBalance(bob);110      expect(bobsBalanceAfterFirst > bobsBalanceBefore, '#1 Balance of the recipient did not increase').to.be.true;111112      await waitNewBlocks(period);113      const bobsBalanceAfterSecond = await getFreeBalance(bob);114      expect(bobsBalanceAfterSecond > bobsBalanceAfterFirst, '#2 Balance of the recipient did not increase').to.be.true;115    });116  });117118  it('Can cancel a scheduled operation which has not yet taken effect', async () => {119    await usingApi(async api => {120      const collectionId = await createCollectionExpectSuccess();121      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');122      const scheduledId = makeScheduledId();123      const waitForBlocks = 4;124125      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 1, waitForBlocks, scheduledId);126      await expect(cancelScheduled(api, alice, scheduledId)).to.not.be.rejected;127128      await waitNewBlocks(waitForBlocks);129130      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));131    });132  });133134  it('Can cancel a periodic operation (transfer of funds)', async () => {135    await usingApi(async api => {136      const waitForBlocks = 1;137      const period = 3;138      const repetitions = 2;139140      const scheduledId = makeScheduledId();141142      const bobsBalanceBefore = await getFreeBalance(bob);143      await scheduleTransferFundsExpectSuccess(api, 1n * UNIQUE, alice, bob, waitForBlocks, scheduledId, period, repetitions);144145      await waitNewBlocks(waitForBlocks + 1);146      const bobsBalanceAfterFirst = await getFreeBalance(bob);147      expect(bobsBalanceAfterFirst > bobsBalanceBefore, '#1 Balance of the recipient did not increase').to.be.true;148149      await expect(cancelScheduled(api, alice, scheduledId)).to.not.be.rejected;150151      await waitNewBlocks(period);152      const bobsBalanceAfterSecond = await getFreeBalance(bob);153      expect(bobsBalanceAfterSecond == bobsBalanceAfterFirst, '#2 Balance of the recipient changed').to.be.true;154    });155  });156157  it('Can schedule a scheduled operation of canceling the scheduled operation', async () => {158    await usingApi(async api => {159      const scheduledId = makeScheduledId();160161      const waitForBlocks = 2;162      const period = 3;163      const repetitions = 2;164165      await expect(scheduleAfter(166        api, 167        api.tx.scheduler.cancelNamed(scheduledId), 168        alice, 169        waitForBlocks, 170        scheduledId, 171        period, 172        repetitions,173      )).to.not.be.rejected;174175176      await waitNewBlocks(waitForBlocks);177178      // todo:scheduler debug line; doesn't work (and doesn't appear in events) when executed in the same block as the scheduled transaction179      //await expect(executeTransaction(api, alice, api.tx.scheduler.cancelNamed(scheduledId))).to.not.be.rejected;180181      let schedulerEvents = 0;182      for (let i = 0; i < period * repetitions; i++) {183        const events = await api.query.system.events();184        schedulerEvents += await expect(checkForFailedSchedulerEvents(api, events)).to.not.be.rejected;185        await waitNewBlocks(1);186      }187      expect(schedulerEvents).to.be.equal(repetitions);188    });189  });190191  after(async () => {192    // todo:scheduler to avoid the failed results of the previous test interfering with the next, delete after the problem is fixed193    await waitNewBlocks(6);194  });195});196197describe('Negative Test: Scheduling', () => {198  let alice: IKeyringPair;199  let bob: IKeyringPair;200201  before(async() => {202    await usingApi(async (_, privateKeyWrapper) => {203      alice = privateKeyWrapper('//Alice');204      bob = privateKeyWrapper('//Bob');205    });206  });207208  it('Can\'t overwrite a scheduled ID', async () => {209    await usingApi(async api => {210      const collectionId = await createCollectionExpectSuccess();211      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');212      const scheduledId = makeScheduledId();213214      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 1, 4, scheduledId);215      await expect(scheduleAfter(216        api, 217        api.tx.balances.transfer(alice.address, 1n * UNIQUE), 218        bob, 219        2, 220        scheduledId,221      )).to.be.rejectedWith(/scheduler\.FailedToSchedule/);222      const bobsBalance = await getFreeBalance(bob);223224      await waitNewBlocks(3);225226      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(bob.address));227      expect(bobsBalance).to.be.equal(await getFreeBalance(bob));228    });229  });230231  it('Can\'t cancel an operation which is not scheduled', async () => {232    await usingApi(async api => {233      const scheduledId = makeScheduledId();234      await expect(cancelScheduled(api, alice, scheduledId)).to.be.rejectedWith(/scheduler\.NotFound/);235    });236  });237238  it('Can\'t cancel a non-owned scheduled operation', async () => {239    await usingApi(async api => {240      const collectionId = await createCollectionExpectSuccess();241      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');242      const scheduledId = makeScheduledId();243      const waitForBlocks = 3;244245      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 1, waitForBlocks, scheduledId);246      await expect(cancelScheduled(api, bob, scheduledId)).to.be.rejected;247248      await waitNewBlocks(waitForBlocks);249250      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));251    });252  });253});254255// Implementation of the functionality tested here was postponed/shelved256describe.skip('Sponsoring scheduling', () => {257  let alice: IKeyringPair;258  let bob: IKeyringPair;259260  before(async() => {261    await usingApi(async (_, privateKeyWrapper) => {262      alice = privateKeyWrapper('//Alice');263      bob = privateKeyWrapper('//Bob');264    });265  });266267  it('Can sponsor scheduling a transaction', async () => {268    const collectionId = await createCollectionExpectSuccess();269    await setCollectionSponsorExpectSuccess(collectionId, bob.address);270    await confirmSponsorshipExpectSuccess(collectionId, '//Bob');271272    await usingApi(async api => {273      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);274275      const bobBalanceBefore = await getFreeBalance(bob);276      const waitForBlocks = 4;277      // no need to wait to check, fees must be deducted on scheduling, immediately278      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, makeScheduledId());279      const bobBalanceAfter = await getFreeBalance(bob);280      // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;281      expect(bobBalanceAfter < bobBalanceBefore).to.be.true;282      // wait for sequentiality matters283      await waitNewBlocks(waitForBlocks - 1);284    });285  });286287  it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {288    await usingApi(async (api, privateKeyWrapper) => {289      // Find an empty, unused account290      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);291292      const collectionId = await createCollectionExpectSuccess();293294      // Add zeroBalance address to allow list295      await enablePublicMintingExpectSuccess(alice, collectionId);296      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);297298      // Grace zeroBalance with money, enough to cover future transactions299      const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);300      await submitTransactionAsync(alice, balanceTx);301302      // Mint a fresh NFT303      const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');304305      // Schedule transfer of the NFT a few blocks ahead306      const waitForBlocks = 5;307      await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, makeScheduledId());308309      // Get rid of the account's funds before the scheduled transaction takes place310      const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);311      const events = await submitTransactionAsync(zeroBalance, balanceTx2);312      expect(getGenericResult(events).success).to.be.true;313      /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?314      const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);315      const events = await submitTransactionAsync(alice, sudoTx);316      expect(getGenericResult(events).success).to.be.true;*/317318      // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions319      await waitNewBlocks(waitForBlocks - 3);320321      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));322    });323  });324325  it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {326    const collectionId = await createCollectionExpectSuccess();327328    await usingApi(async (api, privateKeyWrapper) => {329      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);330      const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);331      await submitTransactionAsync(alice, balanceTx);332333      await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);334      await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);335336      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);337338      const waitForBlocks = 5;339      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, makeScheduledId());340341      const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);342      const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);343      const events = await submitTransactionAsync(alice, sudoTx);344      expect(getGenericResult(events).success).to.be.true;345346      // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions347      await waitNewBlocks(waitForBlocks - 3);348349      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));350    });351  });352353  it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {354    const collectionId = await createCollectionExpectSuccess();355    await setCollectionSponsorExpectSuccess(collectionId, bob.address);356    await confirmSponsorshipExpectSuccess(collectionId, '//Bob');357358    await usingApi(async (api, privateKeyWrapper) => {359      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);360361      await enablePublicMintingExpectSuccess(alice, collectionId);362      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);363364      const bobBalanceBefore = await getFreeBalance(bob);365366      const createData = {nft: {const_data: [], variable_data: []}};367      const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);368369      /*const badTransaction = async function () {370        await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);371      };372      await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/373374      await expect(scheduleAfter(api, creationTx, zeroBalance, 3, makeScheduledId(), 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);375376      expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);377    });378  });379});
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 chai, {expect} from 'chai';18import chaiAsPromised from 'chai-as-promised';19import {20  default as usingApi,21  submitTransactionAsync,22} from '../substrate/substrate-api';23import {24  createItemExpectSuccess,25  createCollectionExpectSuccess,26  scheduleTransferExpectSuccess,27  scheduleTransferAndWaitExpectSuccess,28  setCollectionSponsorExpectSuccess,29  confirmSponsorshipExpectSuccess,30  findUnusedAddress,31  UNIQUE,32  enablePublicMintingExpectSuccess,33  addToAllowListExpectSuccess,34  waitNewBlocks,35  normalizeAccountId,36  getTokenOwner,37  getGenericResult,38  scheduleTransferFundsExpectSuccess,39  getFreeBalance,40  confirmSponsorshipByKeyExpectSuccess,41  scheduleExpectFailure,42  scheduleAfter,43  cancelScheduled,44} from '../deprecated-helpers/helpers';45import {IKeyringPair} from '@polkadot/types/types';46import {ApiPromise} from '@polkadot/api';4748chai.use(chaiAsPromised);4950const scheduledIdBase: string = '0x' + '0'.repeat(31);51let scheduledIdSlider = 0;5253// Loop scheduledId around 10. Unless there are concurrent tasks with long periods/repetitions, tests' tasks' ids shouldn't ovelap.54function makeScheduledId(): string {55  return scheduledIdBase + ((scheduledIdSlider++) % 10);56}5758// Check that there are no failing Dispatched events in the block59function checkForFailedSchedulerEvents(api: ApiPromise, events: any[]) {60  return new Promise((res, rej) => {61    let schedulerEventPresent = false;62    63    for (const {event} of events) {64      if (api.events.scheduler.Dispatched.is(event)) {65        schedulerEventPresent = true;66        const result = event.data.result;67        if (result.isErr) {68          const decoded = api.registry.findMetaError(result.asErr.asModule);69          const {method, section} = decoded;70          rej(new Error(`${section}.${method}`));71        }72      }73    }74    res(schedulerEventPresent);75  });76}7778describe('Scheduling token and balance transfers', () => {79  let alice: IKeyringPair;80  let bob: IKeyringPair;8182  before(async() => {83    await usingApi(async (_, privateKeyWrapper) => {84      alice = privateKeyWrapper('//Alice');85      bob = privateKeyWrapper('//Bob');86    });87  });888990  it('Can delay a transfer of an owned token', async () => {91    await usingApi(async api => {92      const collectionId = await createCollectionExpectSuccess();93      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');9495      await scheduleTransferAndWaitExpectSuccess(api, collectionId, tokenId, alice, bob, 1, 4, makeScheduledId());96    });97  });9899  it('Can transfer funds periodically', async () => {100    await usingApi(async api => {101      const waitForBlocks = 1;102      const period = 2;103      const repetitions = 2;104105      const amount = 1n * UNIQUE;106107      await scheduleTransferFundsExpectSuccess(api, amount, alice, bob, waitForBlocks, makeScheduledId(), period, repetitions);108      const bobsBalanceBefore = await getFreeBalance(bob);109110      await waitNewBlocks(waitForBlocks + 1);111      const bobsBalanceAfterFirst = await getFreeBalance(bob);112      expect(bobsBalanceAfterFirst)113        .to.be.equal(114          bobsBalanceBefore + 1n * amount,115          '#1 Balance of the recipient should be increased by 1 * amount',116        );117118      await waitNewBlocks(period);119      const bobsBalanceAfterSecond = await getFreeBalance(bob);120      expect(bobsBalanceAfterSecond)121        .to.be.equal(122          bobsBalanceBefore + 2n * amount,123          '#2 Balance of the recipient should be increased by 2 * amount',124        );125    });126  });127128  it('Can cancel a scheduled operation which has not yet taken effect', async () => {129    await usingApi(async api => {130      const collectionId = await createCollectionExpectSuccess();131      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');132      const scheduledId = makeScheduledId();133      const waitForBlocks = 4;134135      const amount = 1;136137      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, amount, waitForBlocks, scheduledId);138      await expect(cancelScheduled(api, alice, scheduledId)).to.not.be.rejected;139140      await waitNewBlocks(waitForBlocks);141142      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));143    });144  });145146  it('Can cancel a periodic operation (transfer of funds)', async () => {147    await usingApi(async api => {148      const waitForBlocks = 1;149      const period = 3;150      const repetitions = 2;151152      const scheduledId = makeScheduledId();153      const amount = 1n * UNIQUE;154155      const bobsBalanceBefore = await getFreeBalance(bob);156      await scheduleTransferFundsExpectSuccess(api, amount, alice, bob, waitForBlocks, scheduledId, period, repetitions);157158      await waitNewBlocks(waitForBlocks + 1);159      const bobsBalanceAfterFirst = await getFreeBalance(bob);160      expect(bobsBalanceAfterFirst)161        .to.be.equal(162          bobsBalanceBefore + 1n * amount,163          '#1 Balance of the recipient should be increased by 1 * amount',164        );165166      await expect(cancelScheduled(api, alice, scheduledId)).to.not.be.rejected;167168      await waitNewBlocks(period);169      const bobsBalanceAfterSecond = await getFreeBalance(bob);170      expect(bobsBalanceAfterSecond)171        .to.be.equal(172          bobsBalanceAfterFirst,173          '#2 Balance of the recipient should not be changed',174        );175    });176  });177178  // FIXME What purpose of this test?179  it.skip('Can schedule a scheduled operation of canceling the scheduled operation', async () => {180    await usingApi(async api => {181      const scheduledId = makeScheduledId();182183      const waitForBlocks = 2;184      const period = 3;185      const repetitions = 2;186187      await expect(scheduleAfter(188        api, 189        api.tx.scheduler.cancelNamed(scheduledId), 190        alice, 191        waitForBlocks, 192        scheduledId, 193        period, 194        repetitions,195      )).to.not.be.rejected;196197      await waitNewBlocks(waitForBlocks);198199      // todo:scheduler debug line; doesn't work (and doesn't appear in events) when executed in the same block as the scheduled transaction200      await expect(submitTransactionAsync(alice, api.tx.scheduler.cancelNamed(scheduledId))).to.not.be.rejected;201202      let schedulerEvents = 0;203      for (let i = 0; i < period * repetitions; i++) {204        const events = await api.query.system.events();205        schedulerEvents += await expect(checkForFailedSchedulerEvents(api, events)).to.not.be.rejected;206        await waitNewBlocks(1);207      }208      expect(schedulerEvents).to.be.equal(repetitions);209    });210  });211212  after(async () => {213    // todo:scheduler to avoid the failed results of the previous test interfering with the next, delete after the problem is fixed214    await waitNewBlocks(6);215  });216});217218describe('Negative Test: Scheduling', () => {219  let alice: IKeyringPair;220  let bob: IKeyringPair;221222  before(async() => {223    await usingApi(async (_, privateKeyWrapper) => {224      alice = privateKeyWrapper('//Alice');225      bob = privateKeyWrapper('//Bob');226    });227  });228229  it("Can't overwrite a scheduled ID", async () => {230    await usingApi(async api => {231      const collectionId = await createCollectionExpectSuccess();232      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');233      const scheduledId = makeScheduledId();234      const waitForBlocks = 4;235      const amount = 1;236237      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, amount, waitForBlocks, scheduledId);238      await expect(scheduleAfter(239        api, 240        api.tx.balances.transfer(alice.address, 1n * UNIQUE), 241        bob, 242        /* period = */ 2, 243        scheduledId,244      )).to.be.rejectedWith(/scheduler\.FailedToSchedule/);245246      const bobsBalanceBefore = await getFreeBalance(bob);247248      await waitNewBlocks(waitForBlocks);249250      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(bob.address));251      expect(bobsBalanceBefore).to.be.equal(await getFreeBalance(bob));252    });253  });254255  it("Can't cancel an operation which is not scheduled", async () => {256    await usingApi(async api => {257      const scheduledId = makeScheduledId();258      await expect(cancelScheduled(api, alice, scheduledId)).to.be.rejectedWith(/scheduler\.NotFound/);259    });260  });261262  it("Can't cancel a non-owned scheduled operation", async () => {263    await usingApi(async api => {264      const collectionId = await createCollectionExpectSuccess();265      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');266      const scheduledId = makeScheduledId();267      const waitForBlocks = 3;268269      const amount = 1;270271      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, amount, waitForBlocks, scheduledId);272      await expect(cancelScheduled(api, bob, scheduledId)).to.be.rejected;273274      await waitNewBlocks(waitForBlocks);275276      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));277    });278  });279});280281// Implementation of the functionality tested here was postponed/shelved282describe.skip('Sponsoring scheduling', () => {283  let alice: IKeyringPair;284  let bob: IKeyringPair;285286  before(async() => {287    await usingApi(async (_, privateKeyWrapper) => {288      alice = privateKeyWrapper('//Alice');289      bob = privateKeyWrapper('//Bob');290    });291  });292293  it('Can sponsor scheduling a transaction', async () => {294    const collectionId = await createCollectionExpectSuccess();295    await setCollectionSponsorExpectSuccess(collectionId, bob.address);296    await confirmSponsorshipExpectSuccess(collectionId, '//Bob');297298    await usingApi(async api => {299      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);300301      const bobBalanceBefore = await getFreeBalance(bob);302      const waitForBlocks = 4;303      // no need to wait to check, fees must be deducted on scheduling, immediately304      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, makeScheduledId());305      const bobBalanceAfter = await getFreeBalance(bob);306      // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;307      expect(bobBalanceAfter < bobBalanceBefore).to.be.true;308      // wait for sequentiality matters309      await waitNewBlocks(waitForBlocks - 1);310    });311  });312313  it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {314    await usingApi(async (api, privateKeyWrapper) => {315      // Find an empty, unused account316      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);317318      const collectionId = await createCollectionExpectSuccess();319320      // Add zeroBalance address to allow list321      await enablePublicMintingExpectSuccess(alice, collectionId);322      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);323324      // Grace zeroBalance with money, enough to cover future transactions325      const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);326      await submitTransactionAsync(alice, balanceTx);327328      // Mint a fresh NFT329      const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');330331      // Schedule transfer of the NFT a few blocks ahead332      const waitForBlocks = 5;333      await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, makeScheduledId());334335      // Get rid of the account's funds before the scheduled transaction takes place336      const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);337      const events = await submitTransactionAsync(zeroBalance, balanceTx2);338      expect(getGenericResult(events).success).to.be.true;339      /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?340      const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);341      const events = await submitTransactionAsync(alice, sudoTx);342      expect(getGenericResult(events).success).to.be.true;*/343344      // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions345      await waitNewBlocks(waitForBlocks - 3);346347      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));348    });349  });350351  it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {352    const collectionId = await createCollectionExpectSuccess();353354    await usingApi(async (api, privateKeyWrapper) => {355      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);356      const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);357      await submitTransactionAsync(alice, balanceTx);358359      await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);360      await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);361362      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);363364      const waitForBlocks = 5;365      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, makeScheduledId());366367      const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);368      const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);369      const events = await submitTransactionAsync(alice, sudoTx);370      expect(getGenericResult(events).success).to.be.true;371372      // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions373      await waitNewBlocks(waitForBlocks - 3);374375      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));376    });377  });378379  it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {380    const collectionId = await createCollectionExpectSuccess();381    await setCollectionSponsorExpectSuccess(collectionId, bob.address);382    await confirmSponsorshipExpectSuccess(collectionId, '//Bob');383384    await usingApi(async (api, privateKeyWrapper) => {385      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);386387      await enablePublicMintingExpectSuccess(alice, collectionId);388      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);389390      const bobBalanceBefore = await getFreeBalance(bob);391392      const createData = {nft: {const_data: [], variable_data: []}};393      const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);394395      /*const badTransaction = async function () {396        await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);397      };398      await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/399400      await expect(scheduleAfter(api, creationTx, zeroBalance, 3, makeScheduledId(), 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);401402      expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);403    });404  });405});