git.delta.rocks / unique-network / refs/commits / 885653bf99d3

difftreelog

fix use getApi()

Daniel Shiposha2022-10-06parent: #10c6a16.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 {UNIQUE} from './util/helpers';18import {expect, itSub, Pallets, usingPlaygrounds} from './util/playgrounds';19import {IKeyringPair} from '@polkadot/types/types';2021describe('Scheduling token and balance transfers', () => {22  let alice: IKeyringPair;23  let bob: IKeyringPair;24  let charlie: IKeyringPair;2526  before(async () => {27    await usingPlaygrounds(async (_, privateKeyWrapper) => {28      alice = privateKeyWrapper('//Alice');29      bob = privateKeyWrapper('//Bob');30      charlie = privateKeyWrapper('//Charlie');31    });32  });3334  itSub.ifWithPallets('Can delay a transfer of an owned token', [Pallets.Scheduler], async ({helper}) => {35    const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});36    const token = await collection.mintToken(alice);37    const schedulerId = await helper.arrange.makeScheduledId();38    const blocksBeforeExecution = 4;3940    await token.scheduleAfter(schedulerId, blocksBeforeExecution)41      .transfer(alice, {Substrate: bob.address});4243    expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});4445    await helper.wait.newBlocks(blocksBeforeExecution + 1);4647    expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});48  });4950  itSub.ifWithPallets('Can transfer funds periodically', [Pallets.Scheduler], async ({helper}) => {51    const scheduledId = await helper.arrange.makeScheduledId();52    const waitForBlocks = 1;5354    const amount = 1n * UNIQUE;55    const periodic = {56      period: 2,57      repetitions: 2,58    };5960    const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);6162    await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})63      .balance.transferToSubstrate(alice, bob.address, amount);6465    await helper.wait.newBlocks(waitForBlocks + 1);6667    const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);68    expect(bobsBalanceAfterFirst)69      .to.be.equal(70        bobsBalanceBefore + 1n * amount,71        '#1 Balance of the recipient should be increased by 1 * amount',72      );7374    await helper.wait.newBlocks(periodic.period);7576    const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);77    expect(bobsBalanceAfterSecond)78      .to.be.equal(79        bobsBalanceBefore + 2n * amount,80        '#2 Balance of the recipient should be increased by 2 * amount',81      );82  });8384  itSub.ifWithPallets('Can cancel a scheduled operation which has not yet taken effect', [Pallets.Scheduler], async ({helper}) => {85    const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});86    const token = await collection.mintToken(alice);8788    const scheduledId = await helper.arrange.makeScheduledId();89    const waitForBlocks = 4;9091    expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});9293    await token.scheduleAfter(scheduledId, waitForBlocks)94      .transfer(alice, {Substrate: bob.address});9596    await helper.scheduler.cancelScheduled(alice, scheduledId);9798    await helper.wait.newBlocks(waitForBlocks + 1);99100    expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});101  });102103  itSub.ifWithPallets('Can cancel a periodic operation (transfer of funds)', [Pallets.Scheduler], async ({helper}) => {104    const waitForBlocks = 1;105    const periodic = {106      period: 3,107      repetitions: 2,108    };109110    const scheduledId = await helper.arrange.makeScheduledId();111112    const amount = 1n * UNIQUE;113114    const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);115116    await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})117      .balance.transferToSubstrate(alice, bob.address, amount);118119    await helper.wait.newBlocks(waitForBlocks + 1);120121    const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);122123    expect(bobsBalanceAfterFirst)124      .to.be.equal(125        bobsBalanceBefore + 1n * amount,126        '#1 Balance of the recipient should be increased by 1 * amount',127      );128129    await helper.scheduler.cancelScheduled(alice, scheduledId);130    await helper.wait.newBlocks(periodic.period);131132    const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);133    expect(bobsBalanceAfterSecond)134      .to.be.equal(135        bobsBalanceAfterFirst,136        '#2 Balance of the recipient should not be changed',137      );138  });139140  itSub.ifWithPallets('Scheduled tasks are transactional', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {141    const scheduledId = await helper.arrange.makeScheduledId();142    const waitForBlocks = 4;143144    const initTestVal = 42;145    const changedTestVal = 111;146147    await helper.executeExtrinsic(148      alice,149      'api.tx.testUtils.setTestValue',150      [initTestVal],151      true,152    );153154    await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks)155      .executeExtrinsic(156        alice,157        'api.tx.testUtils.setTestValueAndRollback',158        [changedTestVal],159        true,160      );161162    await helper.wait.newBlocks(waitForBlocks + 1);163164    const testVal = (await helper.api!.query.testUtils.testValue()).toNumber();165    expect(testVal, 'The test value should NOT be commited')166      .to.be.equal(initTestVal);167  });168169  itSub.ifWithPallets('Scheduled tasks should take correct fees', [Pallets.Scheduler, Pallets.TestUtils], async function({helper}) {170    const scheduledId = await helper.arrange.makeScheduledId();171    const waitForBlocks = 4;172    const periodic = {173      period: 2,174      repetitions: 2,175    };176177    const dummyTx = helper.constructApiCall('api.tx.testUtils.justTakeFee', []);178    const scheduledLen = dummyTx.callIndex.length;179180    const expectedScheduledFee = (await helper.getPaymentInfo(alice, dummyTx, scheduledLen))181      .partialFee.toBigInt();182183    await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})184      .executeExtrinsic(alice, 'api.tx.testUtils.justTakeFee', [], true);185186    await helper.wait.newBlocks(1);187188    const aliceInitBalance = await helper.balance.getSubstrate(alice.address);189    let diff;190191    await helper.wait.newBlocks(waitForBlocks);192193    const aliceBalanceAfterFirst = await helper.balance.getSubstrate(alice.address);194    expect(195      aliceBalanceAfterFirst < aliceInitBalance,196      '[after execution #1] Scheduled task should take a fee',197    ).to.be.true;198199    diff = aliceInitBalance - aliceBalanceAfterFirst;200    expect(diff).to.be.equal(201      expectedScheduledFee,202      'Scheduled task should take the right amount of fees',203    );204205    await helper.wait.newBlocks(periodic.period);206207    const aliceBalanceAfterSecond = await helper.balance.getSubstrate(alice.address);208    expect(209      aliceBalanceAfterSecond < aliceBalanceAfterFirst,210      '[after execution #2] Scheduled task should take a fee',211    ).to.be.true;212213    diff = aliceBalanceAfterFirst - aliceBalanceAfterSecond;214    expect(diff).to.be.equal(215      expectedScheduledFee,216      'Scheduled task should take the right amount of fees',217    );218  });219220  // Check if we can cancel a scheduled periodic operation221  // in the same block in which it is running222  itSub.ifWithPallets('Can cancel the periodic sheduled tx when the tx is running', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {223    const currentBlockNumber = await helper.chain.getLatestBlockNumber();224    const blocksBeforeExecution = 10;225    const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;226227    const [228      scheduledId,229      scheduledCancelId,230    ] = await helper.arrange.makeScheduledIds(2);231232    const periodic = {233      period: 5,234      repetitions: 5,235    };236237    const initTestVal = 0;238    const incTestVal = initTestVal + 1;239    const finalTestVal = initTestVal + 2;240241    await helper.executeExtrinsic(242      alice,243      'api.tx.testUtils.setTestValue',244      [initTestVal],245      true,246    );247248    await helper.scheduler.scheduleAt(scheduledId, firstExecutionBlockNumber, {periodic})249      .executeExtrinsic(250        alice,251        'api.tx.testUtils.incTestValue',252        [],253        true,254      );255256    // Cancel the inc tx after 2 executions257    // *in the same block* in which the second execution is scheduled258    await helper.scheduler.scheduleAt(259      scheduledCancelId,260      firstExecutionBlockNumber + periodic.period,261    ).scheduler.cancelScheduled(alice, scheduledId);262263    await helper.wait.newBlocks(blocksBeforeExecution);264265    // execution #0266    expect((await helper.api!.query.testUtils.testValue()).toNumber())267      .to.be.equal(incTestVal);268269    await helper.wait.newBlocks(periodic.period);270271    // execution #1272    expect((await helper.api!.query.testUtils.testValue()).toNumber())273      .to.be.equal(finalTestVal);274275    for (let i = 1; i < periodic.repetitions; i++) {276      await helper.wait.newBlocks(periodic.period);277      expect((await helper.api!.query.testUtils.testValue()).toNumber())278        .to.be.equal(finalTestVal);279    }280  });281282  itSub.ifWithPallets('A scheduled operation can cancel itself', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {283    const scheduledId = await helper.arrange.makeScheduledId();284    const waitForBlocks = 4;285    const periodic = {286      period: 2,287      repetitions: 5,288    };289290    const initTestVal = 0;291    const maxTestVal = 2;292293    await helper.executeExtrinsic(294      alice,295      'api.tx.testUtils.setTestValue',296      [initTestVal],297      true,298    );299300    await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})301      .executeExtrinsic(302        alice,303        'api.tx.testUtils.selfCancelingInc',304        [scheduledId, maxTestVal],305        true,306      );307308    await helper.wait.newBlocks(waitForBlocks + 1);309310    // execution #0311    expect((await helper.api!.query.testUtils.testValue()).toNumber())312      .to.be.equal(initTestVal + 1);313314    await helper.wait.newBlocks(periodic.period);315316    // execution #1317    expect((await helper.api!.query.testUtils.testValue()).toNumber())318      .to.be.equal(initTestVal + 2);319320    await helper.wait.newBlocks(periodic.period);321322    // <canceled>323    expect((await helper.api!.query.testUtils.testValue()).toNumber())324      .to.be.equal(initTestVal + 2);325  });326327  itSub.ifWithPallets('Root can cancel any scheduled operation', [Pallets.Scheduler], async ({helper}) => {328    const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});329    const token = await collection.mintToken(bob);330331    const scheduledId = await helper.arrange.makeScheduledId();332    const waitForBlocks = 4;333334    await token.scheduleAfter(scheduledId, waitForBlocks)335      .transfer(bob, {Substrate: alice.address});336337    await helper.getSudo().scheduler.cancelScheduled(alice, scheduledId);338339    await helper.wait.newBlocks(waitForBlocks + 1);340341    expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});342  });343344  itSub.ifWithPallets('Root can set prioritized scheduled operation', [Pallets.Scheduler], async ({helper}) => {345    const scheduledId = await helper.arrange.makeScheduledId();346    const waitForBlocks = 4;347348    const amount = 42n * UNIQUE;349350    const balanceBefore = await helper.balance.getSubstrate(charlie.address);351352    await helper.getSudo()353      .scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42})354      .balance.forceTransferToSubstrate(alice, bob.address, charlie.address, amount);355356    await helper.wait.newBlocks(waitForBlocks + 1);357358    const balanceAfter = await helper.balance.getSubstrate(charlie.address);359360    expect(balanceAfter > balanceBefore).to.be.true;361362    const diff = balanceAfter - balanceBefore;363    expect(diff).to.be.equal(amount);364  });365366  itSub.ifWithPallets("Root can change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {367    const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});368    const token = await collection.mintToken(bob);369370    const scheduledId = await helper.arrange.makeScheduledId();371    const waitForBlocks = 6;372373    await token.scheduleAfter(scheduledId, waitForBlocks)374      .transfer(bob, {Substrate: alice.address});375376    const priority = 112;377    await helper.getSudo().scheduler.changePriority(alice, scheduledId, priority);378379    const priorityChanged = await helper.wait.event(380      waitForBlocks,381      'scheduler',382      'PriorityChanged',383    );384385    expect(priorityChanged !== null).to.be.true;386    expect(priorityChanged!.event.data[2].toString()).to.be.equal(priority.toString());387  });388389  itSub.ifWithPallets('Prioritized operations executes in valid order', [Pallets.Scheduler], async ({helper}) => {390    const [391      scheduledFirstId,392      scheduledSecondId,393    ] = await helper.arrange.makeScheduledIds(2);394395    const currentBlockNumber = await helper.chain.getLatestBlockNumber();396    const blocksBeforeExecution = 4;397    const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;398399    const prioHigh = 0;400    const prioLow = 255;401402    const periodic = {403      period: 6,404      repetitions: 2,405    };406407    const amount = 1n * UNIQUE;408409    // Scheduler a task with a lower priority first, then with a higher priority410    await helper.getSudo().scheduler.scheduleAt(scheduledFirstId, firstExecutionBlockNumber, {priority: prioLow, periodic})411      .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);412413    await helper.getSudo().scheduler.scheduleAt(scheduledSecondId, firstExecutionBlockNumber, {priority: prioHigh, periodic})414      .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);415416    const capture = await helper.arrange.captureEvents('scheduler', 'Dispatched');417418    await helper.wait.newBlocks(blocksBeforeExecution);419420    // Flip priorities421    await helper.getSudo().scheduler.changePriority(alice, scheduledFirstId, prioHigh);422    await helper.getSudo().scheduler.changePriority(alice, scheduledSecondId, prioLow);423424    await helper.wait.newBlocks(periodic.period);425426    const dispatchEvents = capture.extractCapturedEvents();427    expect(dispatchEvents.length).to.be.equal(4);428429    const dispatchedIds = dispatchEvents.map(r => r.event.data[1].toString());430431    const firstExecuctionIds = [dispatchedIds[0], dispatchedIds[1]];432    const secondExecuctionIds = [dispatchedIds[2], dispatchedIds[3]];433434    expect(firstExecuctionIds[0]).to.be.equal(scheduledSecondId);435    expect(firstExecuctionIds[1]).to.be.equal(scheduledFirstId);436437    expect(secondExecuctionIds[0]).to.be.equal(scheduledFirstId);438    expect(secondExecuctionIds[1]).to.be.equal(scheduledSecondId);439  });440});441442describe('Negative Test: Scheduling', () => {443  let alice: IKeyringPair;444  let bob: IKeyringPair;445446  before(async () => {447    await usingPlaygrounds(async (_, privateKeyWrapper) => {448      alice = privateKeyWrapper('//Alice');449      bob = privateKeyWrapper('//Bob');450    });451  });452453  itSub.ifWithPallets("Can't overwrite a scheduled ID", [Pallets.Scheduler], async ({helper}) => {454    const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});455    const token = await collection.mintToken(alice);456457    const scheduledId = await helper.arrange.makeScheduledId();458    const waitForBlocks = 4;459460    await token.scheduleAfter(scheduledId, waitForBlocks)461      .transfer(alice, {Substrate: bob.address});462463    const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks);464    await expect(scheduled.balance.transferToSubstrate(alice, bob.address, 1n * UNIQUE))465      .to.be.rejectedWith(/scheduler\.FailedToSchedule/);466467    const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);468469    await helper.wait.newBlocks(waitForBlocks + 1);470471    const bobsBalanceAfter = await helper.balance.getSubstrate(bob.address);472473    expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});474    expect(bobsBalanceBefore).to.be.equal(bobsBalanceAfter);475  });476477  itSub.ifWithPallets("Can't cancel an operation which is not scheduled", [Pallets.Scheduler], async ({helper}) => {478    const scheduledId = await helper.arrange.makeScheduledId();479    await expect(helper.scheduler.cancelScheduled(alice, scheduledId))480      .to.be.rejectedWith(/scheduler\.NotFound/);481  });482483  itSub.ifWithPallets("Can't cancel a non-owned scheduled operation", [Pallets.Scheduler], async ({helper}) => {484    const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});485    const token = await collection.mintToken(alice);486487    const scheduledId = await helper.arrange.makeScheduledId();488    const waitForBlocks = 4;489490    await token.scheduleAfter(scheduledId, waitForBlocks)491      .transfer(alice, {Substrate: bob.address});492493    await expect(helper.scheduler.cancelScheduled(bob, scheduledId))494      .to.be.rejectedWith(/BadOrigin/);495496    await helper.wait.newBlocks(waitForBlocks + 1);497498    expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});499  });500501  itSub.ifWithPallets("Regular user can't set prioritized scheduled operation", [Pallets.Scheduler], async ({helper}) => {502    const scheduledId = await helper.arrange.makeScheduledId();503    const waitForBlocks = 4;504505    const amount = 42n * UNIQUE;506507    const balanceBefore = await helper.balance.getSubstrate(bob.address);508509    const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42});510    511    await expect(scheduled.balance.transferToSubstrate(alice, bob.address, amount))512      .to.be.rejectedWith(/BadOrigin/);513514    await helper.wait.newBlocks(waitForBlocks + 1);515516    const balanceAfter = await helper.balance.getSubstrate(bob.address);517518    expect(balanceAfter).to.be.equal(balanceBefore);519  });520521  itSub.ifWithPallets("Regular user can't change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {522    const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});523    const token = await collection.mintToken(bob);524525    const scheduledId = await helper.arrange.makeScheduledId();526    const waitForBlocks = 4;527528    await token.scheduleAfter(scheduledId, waitForBlocks)529      .transfer(bob, {Substrate: alice.address});530531    const priority = 112;532    await expect(helper.scheduler.changePriority(alice, scheduledId, priority))533      .to.be.rejectedWith(/BadOrigin/);534535    const priorityChanged = await helper.wait.event(536      waitForBlocks,537      'scheduler',538      'PriorityChanged',539    );540541    expect(priorityChanged === null).to.be.true;542  });543});544545// Implementation of the functionality tested here was postponed/shelved546describe.skip('Sponsoring scheduling', () => {547  // let alice: IKeyringPair;548  // let bob: IKeyringPair;549550  // before(async() => {551  //   await usingApi(async (_, privateKeyWrapper) => {552  //     alice = privateKeyWrapper('//Alice');553  //     bob = privateKeyWrapper('//Bob');554  //   });555  // });556557  it('Can sponsor scheduling a transaction', async () => {558    // const collectionId = await createCollectionExpectSuccess();559    // await setCollectionSponsorExpectSuccess(collectionId, bob.address);560    // await confirmSponsorshipExpectSuccess(collectionId, '//Bob');561562    // await usingApi(async api => {563    //   const scheduledId = await makeScheduledId();564    //   const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);565566    //   const bobBalanceBefore = await getFreeBalance(bob);567    //   const waitForBlocks = 4;568    //   // no need to wait to check, fees must be deducted on scheduling, immediately569    //   await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, scheduledId);570    //   const bobBalanceAfter = await getFreeBalance(bob);571    //   // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;572    //   expect(bobBalanceAfter < bobBalanceBefore).to.be.true;573    //   // wait for sequentiality matters574    //   await waitNewBlocks(waitForBlocks - 1);575    // });576  });577578  it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {579    // await usingApi(async (api, privateKeyWrapper) => {580    //   // Find an empty, unused account581    //   const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);582583    //   const collectionId = await createCollectionExpectSuccess();584585    //   // Add zeroBalance address to allow list586    //   await enablePublicMintingExpectSuccess(alice, collectionId);587    //   await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);588589    //   // Grace zeroBalance with money, enough to cover future transactions590    //   const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);591    //   await submitTransactionAsync(alice, balanceTx);592593    //   // Mint a fresh NFT594    //   const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');595    //   const scheduledId = await makeScheduledId();596597    //   // Schedule transfer of the NFT a few blocks ahead598    //   const waitForBlocks = 5;599    //   await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, scheduledId);600601    //   // Get rid of the account's funds before the scheduled transaction takes place602    //   const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);603    //   const events = await submitTransactionAsync(zeroBalance, balanceTx2);604    //   expect(getGenericResult(events).success).to.be.true;605    //   /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?606    //   const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);607    //   const events = await submitTransactionAsync(alice, sudoTx);608    //   expect(getGenericResult(events).success).to.be.true;*/609610    //   // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions611    //   await waitNewBlocks(waitForBlocks - 3);612613    //   expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));614    // });615  });616617  it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {618    // const collectionId = await createCollectionExpectSuccess();619620    // await usingApi(async (api, privateKeyWrapper) => {621    //   const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);622    //   const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);623    //   await submitTransactionAsync(alice, balanceTx);624625    //   await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);626    //   await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);627628    //   const scheduledId = await makeScheduledId();629    //   const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);630631    //   const waitForBlocks = 5;632    //   await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, scheduledId);633634    //   const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);635    //   const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);636    //   const events = await submitTransactionAsync(alice, sudoTx);637    //   expect(getGenericResult(events).success).to.be.true;638639    //   // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions640    //   await waitNewBlocks(waitForBlocks - 3);641642    //   expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));643    // });644  });645646  it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {647    // const collectionId = await createCollectionExpectSuccess();648    // await setCollectionSponsorExpectSuccess(collectionId, bob.address);649    // await confirmSponsorshipExpectSuccess(collectionId, '//Bob');650651    // await usingApi(async (api, privateKeyWrapper) => {652    //   const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);653654    //   await enablePublicMintingExpectSuccess(alice, collectionId);655    //   await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);656657    //   const bobBalanceBefore = await getFreeBalance(bob);658659    //   const createData = {nft: {const_data: [], variable_data: []}};660    //   const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);661    //   const scheduledId = await makeScheduledId();662663    //   /*const badTransaction = async function () {664    //     await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);665    //   };666    //   await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/667668    //   await expect(scheduleAfter(api, creationTx, zeroBalance, 3, scheduledId, 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);669670    //   expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);671    // });672  });673});
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 {UNIQUE} from './util/helpers';18import {expect, itSub, Pallets, usingPlaygrounds} from './util/playgrounds';19import {IKeyringPair} from '@polkadot/types/types';2021describe('Scheduling token and balance transfers', () => {22  let alice: IKeyringPair;23  let bob: IKeyringPair;24  let charlie: IKeyringPair;2526  before(async () => {27    await usingPlaygrounds(async (_, privateKeyWrapper) => {28      alice = privateKeyWrapper('//Alice');29      bob = privateKeyWrapper('//Bob');30      charlie = privateKeyWrapper('//Charlie');31    });32  });3334  itSub.ifWithPallets('Can delay a transfer of an owned token', [Pallets.Scheduler], async ({helper}) => {35    const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});36    const token = await collection.mintToken(alice);37    const schedulerId = await helper.arrange.makeScheduledId();38    const blocksBeforeExecution = 4;3940    await token.scheduleAfter(schedulerId, blocksBeforeExecution)41      .transfer(alice, {Substrate: bob.address});4243    expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});4445    await helper.wait.newBlocks(blocksBeforeExecution + 1);4647    expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});48  });4950  itSub.ifWithPallets('Can transfer funds periodically', [Pallets.Scheduler], async ({helper}) => {51    const scheduledId = await helper.arrange.makeScheduledId();52    const waitForBlocks = 1;5354    const amount = 1n * UNIQUE;55    const periodic = {56      period: 2,57      repetitions: 2,58    };5960    const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);6162    await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})63      .balance.transferToSubstrate(alice, bob.address, amount);6465    await helper.wait.newBlocks(waitForBlocks + 1);6667    const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);68    expect(bobsBalanceAfterFirst)69      .to.be.equal(70        bobsBalanceBefore + 1n * amount,71        '#1 Balance of the recipient should be increased by 1 * amount',72      );7374    await helper.wait.newBlocks(periodic.period);7576    const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);77    expect(bobsBalanceAfterSecond)78      .to.be.equal(79        bobsBalanceBefore + 2n * amount,80        '#2 Balance of the recipient should be increased by 2 * amount',81      );82  });8384  itSub.ifWithPallets('Can cancel a scheduled operation which has not yet taken effect', [Pallets.Scheduler], async ({helper}) => {85    const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});86    const token = await collection.mintToken(alice);8788    const scheduledId = await helper.arrange.makeScheduledId();89    const waitForBlocks = 4;9091    expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});9293    await token.scheduleAfter(scheduledId, waitForBlocks)94      .transfer(alice, {Substrate: bob.address});9596    await helper.scheduler.cancelScheduled(alice, scheduledId);9798    await helper.wait.newBlocks(waitForBlocks + 1);99100    expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});101  });102103  itSub.ifWithPallets('Can cancel a periodic operation (transfer of funds)', [Pallets.Scheduler], async ({helper}) => {104    const waitForBlocks = 1;105    const periodic = {106      period: 3,107      repetitions: 2,108    };109110    const scheduledId = await helper.arrange.makeScheduledId();111112    const amount = 1n * UNIQUE;113114    const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);115116    await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})117      .balance.transferToSubstrate(alice, bob.address, amount);118119    await helper.wait.newBlocks(waitForBlocks + 1);120121    const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);122123    expect(bobsBalanceAfterFirst)124      .to.be.equal(125        bobsBalanceBefore + 1n * amount,126        '#1 Balance of the recipient should be increased by 1 * amount',127      );128129    await helper.scheduler.cancelScheduled(alice, scheduledId);130    await helper.wait.newBlocks(periodic.period);131132    const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);133    expect(bobsBalanceAfterSecond)134      .to.be.equal(135        bobsBalanceAfterFirst,136        '#2 Balance of the recipient should not be changed',137      );138  });139140  itSub.ifWithPallets('Scheduled tasks are transactional', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {141    const scheduledId = await helper.arrange.makeScheduledId();142    const waitForBlocks = 4;143144    const initTestVal = 42;145    const changedTestVal = 111;146147    await helper.executeExtrinsic(148      alice,149      'api.tx.testUtils.setTestValue',150      [initTestVal],151      true,152    );153154    await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks)155      .executeExtrinsic(156        alice,157        'api.tx.testUtils.setTestValueAndRollback',158        [changedTestVal],159        true,160      );161162    await helper.wait.newBlocks(waitForBlocks + 1);163164    const testVal = (await helper.getApi().query.testUtils.testValue()).toNumber();165    expect(testVal, 'The test value should NOT be commited')166      .to.be.equal(initTestVal);167  });168169  itSub.ifWithPallets('Scheduled tasks should take correct fees', [Pallets.Scheduler, Pallets.TestUtils], async function({helper}) {170    const scheduledId = await helper.arrange.makeScheduledId();171    const waitForBlocks = 4;172    const periodic = {173      period: 2,174      repetitions: 2,175    };176177    const dummyTx = helper.constructApiCall('api.tx.testUtils.justTakeFee', []);178    const scheduledLen = dummyTx.callIndex.length;179180    const expectedScheduledFee = (await helper.getPaymentInfo(alice, dummyTx, scheduledLen))181      .partialFee.toBigInt();182183    await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})184      .executeExtrinsic(alice, 'api.tx.testUtils.justTakeFee', [], true);185186    await helper.wait.newBlocks(1);187188    const aliceInitBalance = await helper.balance.getSubstrate(alice.address);189    let diff;190191    await helper.wait.newBlocks(waitForBlocks);192193    const aliceBalanceAfterFirst = await helper.balance.getSubstrate(alice.address);194    expect(195      aliceBalanceAfterFirst < aliceInitBalance,196      '[after execution #1] Scheduled task should take a fee',197    ).to.be.true;198199    diff = aliceInitBalance - aliceBalanceAfterFirst;200    expect(diff).to.be.equal(201      expectedScheduledFee,202      'Scheduled task should take the right amount of fees',203    );204205    await helper.wait.newBlocks(periodic.period);206207    const aliceBalanceAfterSecond = await helper.balance.getSubstrate(alice.address);208    expect(209      aliceBalanceAfterSecond < aliceBalanceAfterFirst,210      '[after execution #2] Scheduled task should take a fee',211    ).to.be.true;212213    diff = aliceBalanceAfterFirst - aliceBalanceAfterSecond;214    expect(diff).to.be.equal(215      expectedScheduledFee,216      'Scheduled task should take the right amount of fees',217    );218  });219220  // Check if we can cancel a scheduled periodic operation221  // in the same block in which it is running222  itSub.ifWithPallets('Can cancel the periodic sheduled tx when the tx is running', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {223    const currentBlockNumber = await helper.chain.getLatestBlockNumber();224    const blocksBeforeExecution = 10;225    const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;226227    const [228      scheduledId,229      scheduledCancelId,230    ] = await helper.arrange.makeScheduledIds(2);231232    const periodic = {233      period: 5,234      repetitions: 5,235    };236237    const initTestVal = 0;238    const incTestVal = initTestVal + 1;239    const finalTestVal = initTestVal + 2;240241    await helper.executeExtrinsic(242      alice,243      'api.tx.testUtils.setTestValue',244      [initTestVal],245      true,246    );247248    await helper.scheduler.scheduleAt(scheduledId, firstExecutionBlockNumber, {periodic})249      .executeExtrinsic(250        alice,251        'api.tx.testUtils.incTestValue',252        [],253        true,254      );255256    // Cancel the inc tx after 2 executions257    // *in the same block* in which the second execution is scheduled258    await helper.scheduler.scheduleAt(259      scheduledCancelId,260      firstExecutionBlockNumber + periodic.period,261    ).scheduler.cancelScheduled(alice, scheduledId);262263    await helper.wait.newBlocks(blocksBeforeExecution);264265    // execution #0266    expect((await helper.getApi().query.testUtils.testValue()).toNumber())267      .to.be.equal(incTestVal);268269    await helper.wait.newBlocks(periodic.period);270271    // execution #1272    expect((await helper.getApi().query.testUtils.testValue()).toNumber())273      .to.be.equal(finalTestVal);274275    for (let i = 1; i < periodic.repetitions; i++) {276      await helper.wait.newBlocks(periodic.period);277      expect((await helper.getApi().query.testUtils.testValue()).toNumber())278        .to.be.equal(finalTestVal);279    }280  });281282  itSub.ifWithPallets('A scheduled operation can cancel itself', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {283    const scheduledId = await helper.arrange.makeScheduledId();284    const waitForBlocks = 4;285    const periodic = {286      period: 2,287      repetitions: 5,288    };289290    const initTestVal = 0;291    const maxTestVal = 2;292293    await helper.executeExtrinsic(294      alice,295      'api.tx.testUtils.setTestValue',296      [initTestVal],297      true,298    );299300    await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})301      .executeExtrinsic(302        alice,303        'api.tx.testUtils.selfCancelingInc',304        [scheduledId, maxTestVal],305        true,306      );307308    await helper.wait.newBlocks(waitForBlocks + 1);309310    // execution #0311    expect((await helper.getApi().query.testUtils.testValue()).toNumber())312      .to.be.equal(initTestVal + 1);313314    await helper.wait.newBlocks(periodic.period);315316    // execution #1317    expect((await helper.getApi().query.testUtils.testValue()).toNumber())318      .to.be.equal(initTestVal + 2);319320    await helper.wait.newBlocks(periodic.period);321322    // <canceled>323    expect((await helper.getApi().query.testUtils.testValue()).toNumber())324      .to.be.equal(initTestVal + 2);325  });326327  itSub.ifWithPallets('Root can cancel any scheduled operation', [Pallets.Scheduler], async ({helper}) => {328    const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});329    const token = await collection.mintToken(bob);330331    const scheduledId = await helper.arrange.makeScheduledId();332    const waitForBlocks = 4;333334    await token.scheduleAfter(scheduledId, waitForBlocks)335      .transfer(bob, {Substrate: alice.address});336337    await helper.getSudo().scheduler.cancelScheduled(alice, scheduledId);338339    await helper.wait.newBlocks(waitForBlocks + 1);340341    expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});342  });343344  itSub.ifWithPallets('Root can set prioritized scheduled operation', [Pallets.Scheduler], async ({helper}) => {345    const scheduledId = await helper.arrange.makeScheduledId();346    const waitForBlocks = 4;347348    const amount = 42n * UNIQUE;349350    const balanceBefore = await helper.balance.getSubstrate(charlie.address);351352    await helper.getSudo()353      .scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42})354      .balance.forceTransferToSubstrate(alice, bob.address, charlie.address, amount);355356    await helper.wait.newBlocks(waitForBlocks + 1);357358    const balanceAfter = await helper.balance.getSubstrate(charlie.address);359360    expect(balanceAfter > balanceBefore).to.be.true;361362    const diff = balanceAfter - balanceBefore;363    expect(diff).to.be.equal(amount);364  });365366  itSub.ifWithPallets("Root can change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {367    const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});368    const token = await collection.mintToken(bob);369370    const scheduledId = await helper.arrange.makeScheduledId();371    const waitForBlocks = 6;372373    await token.scheduleAfter(scheduledId, waitForBlocks)374      .transfer(bob, {Substrate: alice.address});375376    const priority = 112;377    await helper.getSudo().scheduler.changePriority(alice, scheduledId, priority);378379    const priorityChanged = await helper.wait.event(380      waitForBlocks,381      'scheduler',382      'PriorityChanged',383    );384385    expect(priorityChanged !== null).to.be.true;386    expect(priorityChanged!.event.data[2].toString()).to.be.equal(priority.toString());387  });388389  itSub.ifWithPallets('Prioritized operations executes in valid order', [Pallets.Scheduler], async ({helper}) => {390    const [391      scheduledFirstId,392      scheduledSecondId,393    ] = await helper.arrange.makeScheduledIds(2);394395    const currentBlockNumber = await helper.chain.getLatestBlockNumber();396    const blocksBeforeExecution = 4;397    const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;398399    const prioHigh = 0;400    const prioLow = 255;401402    const periodic = {403      period: 6,404      repetitions: 2,405    };406407    const amount = 1n * UNIQUE;408409    // Scheduler a task with a lower priority first, then with a higher priority410    await helper.getSudo().scheduler.scheduleAt(scheduledFirstId, firstExecutionBlockNumber, {priority: prioLow, periodic})411      .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);412413    await helper.getSudo().scheduler.scheduleAt(scheduledSecondId, firstExecutionBlockNumber, {priority: prioHigh, periodic})414      .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);415416    const capture = await helper.arrange.captureEvents('scheduler', 'Dispatched');417418    await helper.wait.newBlocks(blocksBeforeExecution);419420    // Flip priorities421    await helper.getSudo().scheduler.changePriority(alice, scheduledFirstId, prioHigh);422    await helper.getSudo().scheduler.changePriority(alice, scheduledSecondId, prioLow);423424    await helper.wait.newBlocks(periodic.period);425426    const dispatchEvents = capture.extractCapturedEvents();427    expect(dispatchEvents.length).to.be.equal(4);428429    const dispatchedIds = dispatchEvents.map(r => r.event.data[1].toString());430431    const firstExecuctionIds = [dispatchedIds[0], dispatchedIds[1]];432    const secondExecuctionIds = [dispatchedIds[2], dispatchedIds[3]];433434    expect(firstExecuctionIds[0]).to.be.equal(scheduledSecondId);435    expect(firstExecuctionIds[1]).to.be.equal(scheduledFirstId);436437    expect(secondExecuctionIds[0]).to.be.equal(scheduledFirstId);438    expect(secondExecuctionIds[1]).to.be.equal(scheduledSecondId);439  });440});441442describe('Negative Test: Scheduling', () => {443  let alice: IKeyringPair;444  let bob: IKeyringPair;445446  before(async () => {447    await usingPlaygrounds(async (_, privateKeyWrapper) => {448      alice = privateKeyWrapper('//Alice');449      bob = privateKeyWrapper('//Bob');450    });451  });452453  itSub.ifWithPallets("Can't overwrite a scheduled ID", [Pallets.Scheduler], async ({helper}) => {454    const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});455    const token = await collection.mintToken(alice);456457    const scheduledId = await helper.arrange.makeScheduledId();458    const waitForBlocks = 4;459460    await token.scheduleAfter(scheduledId, waitForBlocks)461      .transfer(alice, {Substrate: bob.address});462463    const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks);464    await expect(scheduled.balance.transferToSubstrate(alice, bob.address, 1n * UNIQUE))465      .to.be.rejectedWith(/scheduler\.FailedToSchedule/);466467    const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);468469    await helper.wait.newBlocks(waitForBlocks + 1);470471    const bobsBalanceAfter = await helper.balance.getSubstrate(bob.address);472473    expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});474    expect(bobsBalanceBefore).to.be.equal(bobsBalanceAfter);475  });476477  itSub.ifWithPallets("Can't cancel an operation which is not scheduled", [Pallets.Scheduler], async ({helper}) => {478    const scheduledId = await helper.arrange.makeScheduledId();479    await expect(helper.scheduler.cancelScheduled(alice, scheduledId))480      .to.be.rejectedWith(/scheduler\.NotFound/);481  });482483  itSub.ifWithPallets("Can't cancel a non-owned scheduled operation", [Pallets.Scheduler], async ({helper}) => {484    const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});485    const token = await collection.mintToken(alice);486487    const scheduledId = await helper.arrange.makeScheduledId();488    const waitForBlocks = 4;489490    await token.scheduleAfter(scheduledId, waitForBlocks)491      .transfer(alice, {Substrate: bob.address});492493    await expect(helper.scheduler.cancelScheduled(bob, scheduledId))494      .to.be.rejectedWith(/BadOrigin/);495496    await helper.wait.newBlocks(waitForBlocks + 1);497498    expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});499  });500501  itSub.ifWithPallets("Regular user can't set prioritized scheduled operation", [Pallets.Scheduler], async ({helper}) => {502    const scheduledId = await helper.arrange.makeScheduledId();503    const waitForBlocks = 4;504505    const amount = 42n * UNIQUE;506507    const balanceBefore = await helper.balance.getSubstrate(bob.address);508509    const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42});510    511    await expect(scheduled.balance.transferToSubstrate(alice, bob.address, amount))512      .to.be.rejectedWith(/BadOrigin/);513514    await helper.wait.newBlocks(waitForBlocks + 1);515516    const balanceAfter = await helper.balance.getSubstrate(bob.address);517518    expect(balanceAfter).to.be.equal(balanceBefore);519  });520521  itSub.ifWithPallets("Regular user can't change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {522    const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});523    const token = await collection.mintToken(bob);524525    const scheduledId = await helper.arrange.makeScheduledId();526    const waitForBlocks = 4;527528    await token.scheduleAfter(scheduledId, waitForBlocks)529      .transfer(bob, {Substrate: alice.address});530531    const priority = 112;532    await expect(helper.scheduler.changePriority(alice, scheduledId, priority))533      .to.be.rejectedWith(/BadOrigin/);534535    const priorityChanged = await helper.wait.event(536      waitForBlocks,537      'scheduler',538      'PriorityChanged',539    );540541    expect(priorityChanged === null).to.be.true;542  });543});544545// Implementation of the functionality tested here was postponed/shelved546describe.skip('Sponsoring scheduling', () => {547  // let alice: IKeyringPair;548  // let bob: IKeyringPair;549550  // before(async() => {551  //   await usingApi(async (_, privateKeyWrapper) => {552  //     alice = privateKeyWrapper('//Alice');553  //     bob = privateKeyWrapper('//Bob');554  //   });555  // });556557  it('Can sponsor scheduling a transaction', async () => {558    // const collectionId = await createCollectionExpectSuccess();559    // await setCollectionSponsorExpectSuccess(collectionId, bob.address);560    // await confirmSponsorshipExpectSuccess(collectionId, '//Bob');561562    // await usingApi(async api => {563    //   const scheduledId = await makeScheduledId();564    //   const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);565566    //   const bobBalanceBefore = await getFreeBalance(bob);567    //   const waitForBlocks = 4;568    //   // no need to wait to check, fees must be deducted on scheduling, immediately569    //   await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, scheduledId);570    //   const bobBalanceAfter = await getFreeBalance(bob);571    //   // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;572    //   expect(bobBalanceAfter < bobBalanceBefore).to.be.true;573    //   // wait for sequentiality matters574    //   await waitNewBlocks(waitForBlocks - 1);575    // });576  });577578  it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {579    // await usingApi(async (api, privateKeyWrapper) => {580    //   // Find an empty, unused account581    //   const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);582583    //   const collectionId = await createCollectionExpectSuccess();584585    //   // Add zeroBalance address to allow list586    //   await enablePublicMintingExpectSuccess(alice, collectionId);587    //   await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);588589    //   // Grace zeroBalance with money, enough to cover future transactions590    //   const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);591    //   await submitTransactionAsync(alice, balanceTx);592593    //   // Mint a fresh NFT594    //   const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');595    //   const scheduledId = await makeScheduledId();596597    //   // Schedule transfer of the NFT a few blocks ahead598    //   const waitForBlocks = 5;599    //   await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, scheduledId);600601    //   // Get rid of the account's funds before the scheduled transaction takes place602    //   const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);603    //   const events = await submitTransactionAsync(zeroBalance, balanceTx2);604    //   expect(getGenericResult(events).success).to.be.true;605    //   /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?606    //   const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);607    //   const events = await submitTransactionAsync(alice, sudoTx);608    //   expect(getGenericResult(events).success).to.be.true;*/609610    //   // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions611    //   await waitNewBlocks(waitForBlocks - 3);612613    //   expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));614    // });615  });616617  it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {618    // const collectionId = await createCollectionExpectSuccess();619620    // await usingApi(async (api, privateKeyWrapper) => {621    //   const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);622    //   const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);623    //   await submitTransactionAsync(alice, balanceTx);624625    //   await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);626    //   await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);627628    //   const scheduledId = await makeScheduledId();629    //   const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);630631    //   const waitForBlocks = 5;632    //   await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, scheduledId);633634    //   const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);635    //   const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);636    //   const events = await submitTransactionAsync(alice, sudoTx);637    //   expect(getGenericResult(events).success).to.be.true;638639    //   // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions640    //   await waitNewBlocks(waitForBlocks - 3);641642    //   expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));643    // });644  });645646  it('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {647    // const collectionId = await createCollectionExpectSuccess();648    // await setCollectionSponsorExpectSuccess(collectionId, bob.address);649    // await confirmSponsorshipExpectSuccess(collectionId, '//Bob');650651    // await usingApi(async (api, privateKeyWrapper) => {652    //   const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);653654    //   await enablePublicMintingExpectSuccess(alice, collectionId);655    //   await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);656657    //   const bobBalanceBefore = await getFreeBalance(bob);658659    //   const createData = {nft: {const_data: [], variable_data: []}};660    //   const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);661    //   const scheduledId = await makeScheduledId();662663    //   /*const badTransaction = async function () {664    //     await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);665    //   };666    //   await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/667668    //   await expect(scheduleAfter(api, creationTx, zeroBalance, 3, scheduledId, 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);669670    //   expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);671    // });672  });673});