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

difftreelog

fix test both scheduling variants - anon and named

Daniel Shiposha2022-11-10parent: #786ff7e.patch.diff
in: master

8 files changed

modifiedtests/src/eth/scheduling.test.tsdiffbeforeafterboth
--- a/tests/src/eth/scheduling.test.ts
+++ b/tests/src/eth/scheduling.test.ts
@@ -15,7 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {expect} from 'chai';
-import {EthUniqueHelper, itEth} from './util';
+import {EthUniqueHelper, itSchedEth} from './util';
 import {Pallets, usingPlaygrounds} from '../util';
 
 describe('Scheduing EVM smart contracts', () => {
@@ -26,11 +26,11 @@
     });
   });
 
-  itEth.ifWithPallets('Successfully schedules and periodically executes an EVM contract', [Pallets.Scheduler], async ({helper, privateKey}) => {
+  itSchedEth.ifWithPallets('Successfully schedules and periodically executes an EVM contract', [Pallets.Scheduler], async (scheduleKind, {helper, privateKey}) => {
     const donor = await privateKey({filename: __filename});
     const [alice] = await helper.arrange.createAccounts([1000n], donor);
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
 
     const deployer = await helper.eth.createAccountWithBalance(alice);
     const flipper = await helper.eth.deployFlipper(deployer);
@@ -44,7 +44,7 @@
       repetitions: 2,
     };
 
-    await helper.scheduler.scheduleAfter<EthUniqueHelper>(scheduledId, waitForBlocks, {periodic})
+    await helper.scheduler.scheduleAfter<EthUniqueHelper>(waitForBlocks, {scheduledId, periodic})
       .eth.sendEVM(
         alice,
         flipper.options.address,
modifiedtests/src/eth/util/index.tsdiffbeforeafterboth
--- a/tests/src/eth/util/index.ts
+++ b/tests/src/eth/util/index.ts
@@ -8,6 +8,7 @@
 
 import {EthUniqueHelper} from './playgrounds/unique.dev';
 import {SilentLogger, SilentConsole} from '../../util/playgrounds/unique.dev';
+import {SchedKind} from '../../util';
 
 export {EthUniqueHelper} from './playgrounds/unique.dev';
 
@@ -81,3 +82,19 @@
 itEthIfWithPallet.only = (name: string, required: string[], cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any) => itEthIfWithPallet(name, required, cb, {only: true});
 itEthIfWithPallet.skip = (name: string, required: string[], cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any) => itEthIfWithPallet(name, required, cb, {skip: true});
 itEth.ifWithPallets = itEthIfWithPallet;
+
+export function itSchedEth(
+  name: string,
+  cb: (schedKind: SchedKind, apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any,
+  opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {},
+) {
+  itEth(name + ' (anonymous scheduling)', (apis) => cb('anon', apis), opts);
+  itEth(name + ' (named scheduling)', (apis) => cb('named', apis), opts);
+}
+itSchedEth.only = (name: string, cb: (schedKind: SchedKind, apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any) => itSchedEth(name, cb, {only: true});
+itSchedEth.skip = (name: string, cb: (schedKind: SchedKind, apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any) => itSchedEth(name, cb, {skip: true});
+itSchedEth.ifWithPallets = itSchedIfWithPallets;
+
+function itSchedIfWithPallets(name: string, required: string[], cb: (schedKind: SchedKind, apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {
+  return itSchedEth(name, cb, {requiredPallets: required, ...opts});
+}
modifiedtests/src/maintenanceMode.seqtest.tsdiffbeforeafterboth
--- a/tests/src/maintenanceMode.seqtest.ts
+++ b/tests/src/maintenanceMode.seqtest.ts
@@ -16,7 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {ApiPromise} from '@polkadot/api';
-import {expect, itSub, Pallets, usingPlaygrounds} from './util';
+import {expect, itSched, itSub, Pallets, usingPlaygrounds} from './util';
 import {itEth} from './eth/util';
 
 async function maintenanceEnabled(api: ApiPromise): Promise<boolean> {
@@ -162,7 +162,7 @@
     await expect(helper.balance.transferToSubstrate(bob, superuser.address, 1n)).to.be.fulfilled;
   });
 
-  itSub.ifWithPallets('MM blocks scheduled calls and the scheduler itself', [Pallets.Scheduler], async ({helper}) => {
+  itSched.ifWithPallets('MM blocks scheduled calls and the scheduler itself', [Pallets.Scheduler], async (scheduleKind, {helper}) => {
     const collection = await helper.nft.mintCollection(bob);
 
     const nftBeforeMM = await collection.mintToken(bob);
@@ -175,23 +175,25 @@
       scheduledIdBunkerThroughMM,
       scheduledIdAttemptDuringMM,
       scheduledIdAfterMM,
-    ] = await helper.arrange.makeScheduledIds(5);
+    ] = scheduleKind == 'named'
+      ? helper.arrange.makeScheduledIds(5)
+      : new Array(5);
 
     const blocksToWait = 6;
 
     // Scheduling works before the maintenance
-    await nftBeforeMM.scheduleAfter(scheduledIdBeforeMM, blocksToWait)
+    await nftBeforeMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdBeforeMM})
       .transfer(bob, {Substrate: superuser.address});
 
     await helper.wait.newBlocks(blocksToWait + 1);
     expect(await nftBeforeMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});
 
     // Schedule a transaction that should occur *during* the maintenance
-    await nftDuringMM.scheduleAfter(scheduledIdDuringMM, blocksToWait)
+    await nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdDuringMM})
       .transfer(bob, {Substrate: superuser.address});
     
     // Schedule a transaction that should occur *after* the maintenance
-    await nftDuringMM.scheduleAfter(scheduledIdBunkerThroughMM, blocksToWait * 2)
+    await nftDuringMM.scheduleAfter(blocksToWait * 2, {scheduledId: scheduledIdBunkerThroughMM})
       .transfer(bob, {Substrate: superuser.address});
 
     await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);
@@ -202,7 +204,7 @@
     expect(await nftDuringMM.getOwner()).to.be.deep.equal({Substrate: bob.address});
 
     // Any attempts to schedule a tx during the MM should be rejected
-    await expect(nftDuringMM.scheduleAfter(scheduledIdAttemptDuringMM, blocksToWait)
+    await expect(nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAttemptDuringMM})
       .transfer(bob, {Substrate: superuser.address}))
       .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);
 
@@ -210,7 +212,7 @@
     expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;
 
     // Scheduling works after the maintenance
-    await nftAfterMM.scheduleAfter(scheduledIdAfterMM, blocksToWait)
+    await nftAfterMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAfterMM})
       .transfer(bob, {Substrate: superuser.address});
     
     await helper.wait.newBlocks(blocksToWait + 1);
modifiedtests/src/scheduler.seqtest.tsdiffbeforeafterboth
--- a/tests/src/scheduler.seqtest.ts
+++ b/tests/src/scheduler.seqtest.ts
@@ -14,7 +14,7 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-import {expect, itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from './util';
+import {expect, itSched, itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from './util';
 import {IKeyringPair} from '@polkadot/types/types';
 import {DevUniqueHelper} from './util/playgrounds/unique.dev';
 
@@ -36,13 +36,19 @@
     });
   });
 
-  itSub('Can delay a transfer of an owned token', async ({helper}) => {
+  beforeEach(async () => {
+    await usingPlaygrounds(async (helper) => {
+      await helper.wait.noScheduledTasks();
+    });
+  });
+
+  itSched('Can delay a transfer of an owned token', async (scheduleKind, {helper}) => {
     const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
     const token = await collection.mintToken(alice);
-    const schedulerId = await helper.arrange.makeScheduledId();
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
     const blocksBeforeExecution = 4;
     
-    await token.scheduleAfter(schedulerId, blocksBeforeExecution)
+    await token.scheduleAfter(blocksBeforeExecution, {scheduledId})
       .transfer(alice, {Substrate: bob.address});
     const executionBlock = await helper.chain.getLatestBlockNumber() + blocksBeforeExecution + 1;
 
@@ -53,8 +59,8 @@
     expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
   });
 
-  itSub('Can transfer funds periodically', async ({helper}) => {
-    const scheduledId = await helper.arrange.makeScheduledId();
+  itSched('Can transfer funds periodically', async (scheduleKind, {helper}) => {
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
     const waitForBlocks = 1;
 
     const amount = 1n * helper.balance.getOneTokenNominal();
@@ -65,7 +71,7 @@
 
     const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
 
-    await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})
+    await helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId, periodic})
       .balance.transferToSubstrate(alice, bob.address, amount);
     const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
@@ -92,12 +98,12 @@
     const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
     const token = await collection.mintToken(alice);
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
     const waitForBlocks = 4;
 
     expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
 
-    await token.scheduleAfter(scheduledId, waitForBlocks)
+    await token.scheduleAfter(waitForBlocks, {scheduledId})
       .transfer(alice, {Substrate: bob.address});
     const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
@@ -115,13 +121,13 @@
       repetitions: 2,
     };
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
 
     const amount = 1n * helper.balance.getOneTokenNominal();
 
     const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
 
-    await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})
+    await helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId, periodic})
       .balance.transferToSubstrate(alice, bob.address, amount);
     const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
@@ -146,11 +152,16 @@
       );
   });
 
-  itSub('scheduler will not insert more tasks than allowed', async ({helper}) => {
+  itSched('scheduler will not insert more tasks than allowed', async (scheduleKind, {helper}) => {
     const maxScheduledPerBlock = 50;
-    const scheduledIds = await helper.arrange.makeScheduledIds(maxScheduledPerBlock + 1);
-    const fillScheduledIds = scheduledIds.slice(0, maxScheduledPerBlock);
-    const extraScheduledId = scheduledIds[maxScheduledPerBlock];
+    let fillScheduledIds = new Array(maxScheduledPerBlock);
+    let extraScheduledId = undefined;
+    
+    if (scheduleKind == 'named') {
+      const scheduledIds = helper.arrange.makeScheduledIds(maxScheduledPerBlock + 1);
+      fillScheduledIds = scheduledIds.slice(0, maxScheduledPerBlock);
+      extraScheduledId = scheduledIds[maxScheduledPerBlock];
+    }
 
     // Since the dev node has Instant Seal,
     // we need a larger gap between the current block and the target one.
@@ -168,12 +179,12 @@
 
     // Fill the target block
     for (let i = 0; i < maxScheduledPerBlock; i++) {
-      await helper.scheduler.scheduleAt(fillScheduledIds[i], executionBlock)
+      await helper.scheduler.scheduleAt(executionBlock, {scheduledId: fillScheduledIds[i]})
         .balance.transferToSubstrate(superuser, bob.address, amount);
     }
 
     // Try to schedule a task into a full block
-    await expect(helper.scheduler.scheduleAt(extraScheduledId, executionBlock)
+    await expect(helper.scheduler.scheduleAt(executionBlock, {scheduledId: extraScheduledId})
       .balance.transferToSubstrate(superuser, bob.address, amount))
       .to.be.rejectedWith(/scheduler\.AgendaIsExhausted/);
 
@@ -187,8 +198,8 @@
     expect(diff).to.be.equal(amount * BigInt(maxScheduledPerBlock));
   });
 
-  itSub.ifWithPallets('Scheduled tasks are transactional', [Pallets.TestUtils], async ({helper}) => {
-    const scheduledId = await helper.arrange.makeScheduledId();
+  itSched.ifWithPallets('Scheduled tasks are transactional', [Pallets.TestUtils], async (scheduleKind, {helper}) => {
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
     const waitForBlocks = 4;
 
     const initTestVal = 42;
@@ -196,7 +207,7 @@
 
     await helper.testUtils.setTestValue(alice, initTestVal);
 
-    await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks)
+    await helper.scheduler.scheduleAfter<DevUniqueHelper>(waitForBlocks, {scheduledId})
       .testUtils.setTestValueAndRollback(alice, changedTestVal);
     const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
@@ -207,8 +218,8 @@
       .to.be.equal(initTestVal);
   });
 
-  itSub.ifWithPallets('Scheduled tasks should take correct fees', [Pallets.TestUtils], async function({helper}) {
-    const scheduledId = await helper.arrange.makeScheduledId();
+  itSched.ifWithPallets('Scheduled tasks should take correct fees', [Pallets.TestUtils], async function(scheduleKind, {helper}) {
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
     const waitForBlocks = 4;
     const periodic = {
       period: 2,
@@ -221,7 +232,7 @@
     const expectedScheduledFee = (await helper.getPaymentInfo(alice, dummyTx, scheduledLen))
       .partialFee.toBigInt();
 
-    await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks, {periodic})
+    await helper.scheduler.scheduleAfter<DevUniqueHelper>(waitForBlocks, {scheduledId, periodic})
       .testUtils.justTakeFee(alice);
     const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
@@ -267,7 +278,7 @@
     const [
       scheduledId,
       scheduledCancelId,
-    ] = await helper.arrange.makeScheduledIds(2);
+    ] = helper.arrange.makeScheduledIds(2);
 
     const periodic = {
       period: 5,
@@ -280,14 +291,14 @@
 
     await helper.testUtils.setTestValue(alice, initTestVal);
 
-    await helper.scheduler.scheduleAt<DevUniqueHelper>(scheduledId, firstExecutionBlockNumber, {periodic})
+    await helper.scheduler.scheduleAt<DevUniqueHelper>(firstExecutionBlockNumber, {scheduledId, periodic})
       .testUtils.incTestValue(alice);
 
     // Cancel the inc tx after 2 executions
     // *in the same block* in which the second execution is scheduled
     await helper.scheduler.scheduleAt(
-      scheduledCancelId,
       firstExecutionBlockNumber + periodic.period,
+      {scheduledId: scheduledCancelId},
     ).scheduler.cancelScheduled(alice, scheduledId);
 
     await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber);
@@ -310,7 +321,7 @@
   });
 
   itSub.ifWithPallets('A scheduled operation can cancel itself', [Pallets.TestUtils], async ({helper}) => {
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
     const waitForBlocks = 4;
     const periodic = {
       period: 2,
@@ -322,7 +333,7 @@
 
     await helper.testUtils.setTestValue(alice, initTestVal);
 
-    await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks, {periodic})
+    await helper.scheduler.scheduleAfter<DevUniqueHelper>(waitForBlocks, {scheduledId, periodic})
       .testUtils.selfCancelingInc(alice, scheduledId, maxTestVal);
     const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
@@ -349,10 +360,10 @@
     const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
     const token = await collection.mintToken(bob);
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
     const waitForBlocks = 4;
 
-    await token.scheduleAfter(scheduledId, waitForBlocks)
+    await token.scheduleAfter(waitForBlocks, {scheduledId})
       .transfer(bob, {Substrate: alice.address});
     const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
@@ -363,8 +374,8 @@
     expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
   });
 
-  itSub('Root can set prioritized scheduled operation', async ({helper}) => {
-    const scheduledId = await helper.arrange.makeScheduledId();
+  itSched('Root can set prioritized scheduled operation', async (scheduleKind, {helper}) => {
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
     const waitForBlocks = 4;
 
     const amount = 42n * helper.balance.getOneTokenNominal();
@@ -372,7 +383,7 @@
     const balanceBefore = await helper.balance.getSubstrate(charlie.address);
 
     await helper.getSudo()
-      .scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42})
+      .scheduler.scheduleAfter(waitForBlocks, {scheduledId, priority: 42})
       .balance.forceTransferToSubstrate(superuser, bob.address, charlie.address, amount);
     const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
@@ -390,10 +401,10 @@
     const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
     const token = await collection.mintToken(bob);
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
     const waitForBlocks = 6;
 
-    await token.scheduleAfter(scheduledId, waitForBlocks)
+    await token.scheduleAfter(waitForBlocks, {scheduledId})
       .transfer(bob, {Substrate: alice.address});
     const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
@@ -419,7 +430,7 @@
     const [
       scheduledFirstId,
       scheduledSecondId,
-    ] = await helper.arrange.makeScheduledIds(2);
+    ] = helper.arrange.makeScheduledIds(2);
 
     const currentBlockNumber = await helper.chain.getLatestBlockNumber();
     const blocksBeforeExecution = 6;
@@ -436,11 +447,17 @@
     const amount = 1n * helper.balance.getOneTokenNominal();
 
     // Scheduler a task with a lower priority first, then with a higher priority
-    await helper.getSudo().scheduler.scheduleAt(scheduledFirstId, firstExecutionBlockNumber, {priority: prioLow, periodic})
-      .balance.forceTransferToSubstrate(superuser, alice.address, bob.address, amount);
+    await helper.getSudo().scheduler.scheduleAt(firstExecutionBlockNumber, {
+      scheduledId: scheduledFirstId,
+      priority: prioLow,
+      periodic,
+    }).balance.forceTransferToSubstrate(superuser, alice.address, bob.address, amount);
 
-    await helper.getSudo().scheduler.scheduleAt(scheduledSecondId, firstExecutionBlockNumber, {priority: prioHigh, periodic})
-      .balance.forceTransferToSubstrate(superuser, alice.address, bob.address, amount);
+    await helper.getSudo().scheduler.scheduleAt(firstExecutionBlockNumber, {
+      scheduledId: scheduledSecondId,
+      priority: prioHigh,
+      periodic,
+    }).balance.forceTransferToSubstrate(superuser, alice.address, bob.address, amount);
 
     const capture = await helper.arrange.captureEvents('scheduler', 'Dispatched');
 
@@ -467,13 +484,15 @@
     expect(secondExecuctionIds[1]).to.be.equal(scheduledSecondId);
   });
 
-  itSub('Periodic operations always can be rescheduled', async ({helper}) => {
+  itSched('Periodic operations always can be rescheduled', async (scheduleKind, {helper}) => {
     const maxScheduledPerBlock = 50;
     const numFilledBlocks = 3;
-    const ids = await helper.arrange.makeScheduledIds(numFilledBlocks * maxScheduledPerBlock + 1);
-    const periodicId = ids[0];
+    const ids = helper.arrange.makeScheduledIds(numFilledBlocks * maxScheduledPerBlock + 1);
+    const periodicId = scheduleKind == 'named' ? ids[0] : undefined;
     const fillIds = ids.slice(1);
 
+    const fillScheduleFn = scheduleKind == 'named' ? 'scheduleNamed' : 'schedule';
+
     const initTestVal = 0;
     const firstExecTestVal = 1;
     const secondExecTestVal = 2;
@@ -498,15 +517,22 @@
         const scheduledTx = helper.constructApiCall('api.tx.balances.transfer', [bob.address, 1n]);
 
         const when = firstExecutionBlockNumber + period + offset;
-        const tx = helper.constructApiCall('api.tx.scheduler.scheduleNamed', [fillIds[i + offset * maxScheduledPerBlock], when, null, null, scheduledTx]);
+        const mandatoryArgs = [when, null, null, scheduledTx];
+        const scheduleArgs = scheduleKind == 'named'
+          ? [fillIds[i + offset * maxScheduledPerBlock], ...mandatoryArgs]
+          : mandatoryArgs;
+
+        const tx = helper.constructApiCall(`api.tx.scheduler.${fillScheduleFn}`, scheduleArgs);
 
         txs.push(tx);
       }
     }
     await helper.executeExtrinsic(alice, 'api.tx.testUtils.batchAll', [txs], true);
 
-    await helper.scheduler.scheduleAt<DevUniqueHelper>(periodicId, firstExecutionBlockNumber, {periodic})
-      .testUtils.incTestValue(alice);
+    await helper.scheduler.scheduleAt<DevUniqueHelper>(firstExecutionBlockNumber, {
+      scheduledId: periodicId,
+      periodic,
+    }).testUtils.incTestValue(alice);
 
     await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber);
     expect(await helper.testUtils.testValue()).to.be.equal(firstExecTestVal);
@@ -522,12 +548,12 @@
     expect(await helper.testUtils.testValue()).to.be.equal(secondExecTestVal);
   });
 
-  itSub('scheduled operations does not change nonce', async ({helper}) => {
-    const scheduledId = await helper.arrange.makeScheduledId();
+  itSched('scheduled operations does not change nonce', async (scheduleKind, {helper}) => {
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
     const blocksBeforeExecution = 4;
 
     await helper.scheduler
-      .scheduleAfter<DevUniqueHelper>(scheduledId, blocksBeforeExecution)
+      .scheduleAfter<DevUniqueHelper>(blocksBeforeExecution, {scheduledId})
       .balance.transferToSubstrate(alice, bob.address, 1n);
     const executionBlock = await helper.chain.getLatestBlockNumber() + blocksBeforeExecution + 1;
 
@@ -560,14 +586,14 @@
     const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
     const token = await collection.mintToken(alice);
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
     const waitForBlocks = 4;
 
-    await token.scheduleAfter(scheduledId, waitForBlocks)
+    await token.scheduleAfter(waitForBlocks, {scheduledId})
       .transfer(alice, {Substrate: bob.address});
     const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
-    const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks);
+    const scheduled = helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId});
     await expect(scheduled.balance.transferToSubstrate(alice, bob.address, 1n * helper.balance.getOneTokenNominal()))
       .to.be.rejectedWith(/scheduler\.FailedToSchedule/);
 
@@ -582,7 +608,7 @@
   });
 
   itSub("Can't cancel an operation which is not scheduled", async ({helper}) => {
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
     await expect(helper.scheduler.cancelScheduled(alice, scheduledId))
       .to.be.rejectedWith(/scheduler\.NotFound/);
   });
@@ -591,10 +617,10 @@
     const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
     const token = await collection.mintToken(alice);
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
     const waitForBlocks = 4;
 
-    await token.scheduleAfter(scheduledId, waitForBlocks)
+    await token.scheduleAfter(waitForBlocks, {scheduledId})
       .transfer(alice, {Substrate: bob.address});
     const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
@@ -606,15 +632,15 @@
     expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
   });
 
-  itSub("Regular user can't set prioritized scheduled operation", async ({helper}) => {
-    const scheduledId = await helper.arrange.makeScheduledId();
+  itSched("Regular user can't set prioritized scheduled operation", async (scheduleKind, {helper}) => {
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
     const waitForBlocks = 4;
 
     const amount = 42n * helper.balance.getOneTokenNominal();
 
     const balanceBefore = await helper.balance.getSubstrate(bob.address);
 
-    const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42});
+    const scheduled = helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId, priority: 42});
     
     await expect(scheduled.balance.transferToSubstrate(alice, bob.address, amount))
       .to.be.rejectedWith(/BadOrigin/);
@@ -632,10 +658,10 @@
     const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
     const token = await collection.mintToken(bob);
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
     const waitForBlocks = 4;
 
-    await token.scheduleAfter(scheduledId, waitForBlocks)
+    await token.scheduleAfter(waitForBlocks, {scheduledId})
       .transfer(bob, {Substrate: alice.address});
 
     const priority = 112;
modifiedtests/src/util/index.tsdiffbeforeafterboth
--- a/tests/src/util/index.ts
+++ b/tests/src/util/index.ts
@@ -130,6 +130,24 @@
 itSubIfWithPallet.skip = (name: string, required: string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSubIfWithPallet(name, required, cb, {skip: true});
 itSub.ifWithPallets = itSubIfWithPallet;
 
+export type SchedKind = 'anon' | 'named';
+
+export function itSched(
+  name: string,
+  cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any,
+  opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {},
+) {
+  itSub(name + ' (anonymous scheduling)', (apis) => cb('anon', apis), opts);
+  itSub(name + ' (named scheduling)', (apis) => cb('named', apis), opts);
+}
+itSched.only = (name: string, cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSched(name, cb, {only: true});
+itSched.skip = (name: string, cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSched(name, cb, {skip: true});
+itSched.ifWithPallets = itSchedIfWithPallets;
+
+function itSchedIfWithPallets(name: string, required: string[], cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {
+  return itSched(name, cb, {requiredPallets: required, ...opts});
+}
+
 export function describeXCM(title: string, fn: (this: Mocha.Suite) => void, opts: {skip?: boolean} = {}) {
   (process.env.RUN_XCM_TESTS && !opts.skip
     ? describe
modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -172,6 +172,7 @@
 }
 
 export interface ISchedulerOptions {
+  scheduledId?: string,
   priority?: number,
   periodic?: {
     period: number,
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
before · tests/src/util/playgrounds/unique.dev.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034import {stringToU8a} from '@polkadot/util';5import {encodeAddress, mnemonicGenerate} from '@polkadot/util-crypto';6import {UniqueHelper, MoonbeamHelper, ChainHelperBase, AcalaHelper, RelayHelper, WestmintHelper} from './unique';7import {ApiPromise, Keyring, WsProvider} from '@polkadot/api';8import * as defs from '../../interfaces/definitions';9import {IKeyringPair} from '@polkadot/types/types';10import {EventRecord} from '@polkadot/types/interfaces';11import {ICrossAccountId, TSigner} from './types';12import {FrameSystemEventRecord} from '@polkadot/types/lookup';13import {VoidFn} from '@polkadot/api/types';14import {Pallets} from '..';1516export class SilentLogger {17  log(_msg: any, _level: any): void { }18  level = {19    ERROR: 'ERROR' as const,20    WARNING: 'WARNING' as const,21    INFO: 'INFO' as const,22  };23}2425export class SilentConsole {26  // TODO: Remove, this is temporary: Filter unneeded API output27  // (Jaco promised it will be removed in the next version)28  consoleErr: any;29  consoleLog: any;30  consoleWarn: any;3132  constructor() {33    this.consoleErr = console.error;34    this.consoleLog = console.log;35    this.consoleWarn = console.warn;36  }3738  enable() {  39    const outFn = (printer: any) => (...args: any[]) => {40      for (const arg of args) {41        if (typeof arg !== 'string')42          continue;43        if (arg.includes('1000:: Normal connection closure') || arg.includes('Not decorating unknown runtime apis:') || arg.includes('RPC methods not decorated:') || arg === 'Normal connection closure')44          return;45      }46      printer(...args);47    };48  49    console.error = outFn(this.consoleErr.bind(console));50    console.log = outFn(this.consoleLog.bind(console));51    console.warn = outFn(this.consoleWarn.bind(console));52  }5354  disable() {55    console.error = this.consoleErr;56    console.log = this.consoleLog;57    console.warn = this.consoleWarn;58  }59}6061export class DevUniqueHelper extends UniqueHelper {62  /**63   * Arrange methods for tests64   */65  arrange: ArrangeGroup;66  wait: WaitGroup;67  admin: AdminGroup;68  testUtils: TestUtilGroup;6970  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {71    options.helperBase = options.helperBase ?? DevUniqueHelper;7273    super(logger, options);74    this.arrange = new ArrangeGroup(this);75    this.wait = new WaitGroup(this);76    this.admin = new AdminGroup(this);77    this.testUtils = new TestUtilGroup(this);78  }7980  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {81    const wsProvider = new WsProvider(wsEndpoint);82    this.api = new ApiPromise({83      provider: wsProvider,84      signedExtensions: {85        ContractHelpers: {86          extrinsic: {},87          payload: {},88        },89        CheckMaintenance: {90          extrinsic: {},91          payload: {},92        },93        FakeTransactionFinalizer: {94          extrinsic: {},95          payload: {},96        },97      },98      rpc: {99        unique: defs.unique.rpc,100        appPromotion: defs.appPromotion.rpc,101        rmrk: defs.rmrk.rpc,102        eth: {103          feeHistory: {104            description: 'Dummy',105            params: [],106            type: 'u8',107          },108          maxPriorityFeePerGas: {109            description: 'Dummy',110            params: [],111            type: 'u8',112          },113        },114      },115    });116    await this.api.isReadyOrError;117    this.network = await UniqueHelper.detectNetwork(this.api);118  }119}120121export class DevRelayHelper extends RelayHelper {}122123export class DevWestmintHelper extends WestmintHelper {124  wait: WaitGroup;125126  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {127    options.helperBase = options.helperBase ?? DevWestmintHelper;128129    super(logger, options);130    this.wait = new WaitGroup(this);131  }132}133134export class DevMoonbeamHelper extends MoonbeamHelper {135  account: MoonbeamAccountGroup;136  wait: WaitGroup;137138  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {139    options.helperBase = options.helperBase ?? DevMoonbeamHelper;140141    super(logger, options);142    this.account = new MoonbeamAccountGroup(this);143    this.wait = new WaitGroup(this);144  }145}146147export class DevMoonriverHelper extends DevMoonbeamHelper {}148149export class DevAcalaHelper extends AcalaHelper {150  wait: WaitGroup;151152  constructor(logger: { log: (msg: any, level: any) => void, level: any }, options: {[key: string]: any} = {}) {153    options.helperBase = options.helperBase ?? DevAcalaHelper;154155    super(logger, options);156    this.wait = new WaitGroup(this);157  }158}159160export class DevKaruraHelper extends DevAcalaHelper {}161162class ArrangeGroup {163  helper: DevUniqueHelper;164165  scheduledIdSlider = 0;166167  constructor(helper: DevUniqueHelper) {168    this.helper = helper;169  }170171  /**172   * Generates accounts with the specified UNQ token balance 173   * @param balances balances for generated accounts. Each balance will be multiplied by the token nominal.174   * @param donor donor account for balances175   * @returns array of newly created accounts176   * @example const [acc1, acc2, acc3] = await createAccounts([0n, 10n, 20n], donor); 177   */178  createAccounts = async (balances: bigint[], donor: IKeyringPair): Promise<IKeyringPair[]> => {179    let nonce = await this.helper.chain.getNonce(donor.address);180    const wait = new WaitGroup(this.helper);181    const ss58Format = this.helper.chain.getChainProperties().ss58Format;182    const tokenNominal = this.helper.balance.getOneTokenNominal();183    const transactions = [];184    const accounts: IKeyringPair[] = [];185    for (const balance of balances) {186      const recipient = this.helper.util.fromSeed(mnemonicGenerate(), ss58Format);187      accounts.push(recipient);188      if (balance !== 0n) {189        const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recipient.address}, balance * tokenNominal]);190        transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));191        nonce++;192      }193    }194195    await Promise.all(transactions).catch(_e => {});196    197    //#region TODO remove this region, when nonce problem will be solved198    const checkBalances = async () => {199      let isSuccess = true;200      for (let i = 0; i < balances.length; i++) {201        const balance = await this.helper.balance.getSubstrate(accounts[i].address);202        if (balance !== balances[i] * tokenNominal) {203          isSuccess = false;204          break;205        }206      }207      return isSuccess;208    };209210    let accountsCreated = false;211    const maxBlocksChecked = await this.helper.arrange.isDevNode() ? 50 : 5;212    // checkBalances retry up to 5-50 blocks213    for (let index = 0; index < maxBlocksChecked; index++) {214      accountsCreated = await checkBalances();215      if(accountsCreated) break;216      await wait.newBlocks(1);217    }218219    if (!accountsCreated) throw Error('Accounts generation failed');220    //#endregion221222    return accounts;223  };224225  // TODO combine this method and createAccounts into one226  createCrowd = async (accountsToCreate: number, withBalance: bigint, donor: IKeyringPair): Promise<IKeyringPair[]> => {  227    const createAsManyAsCan = async () => {228      let transactions: any = [];229      const accounts: IKeyringPair[] = [];230      let nonce = await this.helper.chain.getNonce(donor.address);231      const tokenNominal = this.helper.balance.getOneTokenNominal();232      for (let i = 0; i < accountsToCreate; i++) {233        if (i === 500) { // if there are too many accounts to create234          await Promise.allSettled(transactions); // wait while first 500 (should be 100 for devnode) tx will be settled 235          transactions = []; //236          nonce = await this.helper.chain.getNonce(donor.address); // update nonce 237        }238        const recepient = this.helper.util.fromSeed(mnemonicGenerate());239        accounts.push(recepient);240        if (withBalance !== 0n) {241          const tx = this.helper.constructApiCall('api.tx.balances.transfer', [{Id: recepient.address}, withBalance * tokenNominal]);242          transactions.push(this.helper.signTransaction(donor, tx, {nonce}, 'account generation'));243          nonce++;244        }245      }246      247      const fullfilledAccounts = [];248      await Promise.allSettled(transactions);249      for (const account of accounts) {250        const accountBalance = await this.helper.balance.getSubstrate(account.address);251        if (accountBalance === withBalance * tokenNominal) {252          fullfilledAccounts.push(account);253        }254      }255      return fullfilledAccounts;256    };257258    259    const crowd: IKeyringPair[] = [];260    // do up to 5 retries261    for (let index = 0; index < 5 && accountsToCreate !== 0; index++) {262      const asManyAsCan = await createAsManyAsCan();263      crowd.push(...asManyAsCan);264      accountsToCreate -= asManyAsCan.length;265    }266267    if (accountsToCreate !== 0) throw Error(`Crowd generation failed: ${accountsToCreate} accounts left`);268269    return crowd;270  };271272  isDevNode = async () => {273    let blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();274    if (blockNumber == 0) {275      await this.helper.wait.newBlocks(1); 276      blockNumber = (await this.helper.callRpc('api.query.system.number')).toJSON();277    }278    const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])]);279    const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber - 1])]);280    const findCreationDate = (block: any) => {281      const humanBlock = block.toHuman();282      let date;283      humanBlock.block.extrinsics.forEach((ext: any) => {284        if(ext.method.section === 'timestamp') {285          date = Number(ext.method.args.now.replaceAll(',', ''));286        }287      });288      return date;289    };290    const block1date = await findCreationDate(block1);291    const block2date = await findCreationDate(block2);292    if(block2date! - block1date! < 9000) return true;293  };294  295  async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {296    const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);297    let balance = await this.helper.balance.getSubstrate(address); 298    299    await promise();300    301    balance -= await this.helper.balance.getSubstrate(address);302    303    return balance;304  }305306  calculatePalletAddress(palletId: any) {307    const address = stringToU8a(('modl' + palletId).padEnd(32, '\0'));308    return encodeAddress(address);309  }310311  async makeScheduledIds(num: number): Promise<string[]> {312    await this.helper.wait.noScheduledTasks();313314    function makeId(slider: number) {315      const scheduledIdSize = 64;316      const hexId = slider.toString(16);317      const prefixSize = scheduledIdSize - hexId.length;318319      const scheduledId = '0x' + '0'.repeat(prefixSize) + hexId;320321      return scheduledId;  322    }323324    const ids = [];325    for (let i = 0; i < num; i++) {326      ids.push(makeId(this.scheduledIdSlider));327      this.scheduledIdSlider += 1;328    }329330    return ids;331  }332333  async makeScheduledId(): Promise<string> {334    return (await this.makeScheduledIds(1))[0];335  }336337  async captureEvents(eventSection: string, eventMethod: string): Promise<EventCapture> {338    const capture = new EventCapture(this.helper, eventSection, eventMethod);339    await capture.startCapture();340341    return capture;342  }343}344345class MoonbeamAccountGroup {346  helper: MoonbeamHelper;347348  keyring: Keyring;349  _alithAccount: IKeyringPair;350  _baltatharAccount: IKeyringPair;351  _dorothyAccount: IKeyringPair;352353  constructor(helper: MoonbeamHelper) {354    this.helper = helper;355356    this.keyring = new Keyring({type: 'ethereum'});357    const alithPrivateKey = '0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133';358    const baltatharPrivateKey = '0x8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b';359    const dorothyPrivateKey = '0x39539ab1876910bbf3a223d84a29e28f1cb4e2e456503e7e91ed39b2e7223d68';360361    this._alithAccount = this.keyring.addFromUri(alithPrivateKey, undefined, 'ethereum');362    this._baltatharAccount = this.keyring.addFromUri(baltatharPrivateKey, undefined, 'ethereum');363    this._dorothyAccount = this.keyring.addFromUri(dorothyPrivateKey, undefined, 'ethereum');364  }365366  alithAccount() {367    return this._alithAccount;368  }369370  baltatharAccount() {371    return this._baltatharAccount;372  }373374  dorothyAccount() {375    return this._dorothyAccount;376  }377378  create() {379    return this.keyring.addFromUri(mnemonicGenerate());380  }381}382383class WaitGroup {384  helper: ChainHelperBase;385386  constructor(helper: ChainHelperBase) {387    this.helper = helper;388  }389390  sleep(milliseconds: number) {391    return new Promise((resolve) => setTimeout(resolve, milliseconds));392  }393394  private async waitWithTimeout(promise: Promise<any>, timeout: number) {395    let isBlock = false;396    promise.then(() => isBlock = true).catch(() => isBlock = true);397    let totalTime = 0;398    const step = 100;399    while(!isBlock) {400      await this.sleep(step);401      totalTime += step;402      if(totalTime >= timeout) throw Error('Blocks production failed');403    }404    return promise;405  }406407  /**408   * Wait for specified number of blocks409   * @param blocksCount number of blocks to wait410   * @returns 411   */412  async newBlocks(blocksCount = 1, timeout?: number): Promise<void> {413    timeout = timeout ?? blocksCount * 60_000;414    // eslint-disable-next-line no-async-promise-executor415    const promise = new Promise<void>(async (resolve) => {416      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {417        if (blocksCount > 0) {418          blocksCount--;419        } else {420          unsubscribe();421          resolve();422        }423      });424    });425    await this.waitWithTimeout(promise, timeout);426    return promise;427  }428429  async forParachainBlockNumber(blockNumber: bigint | number, timeout?: number) {430    timeout = timeout ?? 30 * 60 * 1000;431    // eslint-disable-next-line no-async-promise-executor432    const promise = new Promise<void>(async (resolve) => {433      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads((data: any) => {434        if (data.number.toNumber() >= blockNumber) {435          unsubscribe();436          resolve();437        }438      });439    });440    await this.waitWithTimeout(promise, timeout);441    return promise;442  }443  444  async forRelayBlockNumber(blockNumber: bigint | number, timeout?: number) {445    timeout = timeout ?? 30 * 60 * 1000;446    // eslint-disable-next-line no-async-promise-executor447    const promise = new Promise<void>(async (resolve) => {448      const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData((data: any) => {449        if (data.value.relayParentNumber.toNumber() >= blockNumber) {450          // @ts-ignore451          unsubscribe();452          resolve();453        }454      });455    });456    await this.waitWithTimeout(promise, timeout);457    return promise;458  }459460  noScheduledTasks() {461    const api = this.helper.getApi();462    463    // eslint-disable-next-line no-async-promise-executor464    const promise = new Promise<void>(async resolve => {465      const unsubscribe = await api.rpc.chain.subscribeNewHeads(async () => {466        const areThereScheduledTasks = await api.query.scheduler.lookup.entries();467468        if(areThereScheduledTasks.length == 0) {469          unsubscribe();470          resolve();471        }472      }); 473    });474475    return promise;476  }477478  event(maxBlocksToWait: number, eventSection: string, eventMethod: string) {479    // eslint-disable-next-line no-async-promise-executor480    const promise = new Promise<EventRecord | null>(async (resolve) => {481      const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async header => {482        const blockNumber = header.number.toHuman();483        const blockHash = header.hash;484        const eventIdStr = `${eventSection}.${eventMethod}`;485        const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;486  487        this.helper.logger.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);488  489        const apiAt = await this.helper.getApi().at(blockHash);490        const eventRecords = (await apiAt.query.system.events()) as any;491  492        const neededEvent = eventRecords.toArray().find((r: FrameSystemEventRecord) => {493          return r.event.section == eventSection && r.event.method == eventMethod;494        });495  496        if (neededEvent) {497          unsubscribe();498          resolve(neededEvent);499        } else if (maxBlocksToWait > 0) {500          maxBlocksToWait--;501        } else {502          this.helper.logger.log(`Event \`${eventIdStr}\` is NOT found`);503          unsubscribe();504          resolve(null);505        }506      });507    });508    return promise;509  }510}511512class TestUtilGroup {513  helper: DevUniqueHelper;514515  constructor(helper: DevUniqueHelper) {516    this.helper = helper;517  }518519  async enable() {520    if (this.helper.fetchMissingPalletNames([Pallets.TestUtils]).length != 0) {521      return;522    }523524    const signer = this.helper.util.fromSeed('//Alice');525    await this.helper.getSudo<DevUniqueHelper>().executeExtrinsic(signer, 'api.tx.testUtils.enable', [], true);526  }527528  async setTestValue(signer: TSigner, testVal: number) {529    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValue', [testVal], true);530  }531532  async incTestValue(signer: TSigner) {533    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.incTestValue', [], true);534  }535536  async setTestValueAndRollback(signer: TSigner, testVal: number) {537    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValueAndRollback', [testVal], true);538  }539540  async testValue(blockIdx?: number) {541    const api = blockIdx542      ? await this.helper.getApi().at(await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockIdx]))543      : this.helper.getApi();544545    return (await api.query.testUtils.testValue()).toJSON();546  }547548  async justTakeFee(signer: TSigner) {549    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.justTakeFee', [], true);550  }551552  async selfCancelingInc(signer: TSigner, scheduledId: string, maxTestVal: number) {553    await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.selfCancelingInc', [scheduledId, maxTestVal], true);554  }555}556557class EventCapture {558  helper: DevUniqueHelper;559  eventSection: string;560  eventMethod: string;561  events: EventRecord[] = [];562  unsubscribe: VoidFn | null = null;563564  constructor(565    helper: DevUniqueHelper,566    eventSection: string,567    eventMethod: string,568  ) {569    this.helper = helper;570    this.eventSection = eventSection;571    this.eventMethod = eventMethod;572  }573574  async startCapture() {575    this.stopCapture();576    this.unsubscribe = (await this.helper.getApi().query.system.events((eventRecords: FrameSystemEventRecord[]) => {577      const newEvents = eventRecords.filter(r => {578        return r.event.section == this.eventSection && r.event.method == this.eventMethod;579      });580581      this.events.push(...newEvents);582    })) as any;583  }584585  stopCapture() {586    if (this.unsubscribe !== null) {587      this.unsubscribe();588    }589  }590591  extractCapturedEvents() {592    return this.events;593  }594}595596class AdminGroup {597  helper: UniqueHelper;598599  constructor(helper: UniqueHelper) {600    this.helper = helper;601  }602603  async payoutStakers(signer: IKeyringPair, stakersToPayout: number) {604    const payoutResult = await this.helper.executeExtrinsic(signer, 'api.tx.appPromotion.payoutStakers', [stakersToPayout], true);605    return payoutResult.result.events.filter(e => e.event.method === 'StakingRecalculation').map(e => {606      return {607        staker: e.event.data[0].toString(),608        stake: e.event.data[1].toBigInt(),609        payout: e.event.data[2].toBigInt(),610      };611    });612  }613}
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -2560,24 +2560,21 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);
+    return this.schedule<T>('schedule', executionBlockNumber, options);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);
+    return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);
   }
 
   schedule<T extends UniqueHelper>(
-    scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',
-    scheduledId: string,
+    scheduleFn: 'schedule' | 'scheduleAfter',
     blocksNum: number,
     options: ISchedulerOptions = {},
   ) {
@@ -2585,7 +2582,6 @@
     const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);
     return this.helper.clone(ScheduledHelperType, {
       scheduleFn,
-      scheduledId,
       blocksNum,
       options,
     }) as T;
@@ -2874,16 +2870,14 @@
 // eslint-disable-next-line @typescript-eslint/naming-convention
 function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {
   return class extends Base {
-    scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';
-    scheduledId: string;
+    scheduleFn: 'schedule' | 'scheduleAfter';
     blocksNum: number;
     options: ISchedulerOptions;
 
     constructor(...args: any[]) {
       const logger = args[0] as ILogger;
       const options = args[1] as {
-        scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',
-        scheduledId: string,
+        scheduleFn: 'schedule' | 'scheduleAfter',
         blocksNum: number,
         options: ISchedulerOptions
       };
@@ -2891,25 +2885,42 @@
       super(logger);
 
       this.scheduleFn = options.scheduleFn;
-      this.scheduledId = options.scheduledId;
       this.blocksNum = options.blocksNum;
       this.options = options.options;
     }
 
     executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {
       const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);
-      const extrinsic = 'api.tx.scheduler.' +  this.scheduleFn;
+      
+      const mandatorySchedArgs = [
+        this.blocksNum,
+        this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,
+        this.options.priority ?? null,
+        scheduledTx,
+      ];
+      
+      let schedArgs;
+      let scheduleFn;
+
+      if (this.options.scheduledId) {
+        schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];
 
+        if (this.scheduleFn == 'schedule') {
+          scheduleFn = 'scheduleNamed';
+        } else if (this.scheduleFn == 'scheduleAfter') {
+          scheduleFn = 'scheduleNamedAfter';
+        }
+      } else {
+        schedArgs = mandatorySchedArgs;
+        scheduleFn = this.scheduleFn;
+      }
+
+      const extrinsic = 'api.tx.scheduler.' +  scheduleFn;
+
       return super.executeExtrinsic(
         sender,
         extrinsic,
-        [
-          this.scheduledId,
-          this.blocksNum,
-          this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,
-          this.options.priority ?? null,
-          scheduledTx,
-        ],
+        schedArgs,
         expectSuccess,
       );
     }
@@ -3046,20 +3057,18 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);
     return new UniqueBaseCollection(this.collectionId, scheduledHelper);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);
     return new UniqueBaseCollection(this.collectionId, scheduledHelper);
   }
 
@@ -3155,20 +3164,18 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);
     return new UniqueNFTCollection(this.collectionId, scheduledHelper);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);
     return new UniqueNFTCollection(this.collectionId, scheduledHelper);
   }
 
@@ -3260,20 +3267,18 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);
     return new UniqueRFTCollection(this.collectionId, scheduledHelper);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);
     return new UniqueRFTCollection(this.collectionId, scheduledHelper);
   }
 
@@ -3329,20 +3334,18 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);
     return new UniqueFTCollection(this.collectionId, scheduledHelper);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);
     return new UniqueFTCollection(this.collectionId, scheduledHelper);
   }
 
@@ -3388,20 +3391,18 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);
     return new UniqueBaseToken(this.tokenId, scheduledCollection);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);
     return new UniqueBaseToken(this.tokenId, scheduledCollection);
   }
 
@@ -3468,20 +3469,18 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);
     return new UniqueNFToken(this.tokenId, scheduledCollection);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);
     return new UniqueNFToken(this.tokenId, scheduledCollection);
   }
 
@@ -3543,20 +3542,18 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);
     return new UniqueRFToken(this.tokenId, scheduledCollection);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);
     return new UniqueRFToken(this.tokenId, scheduledCollection);
   }