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

difftreelog

test scheduled tx should take a fee

Daniel Shiposha2022-08-18parent: #07b1ed5.patch.diff
in: master

2 files changed

modifiedtest-pallets/utils/src/lib.rsdiffbeforeafterboth
--- a/test-pallets/utils/src/lib.rs
+++ b/test-pallets/utils/src/lib.rs
@@ -69,5 +69,10 @@
 
 			Err(<Error<T>>::TriggerRollback.into())
 		}
+
+		#[pallet::weight(100_000_000)]
+		pub fn just_take_fee(_origin: OriginFor<T>) -> DispatchResult {
+			Ok(())
+		}
 	}
 }
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  submitTransactionExpectFailAsync,23} from '../substrate/substrate-api';24import {25  createItemExpectSuccess,26  createCollectionExpectSuccess,27  scheduleTransferExpectSuccess,28  scheduleTransferAndWaitExpectSuccess,29  setCollectionSponsorExpectSuccess,30  confirmSponsorshipExpectSuccess,31  findUnusedAddress,32  UNIQUE,33  enablePublicMintingExpectSuccess,34  addToAllowListExpectSuccess,35  waitNewBlocks,36  normalizeAccountId,37  getTokenOwner,38  getGenericResult,39  scheduleTransferFundsExpectSuccess,40  getFreeBalance,41  confirmSponsorshipByKeyExpectSuccess,42  scheduleExpectFailure,43  scheduleAfter,44  cancelScheduled,45  requirePallets,46  Pallets,47} from '../deprecated-helpers/helpers';48import {IKeyringPair} from '@polkadot/types/types';49import {ApiPromise} from '@polkadot/api';5051chai.use(chaiAsPromised);5253const scheduledIdBase: string = '0x' + '0'.repeat(31);54let scheduledIdSlider = 0;5556// Loop scheduledId around 10. Unless there are concurrent tasks with long periods/repetitions, tests' tasks' ids shouldn't ovelap.57function makeScheduledId(): string {58  return scheduledIdBase + ((scheduledIdSlider++) % 10);59}6061// Check that there are no failing Dispatched events in the block62function checkForFailedSchedulerEvents(api: ApiPromise, events: any[]) {63  return new Promise((res, rej) => {64    let schedulerEventPresent = false;65    66    for (const {event} of events) {67      if (api.events.scheduler.Dispatched.is(event)) {68        schedulerEventPresent = true;69        const result = event.data.result;70        if (result.isErr) {71          const decoded = api.registry.findMetaError(result.asErr.asModule);72          const {method, section} = decoded;73          rej(new Error(`${section}.${method}`));74        }75      }76    }77    res(schedulerEventPresent);78  });79}8081describe('Scheduling token and balance transfers', () => {82  let alice: IKeyringPair;83  let bob: IKeyringPair;8485  before(async function() {86    await requirePallets(this, [Pallets.Scheduler]);8788    await usingApi(async (_, privateKeyWrapper) => {89      alice = privateKeyWrapper('//Alice');90      bob = privateKeyWrapper('//Bob');91    });92  });939495  it('Can delay a transfer of an owned token', async () => {96    await usingApi(async api => {97      const collectionId = await createCollectionExpectSuccess();98      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');99100      await scheduleTransferAndWaitExpectSuccess(api, collectionId, tokenId, alice, bob, 1, 4, makeScheduledId());101    });102  });103104  it('Can transfer funds periodically', async () => {105    await usingApi(async api => {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, makeScheduledId(), 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 = 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 = 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 = makeScheduledId();188      const waitForBlocks = 4;189      const period = null;190      const priority = 0;191192      const initTestVal = 42;193      const changedTestVal = 111;194195      const initTx = api.tx.testUtils.setTestValue(initTestVal);196      await submitTransactionAsync(alice, initTx);197198      const changeErrTx = api.tx.testUtils.setTestValueAndRollback(changedTestVal);199200      const scheduleTx = api.tx.scheduler.scheduleNamedAfter(201        scheduledId,202        waitForBlocks, 203        period,204        priority, 205        {Value: changeErrTx as any},206      );207208      await submitTransactionAsync(alice, scheduleTx);209210      await waitNewBlocks(waitForBlocks);211212      const testVal = (await api.query.testUtils.testValue()).toNumber();213      expect(testVal, 'The test value should NOT be commited')214        .not.to.be.equal(changedTestVal)215        .and.to.be.equal(initTx);216    });217  });218219  // FIXME What purpose of this test?220  it.skip('Can schedule a scheduled operation of canceling the scheduled operation', async () => {221    await usingApi(async api => {222      const scheduledId = makeScheduledId();223224      const waitForBlocks = 2;225      const period = 3;226      const repetitions = 2;227228      await expect(scheduleAfter(229        api, 230        api.tx.scheduler.cancelNamed(scheduledId), 231        alice, 232        waitForBlocks, 233        scheduledId, 234        period, 235        repetitions,236      )).to.not.be.rejected;237238      await waitNewBlocks(waitForBlocks);239240      // todo:scheduler debug line; doesn't work (and doesn't appear in events) when executed in the same block as the scheduled transaction241      await expect(submitTransactionAsync(alice, api.tx.scheduler.cancelNamed(scheduledId))).to.not.be.rejected;242243      let schedulerEvents = 0;244      for (let i = 0; i < period * repetitions; i++) {245        const events = await api.query.system.events();246        schedulerEvents += await expect(checkForFailedSchedulerEvents(api, events)).to.not.be.rejected;247        await waitNewBlocks(1);248      }249      expect(schedulerEvents).to.be.equal(repetitions);250    });251  });252253  after(async () => {254    // todo:scheduler to avoid the failed results of the previous test interfering with the next, delete after the problem is fixed255    await waitNewBlocks(6);256  });257});258259describe('Negative Test: Scheduling', () => {260  let alice: IKeyringPair;261  let bob: IKeyringPair;262263  before(async function() {264    await requirePallets(this, [Pallets.Scheduler]);265266    await usingApi(async (_, privateKeyWrapper) => {267      alice = privateKeyWrapper('//Alice');268      bob = privateKeyWrapper('//Bob');269    });270  });271272  it("Can't overwrite a scheduled ID", async () => {273    await usingApi(async api => {274      const collectionId = await createCollectionExpectSuccess();275      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');276      const scheduledId = makeScheduledId();277      const waitForBlocks = 4;278      const amount = 1;279280      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, amount, waitForBlocks, scheduledId);281      await expect(scheduleAfter(282        api, 283        api.tx.balances.transfer(alice.address, 1n * UNIQUE), 284        bob, 285        /* period = */ 2, 286        scheduledId,287      )).to.be.rejectedWith(/scheduler\.FailedToSchedule/);288289      const bobsBalanceBefore = await getFreeBalance(bob);290291      await waitNewBlocks(waitForBlocks);292293      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(bob.address));294      expect(bobsBalanceBefore).to.be.equal(await getFreeBalance(bob));295    });296  });297298  it("Can't cancel an operation which is not scheduled", async () => {299    await usingApi(async api => {300      const scheduledId = makeScheduledId();301      await expect(cancelScheduled(api, alice, scheduledId)).to.be.rejectedWith(/scheduler\.NotFound/);302    });303  });304305  it("Can't cancel a non-owned scheduled operation", async () => {306    await usingApi(async api => {307      const collectionId = await createCollectionExpectSuccess();308      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');309      const scheduledId = makeScheduledId();310      const waitForBlocks = 8;311312      const amount = 1;313314      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, amount, waitForBlocks, scheduledId);315      await expect(cancelScheduled(api, bob, scheduledId)).to.be.rejectedWith(/BadOrigin/);316317      await waitNewBlocks(waitForBlocks);318319      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(bob.address));320    });321  });322});323324// Implementation of the functionality tested here was postponed/shelved325describe.skip('Sponsoring scheduling', () => {326  let alice: IKeyringPair;327  let bob: IKeyringPair;328329  before(async() => {330    await usingApi(async (_, privateKeyWrapper) => {331      alice = privateKeyWrapper('//Alice');332      bob = privateKeyWrapper('//Bob');333    });334  });335336  it('Can sponsor scheduling a transaction', async () => {337    const collectionId = await createCollectionExpectSuccess();338    await setCollectionSponsorExpectSuccess(collectionId, bob.address);339    await confirmSponsorshipExpectSuccess(collectionId, '//Bob');340341    await usingApi(async api => {342      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);343344      const bobBalanceBefore = await getFreeBalance(bob);345      const waitForBlocks = 4;346      // no need to wait to check, fees must be deducted on scheduling, immediately347      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, makeScheduledId());348      const bobBalanceAfter = await getFreeBalance(bob);349      // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;350      expect(bobBalanceAfter < bobBalanceBefore).to.be.true;351      // wait for sequentiality matters352      await waitNewBlocks(waitForBlocks - 1);353    });354  });355356  it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {357    await usingApi(async (api, privateKeyWrapper) => {358      // Find an empty, unused account359      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);360361      const collectionId = await createCollectionExpectSuccess();362363      // Add zeroBalance address to allow list364      await enablePublicMintingExpectSuccess(alice, collectionId);365      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);366367      // Grace zeroBalance with money, enough to cover future transactions368      const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);369      await submitTransactionAsync(alice, balanceTx);370371      // Mint a fresh NFT372      const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');373374      // Schedule transfer of the NFT a few blocks ahead375      const waitForBlocks = 5;376      await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, makeScheduledId());377378      // Get rid of the account's funds before the scheduled transaction takes place379      const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);380      const events = await submitTransactionAsync(zeroBalance, balanceTx2);381      expect(getGenericResult(events).success).to.be.true;382      /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?383      const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);384      const events = await submitTransactionAsync(alice, sudoTx);385      expect(getGenericResult(events).success).to.be.true;*/386387      // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions388      await waitNewBlocks(waitForBlocks - 3);389390      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));391    });392  });393394  it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {395    const collectionId = await createCollectionExpectSuccess();396397    await usingApi(async (api, privateKeyWrapper) => {398      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);399      const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);400      await submitTransactionAsync(alice, balanceTx);401402      await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);403      await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);404405      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);406407      const waitForBlocks = 5;408      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, makeScheduledId());409410      const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);411      const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);412      const events = await submitTransactionAsync(alice, sudoTx);413      expect(getGenericResult(events).success).to.be.true;414415      // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions416      await waitNewBlocks(waitForBlocks - 3);417418      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));419    });420  });421422  it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {423    const collectionId = await createCollectionExpectSuccess();424    await setCollectionSponsorExpectSuccess(collectionId, bob.address);425    await confirmSponsorshipExpectSuccess(collectionId, '//Bob');426427    await usingApi(async (api, privateKeyWrapper) => {428      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);429430      await enablePublicMintingExpectSuccess(alice, collectionId);431      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);432433      const bobBalanceBefore = await getFreeBalance(bob);434435      const createData = {nft: {const_data: [], variable_data: []}};436      const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);437438      /*const badTransaction = async function () {439        await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);440      };441      await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/442443      await expect(scheduleAfter(api, creationTx, zeroBalance, 3, makeScheduledId(), 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);444445      expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);446    });447  });448});
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  submitTransactionExpectFailAsync,23} from '../substrate/substrate-api';24import {25  createItemExpectSuccess,26  createCollectionExpectSuccess,27  scheduleTransferExpectSuccess,28  scheduleTransferAndWaitExpectSuccess,29  setCollectionSponsorExpectSuccess,30  confirmSponsorshipExpectSuccess,31  findUnusedAddress,32  UNIQUE,33  enablePublicMintingExpectSuccess,34  addToAllowListExpectSuccess,35  waitNewBlocks,36  normalizeAccountId,37  getTokenOwner,38  getGenericResult,39  scheduleTransferFundsExpectSuccess,40  getFreeBalance,41  confirmSponsorshipByKeyExpectSuccess,42  scheduleExpectFailure,43  scheduleAfter,44  cancelScheduled,45  requirePallets,46  Pallets,47} from '../deprecated-helpers/helpers';48import {IKeyringPair} from '@polkadot/types/types';49import {ApiPromise} from '@polkadot/api';5051chai.use(chaiAsPromised);5253const scheduledIdBase: string = '0x' + '0'.repeat(31);54let scheduledIdSlider = 0;5556// Loop scheduledId around 10. Unless there are concurrent tasks with long periods/repetitions, tests' tasks' ids shouldn't ovelap.57function makeScheduledId(): string {58  return scheduledIdBase + ((scheduledIdSlider++) % 10);59}6061// Check that there are no failing Dispatched events in the block62function checkForFailedSchedulerEvents(api: ApiPromise, events: any[]) {63  return new Promise((res, rej) => {64    let schedulerEventPresent = false;65    66    for (const {event} of events) {67      if (api.events.scheduler.Dispatched.is(event)) {68        schedulerEventPresent = true;69        const result = event.data.result;70        if (result.isErr) {71          const decoded = api.registry.findMetaError(result.asErr.asModule);72          const {method, section} = decoded;73          rej(new Error(`${section}.${method}`));74        }75      }76    }77    res(schedulerEventPresent);78  });79}8081describe('Scheduling token and balance transfers', () => {82  let alice: IKeyringPair;83  let bob: IKeyringPair;8485  before(async function() {86    await requirePallets(this, [Pallets.Scheduler]);8788    await usingApi(async (_, privateKeyWrapper) => {89      alice = privateKeyWrapper('//Alice');90      bob = privateKeyWrapper('//Bob');91    });92  });939495  it('Can delay a transfer of an owned token', async () => {96    await usingApi(async api => {97      const collectionId = await createCollectionExpectSuccess();98      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');99100      await scheduleTransferAndWaitExpectSuccess(api, collectionId, tokenId, alice, bob, 1, 4, makeScheduledId());101    });102  });103104  it('Can transfer funds periodically', async () => {105    await usingApi(async api => {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, makeScheduledId(), 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 = 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 = 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 = makeScheduledId();188      const waitForBlocks = 4;189      const period = null;190      const priority = 0;191192      const initTestVal = 42;193      const changedTestVal = 111;194195      const initTx = api.tx.testUtils.setTestValue(initTestVal);196      await submitTransactionAsync(alice, initTx);197198      const changeErrTx = api.tx.testUtils.setTestValueAndRollback(changedTestVal);199200      const scheduleTx = api.tx.scheduler.scheduleNamedAfter(201        scheduledId,202        waitForBlocks, 203        period,204        priority, 205        {Value: changeErrTx as any},206      );207208      await submitTransactionAsync(alice, scheduleTx);209210      await waitNewBlocks(waitForBlocks);211212      const testVal = (await api.query.testUtils.testValue()).toNumber();213      expect(testVal, 'The test value should NOT be commited')214        .not.to.be.equal(changedTestVal)215        .and.to.be.equal(initTx);216    });217  });218219  it('Scheduled tasks should take some fees', async function() {220    await requirePallets(this, [Pallets.TestUtils]);221222    await usingApi(async api => {223      const scheduledId = makeScheduledId();224      const waitForBlocks = 10;225      const period = 2;226      const repetitions = 1;227228      const dummyTxFeeAmount = 100_000_000;229230      const dummyTx = api.tx.testUtils.justTakeFee();231232      await expect(scheduleAfter(233        api,234        dummyTx,235        alice,236        waitForBlocks,237        scheduledId,238        period,239        repetitions,240      )).to.not.be.rejected;241242      const aliceInitBalance = await getFreeBalance(alice);243      let diff;244245      await waitNewBlocks(waitForBlocks + 1);246247      const aliceBalanceAfterFirst = await getFreeBalance(alice);248      expect(249        aliceBalanceAfterFirst < aliceInitBalance,250        '[after execution #1] Scheduled task should take a fee',251      ).to.be.true;252253      diff = aliceInitBalance - aliceBalanceAfterFirst;254      expect(diff).to.be.equal(dummyTxFeeAmount, 'Scheduled task should take the right amount of fees');255256      await waitNewBlocks(period);257258      const aliceBalanceAfterSecond = await getFreeBalance(alice);259      expect(260        aliceBalanceAfterSecond < aliceBalanceAfterFirst,261        '[after execution #2] Scheduled task should take a fee',262      ).to.be.true;263264      diff = aliceBalanceAfterFirst - aliceBalanceAfterSecond;265      expect(diff).to.be.equal(dummyTxFeeAmount, 'Scheduled task should take the right amount of fees');266    });267  });268269  // FIXME What purpose of this test?270  it.skip('Can schedule a scheduled operation of canceling the scheduled operation', async () => {271    await usingApi(async api => {272      const scheduledId = makeScheduledId();273274      const waitForBlocks = 2;275      const period = 3;276      const repetitions = 2;277278      await expect(scheduleAfter(279        api, 280        api.tx.scheduler.cancelNamed(scheduledId), 281        alice, 282        waitForBlocks, 283        scheduledId, 284        period, 285        repetitions,286      )).to.not.be.rejected;287288      await waitNewBlocks(waitForBlocks);289290      // todo:scheduler debug line; doesn't work (and doesn't appear in events) when executed in the same block as the scheduled transaction291      await expect(submitTransactionAsync(alice, api.tx.scheduler.cancelNamed(scheduledId))).to.not.be.rejected;292293      let schedulerEvents = 0;294      for (let i = 0; i < period * repetitions; i++) {295        const events = await api.query.system.events();296        schedulerEvents += await expect(checkForFailedSchedulerEvents(api, events)).to.not.be.rejected;297        await waitNewBlocks(1);298      }299      expect(schedulerEvents).to.be.equal(repetitions);300    });301  });302303  after(async () => {304    // todo:scheduler to avoid the failed results of the previous test interfering with the next, delete after the problem is fixed305    await waitNewBlocks(6);306  });307});308309describe('Negative Test: Scheduling', () => {310  let alice: IKeyringPair;311  let bob: IKeyringPair;312313  before(async function() {314    await requirePallets(this, [Pallets.Scheduler]);315316    await usingApi(async (_, privateKeyWrapper) => {317      alice = privateKeyWrapper('//Alice');318      bob = privateKeyWrapper('//Bob');319    });320  });321322  it("Can't overwrite a scheduled ID", async () => {323    await usingApi(async api => {324      const collectionId = await createCollectionExpectSuccess();325      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');326      const scheduledId = makeScheduledId();327      const waitForBlocks = 4;328      const amount = 1;329330      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, amount, waitForBlocks, scheduledId);331      await expect(scheduleAfter(332        api, 333        api.tx.balances.transfer(alice.address, 1n * UNIQUE), 334        bob, 335        /* period = */ 2, 336        scheduledId,337      )).to.be.rejectedWith(/scheduler\.FailedToSchedule/);338339      const bobsBalanceBefore = await getFreeBalance(bob);340341      await waitNewBlocks(waitForBlocks);342343      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(bob.address));344      expect(bobsBalanceBefore).to.be.equal(await getFreeBalance(bob));345    });346  });347348  it("Can't cancel an operation which is not scheduled", async () => {349    await usingApi(async api => {350      const scheduledId = makeScheduledId();351      await expect(cancelScheduled(api, alice, scheduledId)).to.be.rejectedWith(/scheduler\.NotFound/);352    });353  });354355  it("Can't cancel a non-owned scheduled operation", async () => {356    await usingApi(async api => {357      const collectionId = await createCollectionExpectSuccess();358      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');359      const scheduledId = makeScheduledId();360      const waitForBlocks = 8;361362      const amount = 1;363364      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, amount, waitForBlocks, scheduledId);365      await expect(cancelScheduled(api, bob, scheduledId)).to.be.rejectedWith(/BadOrigin/);366367      await waitNewBlocks(waitForBlocks);368369      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(bob.address));370    });371  });372});373374// Implementation of the functionality tested here was postponed/shelved375describe.skip('Sponsoring scheduling', () => {376  let alice: IKeyringPair;377  let bob: IKeyringPair;378379  before(async() => {380    await usingApi(async (_, privateKeyWrapper) => {381      alice = privateKeyWrapper('//Alice');382      bob = privateKeyWrapper('//Bob');383    });384  });385386  it('Can sponsor scheduling a transaction', async () => {387    const collectionId = await createCollectionExpectSuccess();388    await setCollectionSponsorExpectSuccess(collectionId, bob.address);389    await confirmSponsorshipExpectSuccess(collectionId, '//Bob');390391    await usingApi(async api => {392      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);393394      const bobBalanceBefore = await getFreeBalance(bob);395      const waitForBlocks = 4;396      // no need to wait to check, fees must be deducted on scheduling, immediately397      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, makeScheduledId());398      const bobBalanceAfter = await getFreeBalance(bob);399      // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;400      expect(bobBalanceAfter < bobBalanceBefore).to.be.true;401      // wait for sequentiality matters402      await waitNewBlocks(waitForBlocks - 1);403    });404  });405406  it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {407    await usingApi(async (api, privateKeyWrapper) => {408      // Find an empty, unused account409      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);410411      const collectionId = await createCollectionExpectSuccess();412413      // Add zeroBalance address to allow list414      await enablePublicMintingExpectSuccess(alice, collectionId);415      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);416417      // Grace zeroBalance with money, enough to cover future transactions418      const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);419      await submitTransactionAsync(alice, balanceTx);420421      // Mint a fresh NFT422      const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');423424      // Schedule transfer of the NFT a few blocks ahead425      const waitForBlocks = 5;426      await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, makeScheduledId());427428      // Get rid of the account's funds before the scheduled transaction takes place429      const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);430      const events = await submitTransactionAsync(zeroBalance, balanceTx2);431      expect(getGenericResult(events).success).to.be.true;432      /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?433      const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);434      const events = await submitTransactionAsync(alice, sudoTx);435      expect(getGenericResult(events).success).to.be.true;*/436437      // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions438      await waitNewBlocks(waitForBlocks - 3);439440      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));441    });442  });443444  it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {445    const collectionId = await createCollectionExpectSuccess();446447    await usingApi(async (api, privateKeyWrapper) => {448      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);449      const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);450      await submitTransactionAsync(alice, balanceTx);451452      await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);453      await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);454455      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);456457      const waitForBlocks = 5;458      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, makeScheduledId());459460      const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);461      const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);462      const events = await submitTransactionAsync(alice, sudoTx);463      expect(getGenericResult(events).success).to.be.true;464465      // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions466      await waitNewBlocks(waitForBlocks - 3);467468      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));469    });470  });471472  it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {473    const collectionId = await createCollectionExpectSuccess();474    await setCollectionSponsorExpectSuccess(collectionId, bob.address);475    await confirmSponsorshipExpectSuccess(collectionId, '//Bob');476477    await usingApi(async (api, privateKeyWrapper) => {478      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);479480      await enablePublicMintingExpectSuccess(alice, collectionId);481      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);482483      const bobBalanceBefore = await getFreeBalance(bob);484485      const createData = {nft: {const_data: [], variable_data: []}};486      const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);487488      /*const badTransaction = async function () {489        await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);490      };491      await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/492493      await expect(scheduleAfter(api, creationTx, zeroBalance, 3, makeScheduledId(), 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);494495      expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);496    });497  });498});